|
var __defProp=Object.defineProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __defProp2=Object.defineProperty,__name2=__name((target,value)=>__defProp2(target,"name",{value,configurable:!0}),"__name");import{u as uniq,i as isNil,c as compact,a as isObject$1,T as Tagify,p as pick,m as mapToObj,b as mapValues$1,o as omit,k as keys,s as sortBy,d as sumBy,g as groupBy$1,D as Duration,e as isEmpty,f as equals,S as Sortable,h as pipe,j as map,l as filter,n as uniqBy,M as MiniSearch,q as difference,z as zipWith,r as meanBy,E as EditorView,t as basicSetup,v as json,w as linter,x as keymap,y as indentWithTab,A as autocompletion,B as syntaxTree,C as jsonParseLinter,F as fromPairs,G as maxBy,U as UUIDv5,H as range,I as flatMapToObj,J as Interval,K as DateTime,L as noUiSlider,P as PipsMode,N as findLast,O as intersection,Q as omitBy}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")})}},MAGIC_TRADITIONS=new Set(["arcane","divine","occult","primal"]);class BaseStatistic{static{__name(this,"BaseStatistic")}static{__name2(this,"BaseStatistic")}actor;slug;label;data;domains;modifiers;constructor(actor,data){this.actor=actor,this.slug=data.slug,this.label=game.i18n.localize(data.label).trim(),this.data={...data},this.domains=uniq(data.domains??=[]);const modifiers=[data.modifiers??[],extractModifiers(this.actor.synthetics,this.domains)].flat();if(this.modifiers=new StatisticModifier("",modifiers).modifiers.map(m=>m.clone()),this.domains.length>0){const options=this.createRollOptions();for(const modifier of this.modifiers)modifier.test(options)}}createRollOptions(domains=this.domains){return new Set(this.actor.getRollOptions(domains))}}class DelegatedCollection{static{__name(this,"DelegatedCollection")}static{__name2(this,"DelegatedCollection")}#data;constructor(entries=[]){this.#data=new Collection(entries)}[Symbol.iterator](){return this.#data.values()}get size(){return this.#data.size}get contents(){return this.#data.contents}get(key,options){return this.#data.get(key,options)}set(key,value){return this.#data.set(key,value),this}has(key){return this.#data.has(key)}find(predicate){return this.#data.find(predicate)}some(predicate){return this.#data.some(predicate)}filter(predicate){return this.#data.filter(predicate)}map(callback){return this.#data.map(callback)}delete(key){return this.#data.delete(key)}clear(){this.#data.clear()}}function createHTMLElement(nodeName,{classes=[],dataset={},children=[],innerHTML}={}){const element=document.createElement(nodeName);classes.length>0&&element.classList.add(...classes);for(const[key,value]of Object.entries(dataset).filter(([,v])=>!isNil(v)))element.dataset[key]=String(value);if(innerHTML)element.innerHTML=innerHTML;else 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 htmlSelectorFor(element){const nodeName=element.nodeName.toLowerCase(),classes=compact(element.className.split(" ")),classesString=classes.length>0?`.${classes.join(".")}`:"",datasetString=Object.entries(element.dataset).map(([k,v])=>[k.replace(/([A-Z])/g,"-$1").toLowerCase(),v]).map(([k,v])=>`[data-${k}="${v}"]`).join("");return`${nodeName}${classesString}${datasetString}`}__name(htmlSelectorFor,"htmlSelectorFor"),__name2(htmlSelectorFor,"htmlSelectorFor");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 padArray(array,requiredLength,padWith){const result=[...array];for(let i=array.length;i<requiredLength;i+=1)result.push(padWith);return result}__name(padArray,"padArray"),__name2(padArray,"padArray");function mapValues(object,mapping){return Object.entries(object).reduce((result,[key,value])=>(result[key]=mapping(value,key),result),{})}__name(mapValues,"mapValues"),__name2(mapValues,"mapValues");function applyNTimes(func,times,start){let result=start;for(let i=0;i<times;i+=1)result=func(result);return result}__name(applyNTimes,"applyNTimes"),__name2(applyNTimes,"applyNTimes");function objectHasKey(obj,key){return(typeof key=="string"||typeof key=="number")&&key in obj}__name(objectHasKey,"objectHasKey"),__name2(objectHasKey,"objectHasKey");function tupleHasValue(array,value){return array.includes(value)}__name(tupleHasValue,"tupleHasValue"),__name2(tupleHasValue,"tupleHasValue");function setHasElement(set,value){return set.has(value)}__name(setHasElement,"setHasElement"),__name2(setHasElement,"setHasElement");let intlNumberFormat;function signedInteger(value,{emptyStringZero=!1,zeroIsNegative=!1}={}){if(value===0&&emptyStringZero)return"";const nf=intlNumberFormat??=new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always"}),maybeNegativeZero=zeroIsNegative&&value===0?-0:value;return nf.format(maybeNegativeZero)}__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(type,cost){switch(type){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:"1",2:"2",3:"3","1 or 2":"1/2","1 to 3":"1 - 3","2 or 3":"2/3","2 rounds":"3,3",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]?.replace("-","\u2013")??""}__name(getActionGlyph,"getActionGlyph"),__name2(getActionGlyph,"getActionGlyph");function ErrorPF2e(message){return Error(`PF2e System | ${message}`)}__name(ErrorPF2e,"ErrorPF2e"),__name2(ErrorPF2e,"ErrorPF2e");function ordinalString(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(ordinalString,"ordinalString"),__name2(ordinalString,"ordinalString");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])=>foundry.utils.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 recursiveReplaceString(source,replace){const clone=Array.isArray(source)||isObject$1(source)?foundry.utils.deepClone(source):source;if(typeof clone=="string")return replace(clone);if(Array.isArray(clone))return clone.map(e=>recursiveReplaceString(e,replace));if(isObject$1(clone))for(const[key,value]of Object.entries(clone))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((result,[key,value])=>(result[key]=typeof value=="string"?`${prefix}.${key}`:configFromLocalization(value,`${prefix}.${key}`),result),{})}__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");const SORTABLE_BASE_OPTIONS={animation:200,direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",fallbackOnBody:!0,filter:"div.item-summary",ghostClass:"drag-gap",group:"inventory",preventOnFilter:!1,swapThreshold:.25,scroll:!0,scrollSensitivity:30,scrollSpeed:15};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(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,"tagify"),__name2(tagify,"tagify");class PredicatePF2e extends Array{static{__name(this,"PredicatePF2e")}static{__name2(this,"PredicatePF2e")}isValid;constructor(...statements){super(...Array.isArray(statements[0])?statements[0]:statements),this.isValid=PredicatePF2e.isValid(this),Object.defineProperty(this,"isValid",{enumerable:!1})}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 foundry.utils.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}:([^:]+)$`),values=domainArray.map(s=>Number(pattern.exec(s)?.[1]||NaN)).filter(v=>!Number.isNaN(v));return values.length>0?values:[NaN]},"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=>l<r));case"lte":return leftValues.some(l=>rightValues.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))||"xor"in statement&&statement.xor.filter(subProp=>this.#isTrue(subProp,domain)).length===1||"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))}}class StatementValidator{static{__name(this,"StatementValidator")}static{__name2(this,"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#binaryOperators=new Set(["eq","gt","gte","lt","lte"]);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.isXor(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 isXor(statement){return Object.keys(statement).length===1&&Array.isArray(statement.xor)&&statement.xor.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)}}class AutomaticBonusProgression{static{__name(this,"AutomaticBonusProgression")}static{__name2(this,"AutomaticBonusProgression")}static isEnabled(actor){if(actor&&!actor.flags?.pf2e)return!1;const settingEnabled=game.pf2e.settings.variants.abp!=="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){if(!this.isEnabled(actor))return;const{level,synthetics}=actor,values=this.abpValues(level),ac=values.ac,perception=values.perception,save=values.save,setting=game.pf2e.settings.variants.abp;if(save>0&&(synthetics.modifiers["saving-throw"]??=[]).push(()=>new ModifierPF2e({slug:"save-potency",label:"PF2E.AutomaticBonusProgression.savePotency",modifier:save,type:"potency"})),ac>0&&(synthetics.modifiers.ac??=[]).push(()=>new ModifierPF2e({slug:"defense-potency",label:"PF2E.AutomaticBonusProgression.defensePotency",modifier:ac,type:"potency"})),perception>0&&(synthetics.modifiers.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&&(synthetics.modifiers["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};(synthetics.weaponPotency["strike-attack-roll"]??=[]).push(potency)}}}static cleanupRunes(item){this.isEnabled(item.actor)&&(item.system.runes.potency=0,item.isOfType("weapon")?item.system.runes.striking=0:item.system.runes.resilient=0,game.pf2e.settings.variants.abp==="ABPRulesAsWritten"&&(item.system.runes.property=[]))}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}}}function getPropertyRuneSlots(item){const fromMaterial=item.system.material.type==="orichalcum"?1:0,fromPotency=AutomaticBonusProgression.isEnabled(item.actor)?AutomaticBonusProgression.getAttackPotency(!item.actor||item.actor.isOfType("loot")?20:item.actor.level):item.system.runes.potency;return fromMaterial+fromPotency}__name(getPropertyRuneSlots,"getPropertyRuneSlots"),__name2(getPropertyRuneSlots,"getPropertyRuneSlots");function prunePropertyRunes(runes,validTypes){const runeSet=new Set(runes);return Array.from(runeSet).filter(r=>!!r&&r in validTypes&&!runeSet.has(`greater${r.titleCase()}`)&&!runeSet.has(`major${r.replace(/^greater/,"").titleCase()}`)&&!runeSet.has(`true${r.replace(/^greater|^major/,"").titleCase()}`))}__name(prunePropertyRunes,"prunePropertyRunes"),__name2(prunePropertyRunes,"prunePropertyRunes");function getRuneValuationData(item){if(!item.isOfType("armor","shield","weapon"))return[];const itemRunes=item.system.runes,data=item.isOfType("armor")?{runes:RUNE_DATA.armor,weaponRunes:{},secondaryFundamental:"resilient"}:item.isOfType("shield")?{runes:RUNE_DATA.shield,weaponRunes:RUNE_DATA.weapon,secondaryFundamental:""}:{runes:RUNE_DATA.weapon,weaponRunes:{},secondaryFundamental:"striking"};return compact(item.isOfType("shield")?[data.runes.reinforcing[item.system.runes.reinforcing],data.weaponRunes.potency[item.system.traits.integrated?.runes.potency??0],data.weaponRunes.striking[item.system.traits.integrated?.runes.striking??0],item.system.traits.integrated?.runes.property.map(p=>data.weaponRunes.property[p])??[]].flat():[data.runes.potency[item.system.runes.potency],data.runes[data.secondaryFundamental]?.[itemRunes[data.secondaryFundamental]??""],item.system.runes.property.map(p=>data.runes.property[p])].flat())}__name(getRuneValuationData,"getRuneValuationData"),__name2(getRuneValuationData,"getRuneValuationData");function getPropertyRuneDegreeAdjustments(item){return uniq(compact([item.system.runes.property.map(p=>WEAPON_PROPERTY_RUNES[p].attack?.dosAdjustments),item.system.runes.effects.map(p=>WEAPON_PROPERTY_RUNES[p].attack?.dosAdjustments)].flat(2)))}__name(getPropertyRuneDegreeAdjustments,"getPropertyRuneDegreeAdjustments"),__name2(getPropertyRuneDegreeAdjustments,"getPropertyRuneDegreeAdjustments");function getPropertyRuneDice(runes,options){return runes.flatMap(rune=>{const runeData=WEAPON_PROPERTY_RUNES[rune];return foundry.utils.deepClone(runeData.damage?.dice??[]).map(data=>{const dice=new DamageDicePF2e({selector:"strike-damage",slug:rune,label:RUNE_DATA.weapon.property[rune]?.name,diceNumber:data.diceNumber??1,dieSize:data.dieSize??"d6",damageType:data.damageType,category:data.category??null,predicate:data.predicate,critical:data.critical??null});return dice.test(options),dice})})}__name(getPropertyRuneDice,"getPropertyRuneDice"),__name2(getPropertyRuneDice,"getPropertyRuneDice");function getPropertyRuneStrikeAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].strikeAdjustments??[])}__name(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments"),__name2(getPropertyRuneStrikeAdjustments,"getPropertyRuneStrikeAdjustments");function getPropertyRuneModifierAdjustments(runes){return runes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.adjustments??[])}__name(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments"),__name2(getPropertyRuneModifierAdjustments,"getPropertyRuneModifierAdjustments");const FUNDAMENTAL_ARMOR_RUNE_DATA={potency:{0:null,1:{name:"PF2E.ArmorPotencyRune1",value:1,level:5,price:160,rarity:"common",traits:[]},2:{name:"PF2E.ArmorPotencyRune2",value:2,level:11,price:1060,rarity:"common",traits:[]},3:{name:"PF2E.ArmorPotencyRune3",value:3,level:18,price:20560,rarity:"common",traits:[]},4:{name:"PF2E.ArmorPotencyRune4",value:4,level:18,price:20560,rarity:"common",traits:[]}},resilient:{0:null,1:{name:"PF2E.ArmorResilientRune",level:8,price:340,rarity:"common",slug:"resilient",traits:[]},2:{name:"PF2E.ArmorGreaterResilientRune",level:14,price:3440,rarity:"common",slug:"greaterResilient",traits:[]},3:{name:"PF2E.ArmorMajorResilientRune",level:20,price:49440,rarity:"common",slug:"majorResilient",traits:[]}}},FUNDAMENTAL_WEAPON_RUNE_DATA={potency:{0:null,1:{name:"PF2E.WeaponPotencyRune1",value:1,level:2,price:35,rarity:"common",traits:[]},2:{name:"PF2E.WeaponPotencyRune2",value:2,level:10,price:935,rarity:"common",traits:[]},3:{name:"PF2E.WeaponPotencyRune3",value:3,level:16,price:8935,rarity:"common",traits:[]},4:{name:"PF2E.WeaponPotencyRune4",value:4,level:16,price:8935,rarity:"common",traits:[]}},striking:{0:null,1:{name:"PF2E.Item.Weapon.Rune.Striking.Striking",level:4,price:65,rarity:"common",slug:"striking",traits:[]},2:{name:"PF2E.Item.Weapon.Rune.Striking.Greater",level:12,price:1065,rarity:"common",slug:"greaterStriking",traits:[]},3:{name:"PF2E.Item.Weapon.Rune.Striking.Major",level:19,price:31065,rarity:"common",slug:"majorStriking",traits:[]}}},FUNDAMENTAL_SHIELD_RUNE_DATA={reinforcing:{0:null,1:{name:"PF2E.Item.Shield.Rune.Reinforcing.Minor",level:4,price:75,rarity:"common",traits:["magical"],hardness:{increase:3,max:8},maxHP:{increase:44,max:64}},2:{name:"PF2E.Item.Shield.Rune.Reinforcing.Lesser",level:7,price:300,rarity:"common",traits:["magical"],hardness:{increase:3,max:10},maxHP:{increase:52,max:80}},3:{name:"PF2E.Item.Shield.Rune.Reinforcing.Moderate",level:10,price:900,rarity:"common",traits:["magical"],hardness:{increase:3,max:13},maxHP:{increase:64,max:104}},4:{name:"PF2E.Item.Shield.Rune.Reinforcing.Greater",level:13,price:2500,rarity:"common",traits:["magical"],hardness:{increase:5,max:15},maxHP:{increase:80,max:120}},5:{name:"PF2E.Item.Shield.Rune.Reinforcing.Major",level:16,price:8e3,rarity:"common",traits:["magical"],hardness:{increase:5,max:17},maxHP:{increase:84,max:136}},6:{name:"PF2E.Item.Shield.Rune.Reinforcing.Supreme",level:19,price:32e3,rarity:"common",traits:["magical"],hardness:{increase:7,max:20},maxHP:{increase:108,max:160}}}},ARMOR_PROPERTY_RUNES={acidResistant:{name:"PF2E.ArmorPropertyRuneAcidResistant",level:8,price:420,rarity:"common",slug:"acidResistant",traits:["magical"]},advancing:{name:"PF2E.ArmorPropertyRuneAdvancing",level:9,price:625,rarity:"common",slug:"advancing",traits:["magical"]},aimAiding:{name:"PF2E.ArmorPropertyRuneAimAiding",level:6,price:225,rarity:"common",slug:"aimAiding",traits:["magical"]},antimagic:{name:"PF2E.ArmorPropertyRuneAntimagic",level:15,price:6500,rarity:"uncommon",slug:"antimagic",traits:["magical"]},assisting:{name:"PF2E.ArmorPropertyRuneAssisting",level:5,price:125,rarity:"common",slug:"assisting",traits:["magical"]},bitter:{name:"PF2E.ArmorPropertyRuneBitter",level:9,price:135,rarity:"uncommon",slug:"bitter",traits:["magical","poison"]},coldResistant:{name:"PF2E.ArmorPropertyRuneColdResistant",level:8,price:420,rarity:"common",slug:"coldResistant",traits:["magical"]},deathless:{name:"PF2E.ArmorPropertyRuneDeathless",level:7,price:330,rarity:"uncommon",slug:"deathless",traits:["healing","magical"]},electricityResistant:{name:"PF2E.ArmorPropertyRuneElectricityResistant",level:8,price:420,rarity:"common",slug:"electricityResistant",traits:["magical"]},energyAdaptive:{name:"PF2E.ArmorPropertyRuneEnergyAdaptive",level:6,price:225,rarity:"common",slug:"energyAdaptive",traits:["magical"]},ethereal:{name:"PF2E.ArmorPropertyRuneEthereal",level:17,price:13500,rarity:"common",slug:"ethereal",traits:["magical"]},fireResistant:{name:"PF2E.ArmorPropertyRuneFireResistant",level:8,price:420,rarity:"common",slug:"fireResistant",traits:["magical"]},fortification:{name:"PF2E.ArmorPropertyRuneFortification",level:12,price:2e3,rarity:"common",slug:"fortification",traits:["magical"]},glamered:{name:"PF2E.ArmorPropertyRuneGlamered",level:5,price:140,rarity:"common",slug:"glamered",traits:["illusion","magical"]},gliding:{name:"PF2E.ArmorPropertyRuneGliding",level:8,price:450,rarity:"common",slug:"gliding",traits:["magical"]},greaterAcidResistant:{name:"PF2E.ArmorPropertyRuneGreaterAcidResistant",level:12,price:1650,rarity:"common",slug:"greaterAcidResistant",traits:["magical"]},greaterAdvancing:{name:"PF2E.ArmorPropertyRuneGreaterAdvancing",level:16,price:8e3,rarity:"common",slug:"greaterAdvancing",traits:["magical"]},greaterColdResistant:{name:"PF2E.ArmorPropertyRuneGreaterColdResistant",level:12,price:1650,rarity:"common",slug:"greaterColdResistant",traits:["magical"]},greaterDread:{name:"PF2E.ArmorPropertyRuneGreaterDread",level:18,price:21e3,rarity:"uncommon",slug:"greaterDread",traits:["emotion","fear","magical","mental","visual"]},greaterElectricityResistant:{name:"PF2E.ArmorPropertyRuneGreaterElectricityResistant",level:12,price:1650,rarity:"common",slug:"greaterElectricityResistant",traits:["magical"]},greaterFireResistant:{name:"PF2E.ArmorPropertyRuneGreaterFireResistant",level:12,price:1650,rarity:"common",slug:"greaterFireResistant",traits:["magical"]},greaterFortification:{name:"PF2E.ArmorPropertyRuneGreaterFortification",level:19,price:24e3,rarity:"common",slug:"greaterFortification",traits:["magical"]},greaterInvisibility:{name:"PF2E.ArmorPropertyRuneGreaterInvisibility",level:10,price:1e3,rarity:"common",slug:"greaterInvisibility",traits:["illusion","magical"]},greaterReady:{name:"PF2E.ArmorPropertyRuneGreaterReady",level:11,price:1200,rarity:"common",slug:"greaterReady",traits:["magical"]},greaterShadow:{name:"PF2E.ArmorPropertyRuneGreaterShadow",level:9,price:650,rarity:"common",slug:"greaterShadow",traits:["magical"]},greaterSlick:{name:"PF2E.ArmorPropertyRuneGreaterSlick",level:8,price:450,rarity:"common",slug:"greaterSlick",traits:["magical"]},greaterStanching:{name:"PF2E.ArmorPropertyRuneGreaterStanching",level:9,price:600,rarity:"uncommon",slug:"greaterStanching",traits:["magical"]},greaterQuenching:{name:"PF2E.ArmorPropertyRuneGreaterQuenching",level:10,price:1e3,rarity:"common",slug:"greaterQuenching",traits:["magical"]},greaterSwallowSpike:{name:"PF2E.ArmorPropertyRuneGreaterSwallowSpike",level:12,price:1750,rarity:"common",slug:"greaterSwallowSpike",traits:["magical"]},greaterWinged:{name:"PF2E.ArmorPropertyRuneGreaterWinged",level:19,price:35e3,rarity:"common",slug:"greaterWinged",traits:["magical"]},immovable:{name:"PF2E.ArmorPropertyRuneImmovable",level:12,price:1800,rarity:"uncommon",slug:"immovable",traits:["magical"]},implacable:{name:"PF2E.ArmorPropertyRuneImplacable",level:11,price:1200,rarity:"uncommon",slug:"implacable",traits:["magical"]},invisibility:{name:"PF2E.ArmorPropertyRuneInvisibility",level:8,price:500,rarity:"common",slug:"invisibility",traits:["illusion","magical"]},lesserDread:{name:"PF2E.ArmorPropertyRuneLesserDread",level:6,price:225,rarity:"uncommon",slug:"lesserDread",traits:["emotion","fear","magical","mental","visual"]},magnetizing:{name:"PF2E.ArmorPropertyRuneMagnetizing",level:10,price:900,rarity:"common",slug:"magnetizing",traits:["magical"]},majorQuenching:{name:"PF2E.ArmorPropertyRuneMajorQuenching",level:14,price:4500,rarity:"common",slug:"majorQuenching",traits:["magical"]},majorShadow:{name:"PF2E.ArmorPropertyRuneMajorShadow",level:17,price:14e3,rarity:"common",slug:"majorShadow",traits:["magical"]},majorSlick:{name:"PF2E.ArmorPropertyRuneMajorSlick",level:16,price:9e3,rarity:"common",slug:"majorSlick",traits:["magical"]},majorStanching:{name:"PF2E.ArmorPropertyRuneMajorStanching",level:13,price:2500,rarity:"uncommon",slug:"majorStanching",traits:["magical"]},majorSwallowSpike:{name:"PF2E.ArmorPropertyRuneMajorSwallowSpike",level:16,price:19250,rarity:"common",slug:"majorSwallowSpike",traits:["magical"]},malleable:{name:"PF2E.ArmorPropertyRuneMalleable",level:9,price:650,rarity:"common",slug:"malleable",traits:["magical","metal"]},misleading:{name:"PF2E.ArmorPropertyRuneMisleading",level:16,price:8e3,rarity:"common",slug:"misleading",traits:["illusion","magical"]},moderateDread:{name:"PF2E.ArmorPropertyRuneModerateDread",level:12,price:1800,rarity:"uncommon",slug:"moderateDread",traits:["emotion","fear","magical","mental","visual"]},portable:{name:"PF2E.ArmorPropertyRunePortable",level:9,price:660,rarity:"common",slug:"portable",traits:["magical"]},quenching:{name:"PF2E.ArmorPropertyRuneQuenching",level:6,price:250,rarity:"common",slug:"quenching",traits:["magical"]},raiment:{name:"PF2E.ArmorPropertyRuneRaiment",level:5,price:140,rarity:"common",slug:"raiment",traits:["illusion","magical"]},ready:{name:"PF2E.ArmorPropertyRuneReady",level:6,price:200,rarity:"common",slug:"ready",traits:["magical"]},rockBraced:{name:"PF2E.ArmorPropertyRuneRockBraced",level:13,price:3e3,rarity:"rare",slug:"rockBraced",traits:["dwarf","magical","saggorak"]},shadow:{name:"PF2E.ArmorPropertyRuneShadow",level:5,price:55,rarity:"common",slug:"shadow",traits:["magical"]},sinisterKnight:{name:"PF2E.ArmorPropertyRuneSinisterKnight",level:8,price:500,rarity:"uncommon",slug:"sinisterKnight",traits:["illusion","magical"]},slick:{name:"PF2E.ArmorPropertyRuneSlick",level:5,price:45,rarity:"common",slug:"slick",traits:["magical"]},soaring:{name:"PF2E.ArmorPropertyRuneSoaring",level:14,price:3750,rarity:"common",slug:"soaring",traits:["magical"]},stanching:{name:"PF2E.ArmorPropertyRuneStanching",level:5,price:130,rarity:"uncommon",slug:"stanching",traits:["magical"]},swallowSpike:{name:"PF2E.ArmorPropertyRuneSwallowSpike",level:6,price:200,rarity:"common",slug:"swallowSpike",traits:["magical"]},trueQuenching:{name:"PF2E.ArmorPropertyRuneTrueQuenching",level:18,price:24e3,rarity:"common",slug:"trueQuenching",traits:["magical"]},trueStanching:{name:"PF2E.ArmorPropertyRuneTrueStanching",level:17,price:12500,rarity:"uncommon",slug:"trueStanching",traits:["magical"]},winged:{name:"PF2E.ArmorPropertyRuneWinged",level:13,price:2500,rarity:"common",slug:"winged",traits:["magical"]}},WEAPON_PROPERTY_RUNES={ancestralEchoing:{level:15,name:"PF2E.WeaponPropertyRune.ancestralEchoing.Name",price:9500,rarity:"rare",slug:"ancestralEchoing",traits:["dwarf","magical","saggorak"]},anchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.anchoring.Name",text:"PF2E.WeaponPropertyRune.anchoring.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.anchoring.Name",price:900,rarity:"uncommon",slug:"anchoring",traits:["magical"]},ashen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d4"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.ashen.Name",text:"PF2E.WeaponPropertyRune.ashen.Note.success"}]},level:9,name:"PF2E.WeaponPropertyRune.ashen.Name",price:700,rarity:"common",slug:"ashen",traits:["magical"]},astral:{level:8,name:"PF2E.WeaponPropertyRune.astral.Name",price:450,rarity:"common",slug:"astral",traits:["magical","spirit"],damage:{dice:[{damageType:"spirit",diceNumber:1,dieSize:"d6"}]}},authorized:{level:3,name:"PF2E.WeaponPropertyRune.authorized.Name",price:50,rarity:"common",slug:"authorized",traits:["magical"]},bane:{level:4,name:"PF2E.WeaponPropertyRune.bane.Name",price:100,rarity:"uncommon",slug:"bane",traits:["magical"]},bloodbane:{level:8,name:"PF2E.WeaponPropertyRune.bloodbane.Name",price:475,rarity:"uncommon",slug:"bloodbane",traits:["dwarf","magical"]},bloodthirsty:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.bloodbane.Name",text:"PF2E.WeaponPropertyRune.bloodthirsty.Note.criticalSuccess"}]},level:16,name:"PF2E.WeaponPropertyRune.bloodthirsty.Name",price:8500,rarity:"uncommon",slug:"bloodthirsty",traits:["magical"]},brilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"spirit",diceNumber:1,dieSize:"d4",predicate:["target:trait:fiend"]},{damageType:"vitality",diceNumber:1,dieSize:"d4",predicate:["target:negative-healing"]}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.brilliant.Name",text:"PF2E.WeaponPropertyRune.brilliant.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.brilliant.Name",price:2e3,rarity:"common",slug:"brilliant",traits:["magical"]},called:{level:7,name:"PF2E.WeaponPropertyRune.called.Name",price:350,rarity:"common",slug:"called",traits:["magical"]},coating:{level:9,name:"PF2E.WeaponPropertyRune.coating.Name",price:700,rarity:"common",slug:"coating",traits:["extradimensional","magical"]},conducting:{level:7,name:"PF2E.WeaponPropertyRune.conducting.Name",price:300,rarity:"common",slug:"conducting",traits:["magical"]},corrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.corrosive.Name",text:"PF2E.WeaponPropertyRune.corrosive.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.corrosive.Name",price:500,rarity:"common",slug:"corrosive",traits:["acid","magical"]},crushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.crushing.Name",text:"PF2E.WeaponPropertyRune.crushing.Note.criticalSuccess"}]},level:3,name:"PF2E.WeaponPropertyRune.crushing.Name",price:50,rarity:"uncommon",slug:"crushing",traits:["magical"]},cunning:{level:5,name:"PF2E.WeaponPropertyRune.cunning.Name",price:140,rarity:"common",slug:"cunning",traits:["magical"]},dancing:{level:13,name:"PF2E.WeaponPropertyRune.dancing.Name",price:2700,rarity:"uncommon",slug:"dancing",traits:["magical"]},decaying:{damage:{dice:[{slug:"decaying",damageType:"void",diceNumber:1,dieSize:"d4"},{slug:"decaying-persistent",category:"persistent",damageType:"void",diceNumber:2,dieSize:"d4",critical:!0}]},level:8,name:"PF2E.WeaponPropertyRune.decaying.Name",price:500,rarity:"common",slug:"decaying",traits:["acid","magical","void"]},deathdrinking:{damage:{dice:[{slug:"deathdrinking-negative",damageType:"void",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:mode:living",{not:"target:negative-healing"}]},{slug:"deathdrinking-positive",damageType:"vitality",diceNumber:1,dieSize:"d6",critical:!0,predicate:["target:negative-healing"]}]},level:7,name:"PF2E.WeaponPropertyRune.deathdrinking.Name",price:360,rarity:"rare",slug:"deathdrinking",traits:["magical"]},demolishing:{damage:{dice:[{damageType:"force",category:"persistent",diceNumber:1,dieSize:"d6",predicate:["target:trait:construct"]}]},level:6,name:"PF2E.WeaponPropertyRune.demolishing.Name",price:225,rarity:"rare",slug:"demolishing",traits:["magical"]},disrupting:{damage:{dice:[{category:"persistent",damageType:"vitality",diceNumber:1,dieSize:"d6",predicate:["target:negative-healing"]}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.disrupting.Name",text:"PF2E.WeaponPropertyRune.disrupting.Note.criticalSuccess",predicate:["target:negative-healing"]}]},level:5,name:"PF2E.WeaponPropertyRune.disrupting.Name",price:150,rarity:"common",slug:"disrupting",traits:["magical"]},earthbinding:{level:5,name:"PF2E.WeaponPropertyRune.earthbinding.Name",price:125,rarity:"common",slug:"earthbinding",traits:["magical"]},energizing:{level:6,name:"PF2E.WeaponPropertyRune.energizing.Name",price:250,rarity:"uncommon",slug:"energizing",traits:["magical"]},extending:{level:7,name:"PF2E.WeaponPropertyRune.extending.Name",price:700,rarity:"common",slug:"extending",traits:["magical"]},fanged:{level:2,name:"PF2E.WeaponPropertyRune.fanged.Name",price:30,rarity:"uncommon",slug:"fanged",traits:["magical"]},fearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.fearsome.Name",text:"PF2E.WeaponPropertyRune.fearsome.Note.criticalSuccess"}]},level:5,name:"PF2E.WeaponPropertyRune.fearsome.Name",price:160,rarity:"common",slug:"fearsome",traits:["emotion","fear","magical","mental"]},flaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d10",critical:!0}]},level:8,name:"PF2E.WeaponPropertyRune.flaming.Name",price:500,rarity:"common",slug:"flaming",traits:["fire","magical"]},flurrying:{level:7,name:"PF2E.WeaponPropertyRune.flurrying.Name",price:360,rarity:"common",slug:"flurrying",traits:["magical"]},frost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.frost.Name",text:"PF2E.WeaponPropertyRune.frost.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.frost.Name",price:500,rarity:"common",slug:"frost",traits:["cold","magical"]},ghostTouch:{level:4,name:"PF2E.WeaponPropertyRune.ghostTouch.Name",price:75,rarity:"common",slug:"ghostTouch",traits:["magical"]},giantKilling:{damage:{dice:[{slug:"giantKilling",damageType:"mental",diceNumber:1,dieSize:"d6",predicate:["target:trait:giant"]}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.giantKilling.Name",text:"PF2E.WeaponPropertyRune.giantKilling.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.giantKilling.Name",price:450,rarity:"rare",slug:"giantKilling",traits:["magical"]},greaterAnchoring:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",text:"PF2E.WeaponPropertyRune.greaterAnchoring.Note.success"}]},level:18,name:"PF2E.WeaponPropertyRune.greaterAnchoring.Name",price:22e3,rarity:"uncommon",slug:"greaterAnchoring",traits:["magical"]},greaterAshen:{damage:{dice:[{damageType:"fire",category:"persistent",diceNumber:1,dieSize:"d8"}],notes:[{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterAshen.Name",text:"PF2E.WeaponPropertyRune.greaterAshen.Note.success"}]},level:16,name:"PF2E.WeaponPropertyRune.greaterAshen.Name",price:9e3,rarity:"common",slug:"greaterAshen",traits:["magical"]},greaterAstral:{level:15,name:"PF2E.WeaponPropertyRune.greaterAstral.Name",price:6e3,rarity:"common",slug:"greaterAstral",traits:["magical","spirit"],damage:{dice:[{damageType:"spirit",diceNumber:1,dieSize:"d6"}],ignoredResistances:[{type:"spirit",max:null}]}},greaterBloodbane:{level:13,name:"PF2E.WeaponPropertyRune.greaterBloodbane.Name",price:2800,rarity:"uncommon",slug:"greaterBloodbane",traits:["dwarf","magical"]},greaterBrilliant:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d4"},{damageType:"spirit",diceNumber:1,dieSize:"d4",predicate:["target:trait:fiend"]},{damageType:"vitality",diceNumber:1,dieSize:"d4",predicate:["target:negative-healing"]}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",text:"PF2E.WeaponPropertyRune.greaterBrilliant.Note.success"}],ignoredResistances:[{type:"fire",max:null},{type:"spirit",max:null},{type:"vitality",max:null}]},level:18,name:"PF2E.WeaponPropertyRune.greaterBrilliant.Name",price:24e3,rarity:"common",slug:"greaterBrilliant",traits:["magical"]},greaterCorrosive:{damage:{dice:[{damageType:"acid",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",text:"PF2E.WeaponPropertyRune.greaterCorrosive.Note.success"}],ignoredResistances:[{type:"acid",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterCorrosive.Name",price:6500,rarity:"common",slug:"greaterCorrosive",traits:["acid","magical"]},greaterCrushing:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterCrushing.Name",text:"PF2E.WeaponPropertyRune.greaterCrushing.Note.criticalSuccess"}]},level:9,name:"PF2E.WeaponPropertyRune.greaterCrushing.Name",price:650,rarity:"uncommon",slug:"greaterCrushing",traits:["magical"]},greaterDecaying:{damage:{dice:[{slug:"decaying",damageType:"void",diceNumber:1,dieSize:"d4"},{slug:"decaying-persistent",category:"persistent",damageType:"void",diceNumber:4,dieSize:"d4",critical:!0}],ignoredResistances:[{type:"void",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterDecaying.Name",price:6500,rarity:"common",slug:"greaterDecaying",traits:["acid","magical","void"]},greaterDisrupting:{damage:{dice:[{category:"persistent",damageType:"vitality",diceNumber:2,dieSize:"d6",predicate:["target:negative-healing"]}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",text:"PF2E.WeaponPropertyRune.greaterDisrupting.Note.criticalSuccess",predicate:["target:negative-healing"]}]},level:14,name:"PF2E.WeaponPropertyRune.greaterDisrupting.Name",price:4300,rarity:"uncommon",slug:"greaterDisrupting",traits:["magical"]},greaterExtending:{level:13,name:"PF2E.WeaponPropertyRune.greaterExtending.Name",price:3e3,rarity:"common",slug:"greaterExtending",traits:["magical"]},greaterFanged:{level:8,name:"PF2E.WeaponPropertyRune.greaterFanged.Name",price:425,rarity:"uncommon",slug:"greaterFanged",traits:["magical"]},greaterFearsome:{damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFearsome.Name",text:"PF2E.WeaponPropertyRune.greaterFearsome.Note.criticalSuccess"}]},level:12,name:"PF2E.WeaponPropertyRune.greaterFearsome.Name",price:2e3,rarity:"common",slug:"greaterFearsome",traits:["emotion","fear","magical","mental"]},greaterFlaming:{damage:{dice:[{damageType:"fire",diceNumber:1,dieSize:"d6"},{damageType:"fire",category:"persistent",diceNumber:2,dieSize:"d10",critical:!0}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFlaming.Name",text:"PF2E.WeaponPropertyRune.greaterFlaming.Note.success"}],ignoredResistances:[{type:"fire",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFlaming.Name",price:6500,rarity:"common",slug:"greaterFlaming",traits:["fire","magical"]},greaterFrost:{damage:{dice:[{damageType:"cold",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterFrost.Name",text:"PF2E.WeaponPropertyRune.greaterFrost.Note.success"}],ignoredResistances:[{type:"cold",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterFrost.Name",price:6500,rarity:"common",slug:"greaterFrost",traits:["cold","magical"]},greaterGiantKilling:{damage:{dice:[{slug:"greaterGiantKilling",damageType:"mental",diceNumber:2,dieSize:"d6",predicate:["target:trait:giant"]}],ignoredResistances:[{type:"mental",max:null}],notes:[{outcome:["criticalSuccess"],predicate:["target:trait:giant"],title:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",text:"PF2E.WeaponPropertyRune.greaterGiantKilling.Note.criticalSuccess"}]},level:15,name:"PF2E.WeaponPropertyRune.greaterGiantKilling.Name",price:6e3,rarity:"rare",slug:"greaterGiantKilling",traits:["magical"]},greaterHauling:{level:11,name:"PF2E.WeaponPropertyRune.greaterHauling.Name",price:1300,rarity:"uncommon",slug:"greaterHauling",traits:["magical"]},greaterImpactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterImpactful.Name",text:"PF2E.WeaponPropertyRune.greaterImpactful.Note.criticalSuccess"}]},level:17,name:"PF2E.WeaponPropertyRune.greaterImpactful.Name",price:15e3,rarity:"common",slug:"greaterImpactful",traits:["force","magical"]},greaterRooting:{level:11,name:"PF2E.WeaponPropertyRune.greaterRooting.Name",price:1400,rarity:"common",slug:"greaterRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterRooting.Name",text:"PF2E.WeaponPropertyRune.greaterRooting.Note.success"}]}},greaterShock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterShock.Name",text:"PF2E.WeaponPropertyRune.greaterShock.Note.success"}],ignoredResistances:[{type:"electricity",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterShock.Name",price:6500,rarity:"common",slug:"greaterShock",traits:["electricity","magical"]},greaterThundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.criticalSuccess"},{outcome:["success"],title:"PF2E.WeaponPropertyRune.greaterThundering.Name",text:"PF2E.WeaponPropertyRune.greaterThundering.Note.success"}],ignoredResistances:[{type:"sonic",max:null}]},level:15,name:"PF2E.WeaponPropertyRune.greaterThundering.Name",price:6500,rarity:"common",slug:"greaterThundering",traits:["magical","sonic"]},grievous:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6",critical:!0,predicate:["critical-specialization","item:group:dart"]}],notes:[{outcome:["criticalSuccess"],predicate:["item:group:axe"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Axe"},{outcome:["criticalSuccess"],predicate:["item:group:brawling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Brawling"},{outcome:["criticalSuccess"],predicate:["item:group:club"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Club"},{outcome:["criticalSuccess"],predicate:["item:group:flail"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Flail"},{outcome:["criticalSuccess"],predicate:["item:group:hammer"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Hammer"},{outcome:["criticalSuccess"],predicate:["item:group:knife"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Knife"},{outcome:["criticalSuccess"],predicate:["item:group:polearm"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Polearm"},{outcome:["criticalSuccess"],predicate:["item:group:shield"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Shield"},{outcome:["criticalSuccess"],predicate:["item:group:sling"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sling"},{outcome:["criticalSuccess"],predicate:["item:group:spear"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Spear"},{outcome:["criticalSuccess"],predicate:["item:group:sword"],title:"PF2E.WeaponPropertyRune.grievous.Name",text:"PF2E.WeaponPropertyRune.grievous.Note.Sword"}],adjustments:[{slug:"critical-specialization",test:options=>new PredicatePF2e("item:group:pick").test(options),getNewValue:current=>current*2}]},level:9,name:"PF2E.WeaponPropertyRune.grievous.Name",price:700,rarity:"common",slug:"grievous",traits:["magical"]},hauling:{level:6,name:"PF2E.WeaponPropertyRune.hauling.Name",price:225,rarity:"uncommon",slug:"hauling",traits:["magical"]},holy:{level:11,name:"PF2E.WeaponPropertyRune.holy.Name",price:1400,rarity:"common",slug:"holy",traits:["holy","magical"],damage:{dice:[{damageType:"spirit",diceNumber:1,dieSize:"d4",predicate:[{not:"target:trait:unholy"}]},{damageType:"spirit",diceNumber:2,dieSize:"d4",predicate:["target:trait:unholy"]}]},strikeAdjustments:[{adjustTraits:(_weapon,traits)=>{traits.includes("holy")||traits.push("holy")}}]},hopeful:{attack:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.hopeful.Name",text:"PF2E.WeaponPropertyRune.hopeful.Note.criticalSuccess"}]},level:11,name:"PF2E.WeaponPropertyRune.hopeful.Name",price:1200,rarity:"uncommon",slug:"hopeful",traits:["magical"]},hooked:{level:5,name:"PF2E.WeaponPropertyRune.hooked.Name",price:140,rarity:"rare",slug:"hooked",traits:["magical"],strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("trip")||weapon.system.traits.value.push("trip")}}]},impactful:{damage:{dice:[{damageType:"force",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.impactful.Name",text:"PF2E.WeaponPropertyRune.impactful.Note.criticalSuccess"}]},level:10,name:"PF2E.WeaponPropertyRune.impactful.Name",price:1e3,rarity:"common",slug:"impactful",traits:["force","magical"]},impossible:{level:20,name:"PF2E.WeaponPropertyRune.impossible.Name",price:7e4,rarity:"common",slug:"impossible",traits:["magical"],strikeAdjustments:[{adjustWeapon:weapon=>{if(weapon.isOfType("weapon")&&weapon.system.range&&weapon._source.system.range){const sourceRange=weapon._source.system.range,preparedRange=weapon.system.range;weapon.system.range=sourceRange*2+Math.abs(preparedRange-sourceRange)}}}]},keen:{attack:{dosAdjustments:[{adjustments:{success:{label:"PF2E.WeaponPropertyRune.keen.Name",amount:"criticalSuccess"}},predicate:new PredicatePF2e(["check:total:natural:19",{or:["item:damage:type:slashing","item:damage:type:piercing"]}])}]},level:13,name:"PF2E.WeaponPropertyRune.keen.Name",price:3e3,rarity:"uncommon",slug:"keen",traits:["magical"]},kinWarding:{level:3,name:"PF2E.WeaponPropertyRune.kinWarding.Name",price:52,rarity:"uncommon",slug:"kinWarding",traits:["dwarf","magical"]},majorFanged:{level:15,name:"PF2E.WeaponPropertyRune.majorFanged.Name",price:6e3,rarity:"uncommon",slug:"majorFanged",traits:["magical"]},majorRooting:{level:15,name:"PF2E.WeaponPropertyRune.majorRooting.Name",price:6500,rarity:"common",slug:"majorRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.majorRooting.Name",text:"PF2E.WeaponPropertyRune.majorRooting.Note.criticalSuccess"}]}},merciful:{strikeAdjustments:[{adjustWeapon:weapon=>{weapon.system.traits.value.includes("nonlethal")||weapon.system.traits.value.push("nonlethal")}}],level:4,name:"PF2E.WeaponPropertyRune.merciful.Name",price:70,rarity:"common",slug:"merciful",traits:["magical","mental"]},pacifying:{level:5,name:"PF2E.WeaponPropertyRune.pacifying.Name",price:150,rarity:"uncommon",slug:"pacifying",traits:["magical"]},returning:{attack:{notes:[{title:"PF2E.WeaponPropertyRune.returning.Name",text:"PF2E.WeaponPropertyRune.returning.Note"}]},level:3,name:"PF2E.WeaponPropertyRune.returning.Name",price:55,rarity:"common",slug:"returning",traits:["magical"]},rooting:{level:7,name:"PF2E.WeaponPropertyRune.rooting.Name",price:360,rarity:"common",slug:"rooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.rooting.Name",text:"PF2E.WeaponPropertyRune.rooting.Note.criticalSuccess"}]}},serrating:{damage:{dice:[{damageType:"slashing",diceNumber:1,dieSize:"d4"}]},level:10,name:"PF2E.WeaponPropertyRune.serrating.Name",price:1e3,rarity:"uncommon",slug:"serrating",traits:["magical"]},shifting:{level:6,name:"PF2E.WeaponPropertyRune.shifting.Name",price:225,rarity:"common",slug:"shifting",traits:["magical"]},shock:{damage:{dice:[{damageType:"electricity",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.shock.Name",text:"PF2E.WeaponPropertyRune.shock.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.shock.Name",price:500,rarity:"common",slug:"shock",traits:["electricity","magical"]},speed:{level:16,name:"PF2E.WeaponPropertyRune.speed.Name",price:1e4,rarity:"rare",slug:"speed",traits:["magical"]},spellStoring:{level:13,name:"PF2E.WeaponPropertyRune.spellStoring.Name",price:2700,rarity:"uncommon",slug:"spellStoring",traits:["magical"]},swarming:{level:9,name:"PF2E.WeaponPropertyRune.swarming.Name",price:700,rarity:"common",slug:"swarming",traits:["magical"]},thundering:{damage:{dice:[{damageType:"sonic",diceNumber:1,dieSize:"d6"}],notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.thundering.Name",text:"PF2E.WeaponPropertyRune.thundering.Note.criticalSuccess"}]},level:8,name:"PF2E.WeaponPropertyRune.thundering.Name",price:500,rarity:"common",slug:"thundering",traits:["magical","sonic"]},trueRooting:{level:19,name:"PF2E.WeaponPropertyRune.trueRooting.Name",price:4e4,rarity:"common",slug:"trueRooting",traits:["plant","magical","wood"],damage:{notes:[{outcome:["criticalSuccess"],title:"PF2E.WeaponPropertyRune.trueRooting.Name",text:"PF2E.WeaponPropertyRune.trueRooting.Note.criticalSuccess"}]}},underwater:{level:3,name:"PF2E.WeaponPropertyRune.underwater.Name",price:50,rarity:"common",slug:"underwater",traits:["magical","water"]},unholy:{level:11,name:"PF2E.WeaponPropertyRune.unholy.Name",price:1400,rarity:"common",slug:"unholy",traits:["unholy","magical"],damage:{dice:[{damageType:"spirit",diceNumber:1,dieSize:"d4",predicate:[{not:"target:trait:holy"}]},{damageType:"spirit",diceNumber:2,dieSize:"d4",predicate:["target:trait:holy"]}]},strikeAdjustments:[{adjustTraits:(_weapon,traits)=>{traits.includes("unholy")||traits.push("unholy")}}]},vorpal:{level:17,name:"PF2E.WeaponPropertyRune.vorpal.Name",price:15e3,rarity:"rare",slug:"vorpal",traits:["magical"]},wounding:{damage:{dice:[{damageType:"bleed",diceNumber:1,dieSize:"d6"}]},level:7,name:"PF2E.WeaponPropertyRune.wounding.Name",price:340,rarity:"common",slug:"wounding",traits:["magical"]}},RUNE_DATA={armor:{...FUNDAMENTAL_ARMOR_RUNE_DATA,property:ARMOR_PROPERTY_RUNES},shield:FUNDAMENTAL_SHIELD_RUNE_DATA,weapon:{...FUNDAMENTAL_WEAPON_RUNE_DATA,property:WEAPON_PROPERTY_RUNES}};class MigrationRunnerBase{static{__name(this,"MigrationRunnerBase")}static{__name2(this,"MigrationRunnerBase")}migrations;static LATEST_SCHEMA_VERSION=.911;static MINIMUM_SAFE_VERSION=.634;static RECOMMENDED_SAFE_VERSION=.781;static FOUNDRY_SCHEMA_VERSIONS={.8:.634,9:.7,10:.781,11:.841};constructor(migrations=[]){this.migrations=migrations.sort((a,b)=>a.version-b.version)}needsMigration(currentVersion){return currentVersion<this.constructor.LATEST_SCHEMA_VERSION}diffCollection(orig,updated){const diffs={inserted:[],deleted:[],updated:[]},origSources=new Map;for(const source of orig)origSources.set(source._id,source);for(const source of updated){const origSource=origSources.get(source._id);origSource?(JSON.stringify(origSource)!==JSON.stringify(source)&&diffs.updated.push(source),origSources.delete(source._id)):diffs.inserted.push(source)}for(const source of origSources.values())diffs.deleted.push(source._id);return diffs}async getUpdatedActor(actor,migrations){const currentActor=foundry.utils.deepClone(actor);for(const migration of migrations)for(const currentItem of currentActor.items)await migration.preUpdateItem?.(currentItem,currentActor),currentItem.type==="consumable"&¤tItem.system.spell&&await migration.preUpdateItem?.(currentItem.system.spell);for(const migration of migrations){await migration.updateActor?.(currentActor);for(const currentItem of currentActor.items)await migration.updateItem?.(currentItem,currentActor),currentItem.type==="consumable"&¤tItem.system.spell&&await migration.updateItem?.(currentItem.system.spell,currentActor)}if("game"in globalThis){const latestMigration=migrations.slice(-1)[0];currentActor.system._migration??={version:null,previous:null},this.#updateMigrationRecord(currentActor.system._migration,latestMigration);for(const itemSource of currentActor.items)itemSource.system._migration??={version:null,previous:null},this.#updateMigrationRecord(itemSource.system._migration,latestMigration)}return currentActor}async getUpdatedItem(item,migrations){const current=foundry.utils.deepClone(item);for(const migration of migrations)await migration.preUpdateItem?.(current),current.type==="consumable"&¤t.system.spell&&await migration.preUpdateItem?.(current.system.spell);for(const migration of migrations)await migration.updateItem?.(current),current.type==="consumable"&¤t.system.spell&&await migration.updateItem?.(current.system.spell);return migrations.length>0&&this.#updateMigrationRecord(current.system._migration,migrations.slice(-1)[0]),current}async getUpdatedTable(tableSource,migrations){const current=foundry.utils.deepClone(tableSource);for(const migration of migrations)try{await migration.updateTable?.(current)}catch(err){console.error(err)}return current}async getUpdatedMacro(macroSource,migrations){const current=foundry.utils.deepClone(macroSource);for(const migration of migrations)try{await migration.updateMacro?.(current)}catch(err){console.error(err)}return current}async getUpdatedJournalEntry(source,migrations){const clone=foundry.utils.deepClone(source);for(const migration of migrations)try{await migration.updateJournalEntry?.(clone)}catch(err){console.error(err)}return clone}async getUpdatedToken(token,migrations){const current=token.toObject();for(const migration of migrations)await migration.updateToken?.(current,token.actor,token.scene);return current}async getUpdatedUser(userData,migrations){const current=foundry.utils.deepClone(userData);for(const migration of migrations)try{await migration.updateUser?.(current)}catch(err){console.error(err)}return current}#updateMigrationRecord(migrations,latestMigration){if(!("game"in globalThis&&latestMigration))return;const fromVersion=typeof migrations.version=="number"?migrations.version:null;migrations.version=latestMigration.version,migrations.previous={schema:fromVersion,foundry:game.version,system:game.system.version}}}class Progress{static{__name(this,"Progress")}static{__name2(this,"Progress")}value=0;max;label;constructor({max,label}){this.label=label??"",this.max=max}advance({by=1,label=this.label}={}){if(this.value===this.max)return;this.value+=Math.abs(by);const pct=Math.floor(this.value/this.max*100);SceneNavigation.displayProgressBar({label,pct})}close({label=""}={}){SceneNavigation.displayProgressBar({label,pct:100})}}class MigrationRunner extends MigrationRunnerBase{static{__name(this,"MigrationRunner")}static{__name2(this,"MigrationRunner")}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)<currentVersion){const runner=new this(migrations),source=document2._source,updated=await(async()=>{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._migration.version":currentVersion}),"items"in document2&&"token"in document2)for(const item of document2.items)item.schemaVersion||item.updateSource({"system._migration.version":currentVersion})}async#migrateDocuments(collection,migrations,progress){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}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}finally{updateGroup.length=0}const updated="items"in document2?await this.#migrateActor(migrations,document2,{pack}):await this.#migrateItem(migrations,document2);updated&&updateGroup.push(updated)}if(updateGroup.length>0)try{await DocumentClass.updateDocuments(updateGroup,{noHook:!0,pack}),progress?.advance({by:updateGroup.length})}catch(error){console.warn(error)}}async#migrateItem(migrations,item){const baseItem=item.toObject();try{return this.getUpdatedItem(baseItem,migrations)}catch(error){return error instanceof Error&&console.error(`Error thrown while migrating ${item.uuid}: ${error.message}`),null}}async#migrateActor(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;actor.effects.size>0&&actor.deleteEmbeddedDocuments("ActiveEffect",[],{deleteAll:!0});const baseItems=[...baseActor.items],updatedItems=[...updatedActor.items],itemDiff=this.diffCollection(baseItems,updatedItems),finalDeleted=itemDiff.deleted.filter(id=>actor.items.has(id));if(finalDeleted.length>0)try{await actor.deleteEmbeddedDocuments("Item",finalDeleted,{noHook:!0,pack})}catch(error){console.warn(error)}const finalUpdated=itemDiff.updated.filter(i=>actor.items.has(i._id));return updatedActor.items=[...itemDiff.inserted,...finalUpdated],updatedActor}async#migrateWorldJournalEntry(journalEntry,migrations){if(migrations.some(migration=>!!migration.updateJournalEntry))try{const updated=await this.getUpdatedJournalEntry(journalEntry.toObject(),migrations),changes=foundry.utils.diffObject(journalEntry.toObject(),updated);Object.keys(changes).length>0&&await journalEntry.update(changes,{noHook:!0})}catch(error){console.warn(error)}}async#migrateWorldMacro(macro,migrations){if(migrations.some(migration=>!!migration.updateMacro))try{const updatedMacro=await this.getUpdatedMacro(macro.toObject(),migrations),changes=foundry.utils.diffObject(macro.toObject(),updatedMacro);Object.keys(changes).length>0&&await macro.update(changes,{noHook:!0})}catch(error){console.warn(error)}}async#migrateWorldTable(table,migrations){if(migrations.some(migration=>!!migration.updateTable))try{const updatedMacro=await this.getUpdatedTable(table.toObject(),migrations),changes=foundry.utils.diffObject(table.toObject(),updatedMacro);Object.keys(changes).length>0&&table.update(changes,{noHook:!0})}catch(error){console.warn(error)}}async#migrateSceneToken(token,migrations){if(!migrations.some(migration=>!!migration.updateToken))return token.toObject();try{const updatedToken=await this.getUpdatedToken(token,migrations),changes=foundry.utils.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}}async#migrateUser(user,migrations){if(migrations.some(migration=>!!migration.updateUser))try{const baseUser=user.toObject(),updatedUser=await this.getUpdatedUser(baseUser,migrations),changes=foundry.utils.diffObject(user.toObject(),updatedUser);Object.keys(changes).length>0&&await user.update(changes,{noHook:!0})}catch(error){console.error(error)}}async runCompendiumMigration(compendium){const pack=compendium.metadata.id;ui.notifications.info(game.i18n.format("PF2E.Migrations.Starting",{version:game.system.version}));const documents=await compendium.getDocuments();await compendium.documentClass.updateDocuments(documents,{diff:!1,recursive:!1,pack}),ui.notifications.info(game.i18n.format("PF2E.Migrations.Finished",{version:game.system.version}))}async runMigrations(migrations){if(migrations.length===0)return;const progress=new Progress({label:game.i18n.localize("PF2E.Migrations.Running"),max:Math.floor(game.actors.size+game.items.size+game.scenes.map(s=>s.tokens.contents).flat().filter(t=>t.actor?.isToken).length)});await this.#migrateDocuments(game.actors,migrations,progress),await this.#migrateDocuments(game.items,migrations,progress);for(const entry of game.journal)await this.#migrateWorldJournalEntry(entry,migrations);const promises=[];for(const macro of game.macros)promises.push(this.#migrateWorldMacro(macro,migrations));for(const table of game.tables)promises.push(this.#migrateWorldTable(table,migrations));for(const user of game.users)promises.push(this.#migrateUser(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 this.#migrateSceneToken(token,migrations))continue;const deltaSource=token.delta?._source,hasMigratableData=!!deltaSource&&!!deltaSource.flags?.pf2e||((deltaSource??{}).items??[]).length>0||Object.keys(deltaSource?.system??{}).length>0;if(actor.isToken){if(hasMigratableData){const updated=await this.#migrateActor(migrations,actor);if(updated)try{await actor.update(updated,{noHook:!0})}catch(error){console.warn(error)}}progress.advance()}}progress.value<progress.max&&progress.close()}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}));const migrationsToRun=force?this.migrations:this.migrations.filter(x=>schemaVersion.current<x.version),migrationPhases=[[]];for(const migration of migrationsToRun)migrationPhases[migrationPhases.length-1].push(migration),migration.requiresFlush&&migrationPhases.push([]);for(const migrationPhase of migrationPhases)migrationPhase.length>0&&await this.runMigrations(migrationPhase);await game.settings.set("pf2e","worldSchemaVersion",schemaVersion.latest)}}class MigrationBase{static{__name(this,"MigrationBase")}static{__name2(this,"MigrationBase")}static version;version=this.constructor.version;requiresFlush=!1}class Migration634PurgeMartialItems extends MigrationBase{static{__name(this,"Migration634PurgeMartialItems")}static{__name2(this,"Migration634PurgeMartialItems")}static version=.634;async updateActor(actorData){const martialIds=actorData.items.filter(itemData=>itemData.type==="martial").map(itemData=>itemData._id),martialItemWeapons=actorData.items.filter(itemData=>{if(itemData.type!=="weapon")return!1;const systemData=itemData.system;return martialIds.includes(systemData.weaponType?.value??"")});for(const weaponData of martialItemWeapons)weaponData.data.category="simple";actorData.items=actorData.items.filter(itemData=>itemData.type!=="martial")}}const PHYSICAL_ITEM_TYPES=new Set(["armor","backpack","book","consumable","equipment","shield","treasure","weapon"]),PRECIOUS_MATERIAL_TYPES=new Set(["abysium","adamantine","cold-iron","duskwood","djezet","dragonhide","grisantian-pelt","inubrix","keep-stone","dawnsilver","noqual","orichalcum","peachwood","siccatite","silver","sisterstone","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),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 Migration635NumifyACAndQuantity extends MigrationBase{static{__name(this,"Migration635NumifyACAndQuantity")}static{__name2(this,"Migration635NumifyACAndQuantity")}static version=.635;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))}}}class Migration636NumifyArmorData extends MigrationBase{static{__name(this,"Migration636NumifyArmorData")}static{__name2(this,"Migration636NumifyArmorData")}static version=.636;async updateItem(source){if(source.type!=="armor")return;const systemData=source.system;isObject(systemData.armor)&&(systemData.armor.value=Number(systemData.armor.value)||0),isObject(systemData.check)&&(systemData.check.value=Number(systemData.check.value)||0),isObject(systemData.dex)&&(systemData.dex.value=Number(systemData.dex.value)||0),isObject(systemData.strength)&&(systemData.strength.value=Number(systemData.strength.value)||0),isObject(systemData.speed)&&typeof systemData.speed.value=="string"&&(systemData.speed.value=parseInt(systemData.speed.value,10)||0)}}const meleeKeys=new Set(["description","source","traits","rules","slug","weaponType","attack","damageRolls","bonus","attackEffects"]);class Migration637CleanMeleeItems extends MigrationBase{static{__name(this,"Migration637CleanMeleeItems")}static{__name2(this,"Migration637CleanMeleeItems")}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]}}const validComponents=["material","somatic","verbal"];class Migration638SpellComponents extends MigrationBase{static{__name(this,"Migration638SpellComponents")}static{__name2(this,"Migration638SpellComponents")}static version=.638;async updateItem(source){if(source.type!=="spell")return;const components="components"in source.system&&isObject(source.system.components)?source.system.components:{value:""},oldComponents=new Set(String(components.value).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)}}const REINFORCING_RUNE_LOC_PATHS=[null,"PF2E.Item.Shield.Rune.Reinforcing.Minor","PF2E.Item.Shield.Rune.Reinforcing.Lesser","PF2E.Item.Shield.Rune.Reinforcing.Moderate","PF2E.Item.Shield.Rune.Reinforcing.Greater","PF2E.Item.Shield.Rune.Reinforcing.Major","PF2E.Item.Shield.Rune.Reinforcing.Supreme"],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"],STACK_DEFINITIONS={bolts:{size:10,lightBulk:1},arrows:{size:10,lightBulk:1},slingBullets:{size:10,lightBulk:1},blowgunDarts:{size:10,lightBulk:1},woodenTaws:{size:10,lightBulk:1},rounds5:{size:5,lightBulk:1},rounds10:{size:10,lightBulk:1},coins:{size:1e3,lightBulk:10},gems:{size:2e3,lightBulk:10}};class Bulk{static{__name(this,"Bulk")}static{__name2(this,"Bulk")}value;constructor(value=0){this.value=Math.round(Math.max(value,0)*10)/10}get normal(){return Math.floor(this.value)}get light(){return Math.round((this.value-this.normal)*10)}get isNegligible(){return this.value===0}get isLight(){return this.value>0&&this.value<1}toLightUnits(){return this.normal*10+this.light}increment(){return this.isNegligible?new Bulk(.1):this.isLight?new Bulk(1):new Bulk(this.value+1)}plus(other){const otherValue=typeof other=="number"?other:other.value;return new Bulk(this.value+otherValue)}minus(other){const otherValue=typeof other=="number"?other:other.value;return new Bulk(this.value-otherValue)}times(factor){return new Bulk(Math.round(this.value*factor*10)/10)}toString(){const{light,normal}=this;return this.isNegligible?game.i18n.localize("PF2E.Item.Physical.Bulk.Negligible.ShortLabel"):this.value===normal?normal.toString():normal===0&&light===1?game.i18n.localize("PF2E.Item.Physical.Bulk.Light.ShortLabel"):light>0&&normal===0?game.i18n.format("PF2E.Item.Physical.Bulk.NLight",{light}):game.i18n.format("PF2E.Item.Physical.Bulk.WithLight",{bulk:normal,light})}double(){return this.isNegligible?new Bulk(.1):this.isLight?new Bulk(1):this.times(2)}halve(){return this.isNegligible||this.isLight?new Bulk:this.normal===1?new Bulk(.1):this.times(.5)}convertToSize(itemSize,actorSize){const sizes=Array.from(SIZES).filter(size=>size!=="sm"),itemSizeIndex=sizes.indexOf(itemSize==="sm"?"med":itemSize),actorSizeIndex=sizes.indexOf(actorSize==="sm"?"med":actorSize);return itemSizeIndex===actorSizeIndex?this:itemSizeIndex>actorSizeIndex?applyNTimes(bulk=>bulk.double(),itemSizeIndex-actorSizeIndex,this):applyNTimes(bulk=>bulk.halve(),actorSizeIndex-itemSizeIndex,this)}}class CoinsPF2e{static{__name(this,"CoinsPF2e")}static{__name2(this,"CoinsPF2e")}constructor(data){data??={};for(const denomination of DENOMINATIONS)this[denomination]=Math.max(Math.floor(Math.abs(data[denomination]??0)),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(", ")}}const coinCompendiumIds={pp:"JuNPeK5Qm1w6wpb4",gp:"B6B7tBWJSqOBz5zz",sp:"5Ew82vBF9YfaiY9f",cp:"lzJ8AVhRcbFul5fh"};function getMaterialValuationData(item){const{material}=item;if(!material.type||!material.grade)return null;const valuationData=item.isOfType("weapon")?MATERIAL_DATA.weapon:item.isOfType("armor")?MATERIAL_DATA.armor:item.isOfType("shield")?item.isBuckler?MATERIAL_DATA.shield.buckler:item.isTowerShield?MATERIAL_DATA.shield.towerShield:MATERIAL_DATA.shield.shield:null;return valuationData?valuationData[material.type]?.[material.grade]??null:null}__name(getMaterialValuationData,"getMaterialValuationData"),__name2(getMaterialValuationData,"getMaterialValuationData");const WEAPON_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},dawnsilver:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:18,price:22e3,rarity:"rare"}},duskwood:{low:null,standard:{level:11,price:1400,rarity:"uncommon"},high:{level:17,price:13500,rarity:"uncommon"}},inubrix:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:13500,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:18,price:24e3,rarity:"rare"}},peachwood:{low:null,standard:{level:12,price:2e3,rarity:"uncommon"},high:{level:18,price:19e3,rarity:"uncommon"}},orichalcum:{low:null,standard:null,high:{level:18,price:22500,rarity:"rare"}},siccatite:{low:null,standard:{level:11,price:1400,rarity:"rare"},high:{level:17,price:15e3,rarity:"rare"}},silver:{low:{level:2,price:40,rarity:"common"},standard:{level:10,price:880,rarity:"common"},high:{level:16,price:9e3,rarity:"common"}},"sisterstone-dusk":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sisterstone-scarlet":{low:{level:3,price:70,rarity:"rare"},standard:{level:11,price:1200,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},warpglass:{low:null,standard:null,high:{level:17,price:14e3,rarity:"rare"}}},ARMOR_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:12,price:2e3,rarity:"rare"},high:{level:19,price:4e4,rarity:"rare"}},adamantine:{low:null,standard:{level:11,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"cold-iron":{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},dawnsilver:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},djezet:{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:35e3,rarity:"rare"}},dragonhide:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},duskwood:{low:null,standard:{level:12,price:1600,rarity:"uncommon"},high:{level:19,price:32e3,rarity:"uncommon"}},"grisantian-pelt":{low:null,standard:{level:12,price:1800,rarity:"rare"},high:{level:19,price:33e3,rarity:"rare"}},inubrix:{low:null,standard:{level:11,price:1200,rarity:"rare"},high:{level:18,price:18e3,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:20,price:56e3,rarity:"rare"}},noqual:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},peachwood:{low:null,standard:null,high:null},orichalcum:{low:null,standard:null,high:{level:20,price:55e3,rarity:"rare"}},siccatite:{low:null,standard:{level:12,price:1600,rarity:"rare"},high:{level:19,price:32e3,rarity:"rare"}},silver:{low:{level:5,price:140,rarity:"common"},standard:{level:11,price:1200,rarity:"common"},high:{level:18,price:2e4,rarity:"common"}},"sisterstone-dusk":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sisterstone-scarlet":{low:{level:5,price:140,rarity:"rare"},standard:{level:10,price:1e3,rarity:"rare"},high:{level:18,price:19500,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:13,price:2400,rarity:"rare"},high:{level:20,price:5e4,rarity:"rare"}},warpglass:{low:null,standard:null,high:null}},OBJECT_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:8,price:450,rarity:"rare"},high:{level:16,price:7500,rarity:"rare"}},adamantine:{low:null,standard:{level:8,price:350,rarity:"uncommon"},high:{level:16,price:6e3,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:20,rarity:"common"},standard:{level:7,price:250,rarity:"common"},high:{level:15,price:4500,rarity:"common"}},dawnsilver:{low:null,standard:{level:8,price:350,rarity:"uncommon"},high:{level:16,price:6e3,rarity:"uncommon"}},djezet:{low:null,standard:{level:8,price:400,rarity:"rare"},high:{level:16,price:7e3,rarity:"rare"}},duskwood:{low:null,standard:{level:8,price:350,rarity:"uncommon"},high:{level:16,price:6e3,rarity:"uncommon"}},inubrix:{low:null,standard:{level:8,price:400,rarity:"rare"},high:{level:16,price:1600,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:17,price:9e3,rarity:"rare"}},noqual:{low:null,standard:{level:8,price:400,rarity:"rare"},high:{level:16,price:7e3,rarity:"rare"}},orichalcum:{low:null,standard:null,high:{level:17,price:1e4,rarity:"rare"}},peachwood:{low:null,standard:{level:8,price:500,rarity:"uncommon"},high:{level:16,price:7500,rarity:"uncommon"}},siccatite:{low:null,standard:{level:8,price:350,rarity:"rare"},high:{level:16,price:6e3,rarity:"rare"}},silver:{low:{level:2,price:20,rarity:"common"},standard:{level:7,price:250,rarity:"common"},high:{level:15,price:4500,rarity:"common"}},sisterstone:{low:{level:3,price:30,rarity:"rare"},standard:{level:8,price:350,rarity:"rare"},high:{level:16,price:5500,rarity:"rare"}},"sovereign-steel":{low:null,standard:{level:9,price:500,rarity:"rare"},high:{level:17,price:8e3,rarity:"rare"}},warpglass:{low:null,standard:null,high:{level:17,price:8e3,rarity:"rare"}}},BUCKLER_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:8,price:400,hardness:4,maxHP:16,rarity:"rare"},high:{level:16,price:8e3,hardness:7,maxHP:28,rarity:"rare"}},adamantine:{low:null,standard:{level:8,price:400,rarity:"uncommon",hardness:8,maxHP:32},high:{level:16,price:8e3,hardness:11,maxHP:44,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:30,hardness:3,maxHP:12,rarity:"common"},standard:{level:7,price:300,hardness:5,maxHP:20,rarity:"common"},high:{level:15,price:5e3,hardness:8,maxHP:32,rarity:"common"}},dawnsilver:{low:null,standard:{level:8,price:400,hardness:3,maxHP:12,rarity:"uncommon"},high:{level:16,price:8e3,hardness:6,maxHP:24,rarity:"uncommon"}},djezet:{low:null,standard:{level:9,price:600,hardness:3,maxHP:12,rarity:"rare"},high:{level:16,price:8e3,hardness:6,maxHP:24,rarity:"rare"}},duskwood:{low:null,standard:{level:8,price:400,hardness:3,maxHP:12,rarity:"uncommon"},high:{level:16,price:8e3,hardness:5,maxHP:20,rarity:"uncommon"}},inubrix:{low:null,standard:{level:7,price:320,hardness:2,maxHP:8,rarity:"rare"},high:{level:15,price:5e3,hardness:5,maxHP:20,rarity:"rare"}},noqual:{low:null,standard:null,high:{level:17,price:14e3,hardness:7,maxHP:28,rarity:"rare"}},orichalcum:{low:null,standard:null,high:{level:17,price:12e3,hardness:14,maxHP:56,rarity:"rare"}},siccatite:{low:null,standard:{level:8,price:400,hardness:4,maxHP:16,rarity:"rare"},high:{level:16,price:8e3,hardness:7,maxHP:28,rarity:"rare"}},silver:{low:{level:2,price:30,hardness:1,maxHP:4,rarity:"common"},standard:{level:7,price:300,hardness:3,maxHP:12,rarity:"common"},high:{level:15,price:5e3,hardness:6,maxHP:24,rarity:"common"}}},SHIELD_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},abysium:{low:null,standard:{level:8,price:440,hardness:6,maxHP:24,rarity:"rare"},high:{level:16,price:8800,hardness:10,maxHP:40,rarity:"rare"}},adamantine:{low:null,standard:{level:8,price:440,rarity:"uncommon",hardness:10,maxHP:40},high:{level:16,price:8800,hardness:13,maxHP:52,rarity:"uncommon"}},"cold-iron":{low:{level:2,price:34,hardness:5,maxHP:20,rarity:"common"},standard:{level:7,price:340,hardness:7,maxHP:28,rarity:"common"},high:{level:15,price:5500,hardness:10,maxHP:40,rarity:"common"}},dawnsilver:{low:null,standard:{level:8,price:440,hardness:5,maxHP:20,rarity:"uncommon"},high:{level:16,price:8800,hardness:8,maxHP:32,rarity:"uncommon"}},djezet:{low:null,standard:{level:9,price:660,hardness:5,maxHP:20,rarity:"rare"},high:{level:16,price:8800,hardness:8,maxHP:32,rarity:"rare"}},duskwood:{low:null,standard:{level:8,price:440,hardness:5,maxHP:20,rarity:"uncommon"},high:{level:16,price:8800,hardness:8,maxHP:32,rarity:"uncommon"}},inubrix:{low:null,standard:{level:7,price:352,hardness:4,maxHP:16,rarity:"rare"},high:{level:15,price:5500,hardness:7,maxHP:28,rarity:"rare"}},"keep-stone":{low:null,standard:null,high:{level:17,price:13200,hardness:11,maxHP:46,rarity:"rare"}},noqual:{low:null,standard:null,high:{level:17,price:15400,hardness:10,maxHP:40,rarity:"rare"}},orichalcum:{low:null,standard:null,high:{level:17,price:13200,hardness:16,maxHP:64,rarity:"rare"}},siccatite:{low:null,standard:{level:8,price:440,hardness:6,maxHP:24,rarity:"rare"},high:{level:16,price:8800,hardness:10,maxHP:40,rarity:"rare"}},silver:{low:{level:2,price:34,hardness:3,maxHP:12,rarity:"common"},standard:{level:7,price:340,hardness:5,maxHP:20,rarity:"common"},high:{level:15,price:5500,hardness:8,maxHP:32,rarity:"common"}}},TOWER_SHIELD_MATERIAL_VALUATION_DATA={"":{low:null,standard:null,high:null},duskwood:{low:null,standard:{level:8,price:560,hardness:5,maxHP:20,rarity:"uncommon"},high:{level:16,price:11200,hardness:8,maxHP:32,rarity:"uncommon"}}},MATERIAL_DATA={armor:ARMOR_MATERIAL_VALUATION_DATA,object:OBJECT_MATERIAL_VALUATION_DATA,shield:{shield:SHIELD_MATERIAL_VALUATION_DATA,buckler:BUCKLER_MATERIAL_VALUATION_DATA,towerShield:TOWER_SHIELD_MATERIAL_VALUATION_DATA},weapon:WEAPON_MATERIAL_VALUATION_DATA};function computePrice(item){const basePrice=item.price.value;if(item.isOfType("treasure"))return basePrice;const materialPrice=getMaterialValuationData(item)?.price??0,heldOrStowedBulk=new Bulk(item.system.bulk.heldOrStowed),bulk=Math.max(Math.ceil(heldOrStowedBulk.normal),1),materialValue=item.isSpecific?0:materialPrice+bulk*materialPrice/10,runesData=getRuneValuationData(item),reinforcingRuneValue=!item.isOfType("shield")||item.isSpecific?0:RUNE_DATA.shield.reinforcing[item.system.runes.reinforcing]?.price??0,runeValue=item.isSpecific?0:runesData.reduce((sum,rune)=>sum+rune.price,0)-reinforcingRuneValue,afterMaterialAndRunes=runeValue?new CoinsPF2e({gp:runeValue+materialValue}):basePrice.add({gp:materialValue}),afterReinforcingRune=(afterMaterialAndRunes.copperValue>basePrice.copperValue?afterMaterialAndRunes:basePrice).add(new CoinsPF2e({gp:reinforcingRuneValue})),afterShoddy=item.isShoddy?afterReinforcingRune.scale(.5):afterReinforcingRune;return item.isMagical?afterShoddy:afterShoddy.adjustForSize(item.size)}__name(computePrice,"computePrice"),__name2(computePrice,"computePrice");function computeLevelRarityPrice(item){const materialData=getMaterialValuationData(item),price=computePrice(item);if(!(item.isMagical||materialData)||item.isSpecific)return{...pick(item,["level","rarity"]),price};const runesData=getRuneValuationData(item),level=runesData.map(r=>r.level).concat(materialData?.level??0).reduce((highest,level2)=>level2>highest?level2:highest,item.level),rarityOrder={common:0,uncommon:1,rare:2,unique:3},baseRarity=item.rarity,rarity=runesData.map(runeData=>runeData.rarity).concat(materialData?.rarity??"common").reduce((highest,rarity2)=>rarityOrder[rarity2]>rarityOrder[highest]?rarity2:highest,baseRarity);return{level,rarity,price}}__name(computeLevelRarityPrice,"computeLevelRarityPrice"),__name2(computeLevelRarityPrice,"computeLevelRarityPrice");function generateItemName(item){if(!item.isOfType("armor","shield","weapon"))return item.name;const[baseItemDictionary,propertyDictionary,fundamentalTwoDictionary]=item.isOfType("armor")?[CONFIG.PF2E.baseArmorTypes,RUNE_DATA.armor.property,RUNE_DATA.armor.resilient]:item.isOfType("shield")?[CONFIG.PF2E.baseShieldTypes,null,null]:[{...CONFIG.PF2E.baseWeaponTypes,...CONFIG.PF2E.baseShieldTypes},RUNE_DATA.weapon.property,RUNE_DATA.weapon.striking],storedName=item._source.name,baseType=item.baseType??"";if(!baseType||!(baseType in baseItemDictionary)||item.isSpecific||storedName!==game.i18n.localize(baseItemDictionary[baseType]??""))return item.name;const{runes,material}=item.system,potency="potency"in runes?runes.potency:null,fundamental2="resilient"in runes?runes.resilient:"striking"in runes?runes.striking:null,reinforcing="reinforcing"in runes&&game.i18n.localize(REINFORCING_RUNE_LOC_PATHS[runes.reinforcing]??"")||null,params={base:baseType?material.type&&["hide-armor","steel-shield","wooden-shield"].includes(baseType)?game.i18n.localize(`TYPES.Item.${item.type}`):game.i18n.localize(baseItemDictionary[baseType]??""):item.name,material:material.type&&game.i18n.localize(CONFIG.PF2E.preciousMaterials[material.type]),potency,reinforcing,fundamental2:fundamental2&&fundamentalTwoDictionary&&game.i18n.localize(fundamentalTwoDictionary[fundamental2]?.name??"")||null};if("property"in runes&&propertyDictionary)for(const index of[0,1,2,3])params[`property${index+1}`]=game.i18n.localize(propertyDictionary[runes.property[index]]?.name??"")||null;const formatString=(()=>{const potency2=params.potency?"Potency":null,reinforcing2=params.reinforcing?"Reinforcing":null,fundamental22=params.fundamental2&&"Fundamental2",properties=params.property4?"FourProperties":params.property3?"ThreeProperties":params.property2?"TwoProperties":params.property1?"OneProperty":null,material2=params.material&&"Material",key=compact([potency2,reinforcing2,fundamental22,properties,material2]).join("")||null;return key&&game.i18n.localize(key)})();return formatString?game.i18n.format(`PF2E.Item.Physical.GeneratedName.${formatString}`,params):item.name}__name(generateItemName,"generateItemName"),__name2(generateItemName,"generateItemName");function handleHPChange(item,changed){for(const property of["value","max"])changed.system?.hp&&changed.system.hp[property]!==void 0&&(changed.system.hp[property]=Math.max(Math.floor(Number(changed.system.hp[property])),0)||0);const actorSource=item.actor?.toObject(),changedSource=item.clone(foundry.utils.deepClone(changed),{keepId:!0}).toObject(),itemIndex=actorSource?.items.findIndex(i=>i._id===item._id);if(itemIndex===-1)return;actorSource?.items.splice(itemIndex??0,1,changedSource);const itemClone=(actorSource?new ActorProxyPF2e(actorSource):null)?.inventory.get(item.id,{strict:!0})??item.clone(changed,{keepId:!0}),maxHPDifference=itemClone.system.hp.max-item.system.hp.max;maxHPDifference!==0&&(changed.system=foundry.utils.mergeObject(changed.system??{},{hp:{value:Math.max(item.system.hp.value+maxHPDifference,0)}})),(changed.system?.hp?.value??itemClone.system.hp.value)>itemClone.system.hp.max&&(changed.system=foundry.utils.mergeObject(changed.system??{},{hp:{value:itemClone.system.hp.max}}))}__name(handleHPChange,"handleHPChange"),__name2(handleHPChange,"handleHPChange");function prepareBulkData(item){const per=(STACK_DEFINITIONS[item.system.stackGroup??""]??null)?.size??1,sourceBulk=item._source.system.bulk,heldOrStowed=item.isOfType("armor")?new Bulk(sourceBulk.value).increment().value:"heldOrStowed"in sourceBulk?Number(sourceBulk.heldOrStowed)||0:sourceBulk.value,worn=item.system.bulk.value,value=!item.actor||item.isEquipped?worn:heldOrStowed,data={heldOrStowed,value,per};return item.isOfType("backpack")?{...data,capacity:item.system.bulk.capacity,ignored:item.system.bulk.ignored}:data}__name(prepareBulkData,"prepareBulkData"),__name2(prepareBulkData,"prepareBulkData");class Migration639NormalizeLevelAndPrice extends MigrationBase{static{__name(this,"Migration639NormalizeLevelAndPrice")}static{__name2(this,"Migration639NormalizeLevelAndPrice")}static version=.639;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 system=source.system,price=system.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=system.quantity,priceValue=price.value;CoinsPF2e.fromString(priceValue,quantity).copperValue&&(price.value="0 gp")}}}class Migration640CantripsAreNotZeroLevel extends MigrationBase{static{__name(this,"Migration640CantripsAreNotZeroLevel")}static{__name2(this,"Migration640CantripsAreNotZeroLevel")}static version=.64;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"))}}class Migration641SovereignSteelValue extends MigrationBase{static{__name(this,"Migration641SovereignSteelValue")}static{__name2(this,"Migration641SovereignSteelValue")}static version=.641;async updateItem(source){if(source.type!=="weapon")return;const material=source.system.preciousMaterial??{};material.value?.toLowerCase()==="sovereign steel"&&(material.value="sovereignSteel")}}class Migration642TrackSchemaVersion extends MigrationBase{static{__name(this,"Migration642TrackSchemaVersion")}static{__name2(this,"Migration642TrackSchemaVersion")}static version=.642;async updateActor(actorSource){actorSource.system.schema??={version:null,lastMigration:null}}async updateItem(itemSource){itemSource.system.schema??={version:null,lastMigration:null}}}class Migration643HazardLevel extends MigrationBase{static{__name(this,"Migration643HazardLevel")}static{__name2(this,"Migration643HazardLevel")}static version=.643;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}}}}const defaultTraditionByClass$1={wizard:"arcane",cleric:"divine",druid:"primal",bard:"occult",ranger:"primal",champion:"divine",monk:"divine"};class Migration644SpellcastingCategory extends MigrationBase{static{__name(this,"Migration644SpellcastingCategory")}static{__name2(this,"Migration644SpellcastingCategory")}static version=.644;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"}}}}class Migration645TokenImageSize extends MigrationBase{static{__name(this,"Migration645TokenImageSize")}static{__name2(this,"Migration645TokenImageSize")}static version=.645;#imageOverrides=new Map;#sizeOverrides=new Map;#isTokenImageFlag(flag){return typeof flag=="string"}#isTokenSizeFlag(flag){return flag instanceof Object&&"height"in flag&&typeof flag.height=="number"&&"width"in flag&&typeof flag.width=="number"}async updateActor(actorSource){const flags=actorSource.flags,originalImg=flags.pf2e?.token?.img;this.#isTokenImageFlag(originalImg)&&this.#imageOverrides.set(actorSource._id,originalImg);const originalSize=flags.pf2e?.token?.size;this.#isTokenSizeFlag(originalSize)&&this.#sizeOverrides.set(actorSource._id,originalSize),typeof flags.pf2e?.token=="object"&&("game"in globalThis&&(flags.pf2e["-=token"]=null),delete flags.pf2e.token)}async updateToken(tokenSource,actor){tokenSource.texture.src=this.#imageOverrides.get(actor?.id??"")??tokenSource.texture.src;const sizeOverride=this.#sizeOverrides.get(actor?.id??"");tokenSource.height=sizeOverride?.height??tokenSource.height,tokenSource.width=sizeOverride?.width??tokenSource.width}}class Migration646UpdateInlineLinks extends MigrationBase{static{__name(this,"Migration646UpdateInlineLinks")}static{__name2(this,"Migration646UpdateInlineLinks")}static version=.646;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??"")}}class Migration647FixPCSenses extends MigrationBase{static{__name(this,"Migration647FixPCSenses")}static{__name2(this,"Migration647FixPCSenses")}static version=.647;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=[]}}class Migration648RemoveInvestedProperty extends MigrationBase{static{__name(this,"Migration648RemoveInvestedProperty")}static{__name2(this,"Migration648RemoveInvestedProperty")}static version=.648;async updateItem(itemSource){if(!(itemSource.type==="treasure"||itemSource.type==="consumable"))return;const systemData=itemSource.system;delete systemData.invested,"game"in globalThis&&(systemData["-=invested"]=null)}}function isCreatureSource(source){return["character","npc"].includes(source.type)}__name(isCreatureSource,"isCreatureSource"),__name2(isCreatureSource,"isCreatureSource");class Migration649FocusToActor extends MigrationBase{static{__name(this,"Migration649FocusToActor")}static{__name2(this,"Migration649FocusToActor")}static version=.649;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)=>(b.focus?.pool||0)-(a.focus?.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)}}class Migration650StringifyWeaponProperties extends MigrationBase{static{__name(this,"Migration650StringifyWeaponProperties")}static{__name2(this,"Migration650StringifyWeaponProperties")}static version=.65;async updateItem(itemData){if(itemData.type!=="weapon")return;const systemData=itemData.system;systemData.weaponType&&(systemData.weaponType.value||="simple");const range2=systemData.range??={value:"melee"};range2 instanceof Object&&typeof range2.value=="string"&&(range2.value=range2.value.trim()||"melee",range2.value==="reach"&&(range2.value="melee"))}}class Migration651EphemeralFocusPool extends MigrationBase{static{__name(this,"Migration651EphemeralFocusPool")}static{__name2(this,"Migration651EphemeralFocusPool")}static version=.651;#needsRuleElement(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")}#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"]);#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateActor(source){if(source.type!=="character")return;const systemData=source.system;systemData.resources??={};const resources=systemData.resources;typeof resources.focus?.max=="number"&&"game"in globalThis?resources.focus["-=max"]=null:delete resources.focus?.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)&&this.#isClassFeature(source)?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"upgrade",value:1,priority:10}:this.#increasesByOne.has(slug)||slug.startsWith("first-revelation-")?{key:"ActiveEffectLike",path:"system.resources.focus.max",mode:"add",value:1}:null})();rule&&this.#needsRuleElement(source.system.rules)&&systemData.rules.push(rule)}}const defaultTraditionByClass={wizard:"arcane",druid:"primal",ranger:"primal"};class Migration652KillHalcyonTradition extends MigrationBase{static{__name(this,"Migration652KillHalcyonTradition")}static{__name2(this,"Migration652KillHalcyonTradition")}static version=.652;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"}}}class Migration653AEstoREs extends MigrationBase{static{__name(this,"Migration653AEstoREs")}static{__name2(this,"Migration653AEstoREs")}static version=.653;#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=>{const origin=effect.origin??"",itemId=/\bItem\.([A-Za-z0-9]{16})$/.exec(origin)?.[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??50};rules.push(newRule)}effect.changes=effect.changes.filter(change=>!this.#isRemoveableChange(change))}itemSource.effects=itemSource.effects.filter(effect=>!this.#isRemovableAE(effect))}}class Migration654ActionTypeAndCount extends MigrationBase{static{__name(this,"Migration654ActionTypeAndCount")}static{__name2(this,"Migration654ActionTypeAndCount")}static version=.654;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}}class Migration655CreatureTokenSizes extends MigrationBase{static{__name(this,"Migration655CreatureTokenSizes")}static{__name2(this,"Migration655CreatureTokenSizes")}static version=.655;#isTokenSizeRE(rule){return typeof rule.key=="string"&&rule.key.endsWith("TokenSize")}#isActorSizeAELike(rule){return typeof rule.key=="string"&&rule.key.endsWith("ActiveEffectLike")&&rule.path==="system.traits.size.value"}#isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)}dimensionToSize={.5:"tiny",2:"lg",3:"huge",4:"grg"};async updateItem(itemSource){itemSource.system.rules??=[];const rules=itemSource.system.rules,actorSizeAELike=rules.find(this.#isActorSizeAELike),tokenSizeRE=rules.find(this.#isTokenSizeRE);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",this.#isBracketedValue(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)}}class Migration656OtherFocusPoolSources extends MigrationBase{static{__name(this,"Migration656OtherFocusPoolSources")}static{__name2(this,"Migration656OtherFocusPoolSources")}static version=.656;needsRuleElement(rules){return!rules.some(rule=>rule.key==="ActiveEffectLike"&&rule.path==="system.resources.focus.max")}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"]);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)}}class Migration657RemoveSetProperty extends MigrationBase{static{__name(this,"Migration657RemoveSetProperty")}static{__name2(this,"Migration657RemoveSetProperty")}static version=.657;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){itemSource.system.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(setProperty=>({key:"ActiveEffectLike",mode:"override",path:setProperty.property.replace(/^flags\.2e/,"flags.pf2e"),value:setProperty.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"))}}class Migration658MonkUnarmoredProficiency extends MigrationBase{static{__name(this,"Migration658MonkUnarmoredProficiency")}static{__name2(this,"Migration658MonkUnarmoredProficiency")}static version=.658;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)}}const formulaHasValue=__name2(value=>!!value&&value!=="0","formulaHasValue"),modes=["level1","level2","level3","level4"];class Migration659MultipleDamageRows extends MigrationBase{static{__name(this,"Migration659MultipleDamageRows")}static{__name2(this,"Migration659MultipleDamageRows")}static version=.659;async updateItem(source){if(source.type!=="spell")return;const data=source.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:data.damageType?.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)}}class Migration660DerivedSpellTraits extends MigrationBase{static{__name(this,"Migration660DerivedSpellTraits")}static{__name2(this,"Migration660DerivedSpellTraits")}static version=.66;#MAGIC_SCHOOLS=new Set(["abjuration","conjuration","divination","enchantment","evocation","illusion","necromancy","transmutation"]);#derivedTraits=[...this.#MAGIC_SCHOOLS,...MAGIC_TRADITIONS];async updateItem(source){if(source.type==="spell"){const traits=source.system.traits;traits.value=traits.value.filter(trait=>!this.#derivedTraits.includes(trait))}}}class Migration661NumifyVehicleDimensions extends MigrationBase{static{__name(this,"Migration661NumifyVehicleDimensions")}static{__name2(this,"Migration661NumifyVehicleDimensions")}static version=.661;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}}}class Migration662LinkToActorSizeDefaults extends MigrationBase{static{__name(this,"Migration662LinkToActorSizeDefaults")}static{__name2(this,"Migration662LinkToActorSizeDefaults")}static version=.662;async updateActor(actorSource){const linkToActorSize=!["hazard","loot"].includes(actorSource.type);actorSource.prototypeToken.flags??={pf2e:{linkToActorSize}},actorSource.prototypeToken.flags.pf2e??={linkToActorSize},actorSource.prototypeToken.flags.pf2e.linkToActorSize??=linkToActorSize}async updateToken(tokenSource,actor){const linkToActorSize=!["hazard","loot"].includes(actor.type);tokenSource.flags.pf2e??={linkToActorSize},tokenSource.flags.pf2e.linkToActorSize??=linkToActorSize}}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{static{__name(this,"Migration663FixSpellDamage")}static{__name2(this,"Migration663FixSpellDamage")}static version=.663;async updateItem(source){if(source.type!=="spell"||Object.keys(source.system.damage?.value??{}).length>0)return;const itemName=source.system.slug??sluggify(source.name),systemData=source.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}}}class Migration664DeleteCUBConditions extends MigrationBase{static{__name(this,"Migration664DeleteCUBConditions")}static{__name2(this,"Migration664DeleteCUBConditions")}static version=.664;async updateActor(actorSource){const cubConditions=actorSource.items.filter(item=>item.type==="condition"&&!item.system.references?.overriddenBy);for(const condition of cubConditions)actorSource.items.findSplice(item=>item===condition)}}class Migration665HandwrapsCorrections extends MigrationBase{static{__name(this,"Migration665HandwrapsCorrections")}static{__name2(this,"Migration665HandwrapsCorrections")}static version=.665;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`)}}class Migration666UsageAndStowingContainers extends MigrationBase{static{__name(this,"Migration666UsageAndStowingContainers")}static{__name2(this,"Migration666UsageAndStowingContainers")}static version=.666;#backpacks=new Set(["backpack","knapsack-of-halflingkind","knapsack-of-halflingkind-greater","sturdy-satchel","vaultbreaker-harness","voyagers-pack"]);#wornGarment=new Set(["sleeves-of-storage","sleeves-of-storage-greater"]);#wornGloves=new Set(["gloves-of-storing"]);#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"]);#stowingContainers=new Set([...this.#backpacks,...this.#heldInTwoHands,...this.#wornGarment,...this.#wornGloves,"extradimensional-stash"]);async updateItem(source){if(!source.system.traits)return;const traits=source.system.traits;if(typeof traits.usage?.value=="string"){const traitUsage=traits.usage.value,isPhysical=isPhysicalData(source),keepUsage=isPhysical&&(traitUsage!=="held-in-one-hand"||source.system.usage?.value==="");isPhysical&&keepUsage&&source.system.usage&&(source.system.usage.value=traits.usage.value),"game"in globalThis?traits["-=usage"]=null:delete traits.usage}if(source.type!=="backpack")return;const slug=source.system.slug??sluggify(source.name);this.#backpacks.has(slug)?source.system.usage.value="wornbackpack":this.#heldInTwoHands.has(slug)?source.system.usage.value="held-in-two-hands":this.#wornGarment.has(slug)?source.system.usage.value="worngarment":this.#wornGloves.has(slug)?source.system.usage.value="worngloves":source.system.usage.value="worn",source.system.stowing=this.#stowingContainers.has(slug)}}class Migration667HPSubProperties extends MigrationBase{static{__name(this,"Migration667HPSubProperties")}static{__name2(this,"Migration667HPSubProperties")}static version=.667;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)}}class Migration668ArmorSpeedPenalty extends MigrationBase{static{__name(this,"Migration668ArmorSpeedPenalty")}static{__name2(this,"Migration668ArmorSpeedPenalty")}static version=.668;async updateItem(itemSource){const slug=itemSource.system.slug??sluggify(itemSource.name);if(itemSource.type==="armor"){const rules=itemSource.system.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]}}}}class Migration669NPCAttackEffects extends MigrationBase{static{__name(this,"Migration669NPCAttackEffects")}static{__name2(this,"Migration669NPCAttackEffects")}static version=.669;async updateItem(item,actor){!actor||item.type!=="melee"||(item.system.attackEffects??={value:[]},Array.isArray(item.system.attackEffects.value)&&item.system.attackEffects.value.forEach((entry,index,arr)=>{arr[index]=sluggify(entry)}))}}class Migration670AncestryVision extends MigrationBase{static{__name(this,"Migration670AncestryVision")}static{__name2(this,"Migration670AncestryVision")}static version=.67;DARKVISION_ID="HHVQDp61ehcpdiU8";LOWLIGHTVISION_ID="DRtaqOHXTRtGRIUT";async updateActor(source){if(source.type!=="character")return;const ancestry=source.items.find(item=>item.type==="ancestry");if(ancestry){this.#setAncestryVision(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&&this.#setAncestryVision(source)}#setAncestryVision(ancestry){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");ancestry.system.vision??="normal"}}class Migration670NoCustomTrait extends MigrationBase{static{__name(this,"Migration670NoCustomTrait")}static{__name2(this,"Migration670NoCustomTrait")}static version=.67;async updateItem(itemSource){const traits=itemSource.system.traits;traits&&(Array.isArray(traits.value)?traits.value=traits.value.filter(trait=>trait&&trait!=="custom"):traits.value=[])}}class Migration671NoPCItemsOnNonPCs extends MigrationBase{static{__name(this,"Migration671NoPCItemsOnNonPCs")}static{__name2(this,"Migration671NoPCItemsOnNonPCs")}static version=.671;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)}}}const PHYSICAL_DAMAGE_TYPES=["bludgeoning","piercing","slashing","bleed"],LIFE_ENERGY_DAMAGE_TYPES=["vitality","void"],ENERGY_DAMAGE_TYPES=["acid","cold","electricity","fire","sonic","force",...LIFE_ENERGY_DAMAGE_TYPES],DAMAGE_CATEGORIES_UNIQUE=new Set(["persistent","precision","splash"]),MATERIAL_DAMAGE_EFFECTS=new Set(["adamantine","cold-iron","dawnsilver","duskwood","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,"mental","poison","spirit","untyped"]),BASE_DAMAGE_TYPES_TO_CATEGORIES={bludgeoning:"physical",piercing:"physical",slashing:"physical",bleed:"physical",acid:"energy",cold:"energy",electricity:"energy",fire:"energy",sonic:"energy",vitality:"energy",void:"energy",force:"energy",mental:null,poison:null,spirit:null,untyped:null},DAMAGE_TYPE_ICONS={bleed:"droplet",acid:"vial",bludgeoning:"hammer",cold:"snowflake",electricity:"bolt",fire:"fire",force:"sparkles",mental:"brain",piercing:"bow-arrow",poison:"spider",slashing:"axe",sonic:"waveform-lines",spirit:"ghost",vitality:"sun",void:"skull",untyped:null},PERSISTENT_DAMAGE_IMAGES={acid:"icons/magic/acid/dissolve-arm-flesh.webp",bludgeoning:"systems/pf2e/icons/equipment/weapons/bola.webp",cold:"icons/magic/water/ice-snowman.webp",electricity:"systems/pf2e/icons/spells/chain-lightning.webp",fire:"icons/magic/fire/flame-burning-creature-skeleton.webp",force:"systems/pf2e/icons/spells/magic-missile.webp",mental:"systems/pf2e/icons/spells/modify-memory.webp",piercing:"systems/pf2e/icons/equipment/weapons/throwing-knife.webp",poison:"systems/pf2e/icons/spells/acidic-burst.webp",slashing:"systems/pf2e/icons/equipment/weapons/scimitar.webp",sonic:"systems/pf2e/icons/spells/cry-of-destruction.webp",spirit:"icons/magic/unholy/hand-claw-fire-blue.webp",vitality:"systems/pf2e/icons/spells/moment-of-renewal.webp",void:"systems/pf2e/icons/spells/grim-tendrils.webp"},CRITICAL_INCLUSION={DOUBLE_ON_CRIT:null,CRITICAL_ONLY:!0,DONT_DOUBLE_ON_CRIT:!1};class MystifiedTraits{static{__name(this,"MystifiedTraits")}static{__name2(this,"MystifiedTraits")}static mystifiedTraits=new Set;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)}}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"],ancestryTraits={aberration:"PF2E.TraitAberration",aiuvarin:"PF2E.TraitAiuvarin",anadi:"PF2E.TraitAnadi",android:"PF2E.TraitAndroid",aphorite:"PF2E.TraitAphorite",ardande:"PF2E.TraitArdande",automaton:"PF2E.TraitAutomaton",azarketi:"PF2E.TraitAzarketi",beastkin:"PF2E.TraitBeastkin",catfolk:"PF2E.TraitCatfolk",changeling:"PF2E.TraitChangeling",conrasu:"PF2E.TraitConrasu",dhampir:"PF2E.TraitDhampir",dromaar:"PF2E.TraitDromaar",duskwalker:"PF2E.TraitDuskwalker",dwarf:"PF2E.TraitDwarf",elf:"PF2E.TraitElf",fetchling:"PF2E.TraitFetchling",fleshwarp:"PF2E.TraitFleshwarp",ganzi:"PF2E.TraitGanzi",geniekin:"PF2E.TraitGeniekin",ghoran:"PF2E.TraitGhoran",gnoll:"PF2E.TraitGnoll",gnome:"PF2E.TraitGnome",goblin:"PF2E.TraitGoblin",goloma:"PF2E.TraitGoloma",grippli:"PF2E.TraitGrippli",halfling:"PF2E.TraitHalfling",hobgoblin:"PF2E.TraitHobgoblin",human:"PF2E.TraitHuman",kashrishi:"PF2E.TraitKashrishi",kitsune:"PF2E.TraitKitsune",kobold:"PF2E.TraitKobold",leshy:"PF2E.TraitLeshy",lizardfolk:"PF2E.TraitLizardfolk",nagaji:"PF2E.TraitNagaji",naari:"PF2E.TraitNaari",nephilim:"PF2E.TraitNephilim",orc:"PF2E.TraitOrc",oread:"PF2E.TraitOread",poppet:"PF2E.TraitPoppet",ratfolk:"PF2E.TraitRatfolk",reflection:"PF2E.TraitReflection",shisk:"PF2E.TraitShisk",shoony:"PF2E.TraitShoony",skeleton:"PF2E.TraitSkeleton",sprite:"PF2E.TraitSprite",strix:"PF2E.TraitStrix",suli:"PF2E.TraitSuli",sylph:"PF2E.TraitSylph",talos:"PF2E.TraitTalos",tengu:"PF2E.TraitTengu",undine:"PF2E.TraitUndine",vanara:"PF2E.TraitVanara",vishkanya:"PF2E.TraitVishkanya"},elementTraits={air:"PF2E.TraitAir",earth:"PF2E.TraitEarth",fire:"PF2E.TraitFire",metal:"PF2E.TraitMetal",water:"PF2E.TraitWater",wood:"PF2E.TraitWood"},energyDamageTypes={acid:"PF2E.TraitAcid",cold:"PF2E.TraitCold",electricity:"PF2E.TraitElectricity",fire:"PF2E.TraitFire",force:"PF2E.TraitForce",sonic:"PF2E.TraitSonic",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},magicTraditions={arcane:"PF2E.TraitArcane",divine:"PF2E.TraitDivine",occult:"PF2E.TraitOccult",primal:"PF2E.TraitPrimal"},sanctificationTraits={holy:"PF2E.TraitHoly",unholy:"PF2E.TraitUnholy"},creatureTraits={...ancestryTraits,...elementTraits,...energyDamageTypes,...magicTraditions,...sanctificationTraits,aberration:"PF2E.TraitAberration",aeon:"PF2E.TraitAeon",aesir:"PF2E.TraitAesir",agathion:"PF2E.TraitAgathion",alchemical:"PF2E.TraitAlchemical",amphibious:"PF2E.TraitAmphibious",angel:"PF2E.TraitAngel",animal:"PF2E.TraitAnimal",anugobu:"PF2E.TraitAnugobu",aquatic:"PF2E.TraitAquatic",archon:"PF2E.TraitArchon",astral:"PF2E.TraitAstral",asura:"PF2E.TraitAsura",azata:"PF2E.TraitAzata",beast:"PF2E.TraitBeast",boggard:"PF2E.TraitBoggard",caligni:"PF2E.TraitCaligni",celestial:"PF2E.TraitCelestial","charau-ka":"PF2E.TraitCharauKa",clockwork:"PF2E.TraitClockwork",construct:"PF2E.TraitConstruct",couatl:"PF2E.TraitCouatl",daemon:"PF2E.TraitDaemon",darvakka:"PF2E.TraitDarvakka",demon:"PF2E.TraitDemon",dero:"PF2E.TraitDero",devil:"PF2E.TraitDevil",dinosaur:"PF2E.TraitDinosaur",div:"PF2E.TraitDiv",dragon:"PF2E.TraitDragon",dream:"PF2E.TraitDream",drow:"PF2E.TraitDrow",duergar:"PF2E.TraitDuergar",eidolon:"PF2E.TraitEidolon",elemental:"PF2E.TraitElemental",ethereal:"PF2E.TraitEthereal",fey:"PF2E.TraitFey",fiend:"PF2E.TraitFiend",formian:"PF2E.TraitFormian",fungus:"PF2E.TraitFungus",genie:"PF2E.TraitGenie",ghoran:"PF2E.TraitGhoran",ghost:"PF2E.TraitGhost",ghoul:"PF2E.TraitGhoul",ghul:"PF2E.TraitGhul",giant:"PF2E.TraitGiant",golem:"PF2E.TraitGolem",gremlin:"PF2E.TraitGremlin",grioth:"PF2E.TraitGrioth",hag:"PF2E.TraitHag",hantu:"PF2E.TraitHantu",herald:"PF2E.TraitHerald",hryngar:"PF2E.TraitHryngar",humanoid:"PF2E.TraitHumanoid",ikeshti:"PF2E.TraitIkeshti",illusion:"PF2E.TraitIllusion",incorporeal:"PF2E.TraitIncorporeal",inevitable:"PF2E.TraitInevitable",kami:"PF2E.TraitKami",kovintus:"PF2E.TraitKovintus",light:"PF2E.TraitLight",lilu:"PF2E.TraitLilu",locathah:"PF2E.TraitLocathah",mental:"PF2E.TraitMental",merfolk:"PF2E.TraitMerfolk",mindless:"PF2E.TraitMindless",minion:"PF2E.TraitMinion",monitor:"PF2E.TraitMonitor",morlock:"PF2E.TraitMorlock",mortic:"PF2E.TraitMortic",mummy:"PF2E.TraitMummy",munavri:"PF2E.TraitMunavri",mutant:"PF2E.TraitMutant",nindoru:"PF2E.TraitNindoru",nymph:"PF2E.TraitNymph",oni:"PF2E.TraitOni",ooze:"PF2E.TraitOoze",oread:"PF2E.TraitOread",paaridar:"PF2E.TraitPaaridar",petitioner:"PF2E.TraitPetitioner",phantom:"PF2E.TraitPhantom",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",protean:"PF2E.TraitProtean",psychopomp:"PF2E.TraitPsychopomp",qlippoth:"PF2E.TraitQlippoth",rakshasa:"PF2E.TraitRakshasa",reflection:"PF2E.TraitReflection",sahkil:"PF2E.TraitSahkil",samsaran:"PF2E.TraitSamsaran","sea-devil":"PF2E.TraitSeaDevil",serpentfolk:"PF2E.TraitSerpentfolk",seugathi:"PF2E.TraitSeugathi",shabti:"PF2E.TraitShabti",shadow:"PF2E.TraitShadow",shobhad:"PF2E.TraitShobhad",siktempora:"PF2E.TraitSiktempora",skelm:"PF2E.TraitSkelm",skulk:"PF2E.TraitSkulk",soulbound:"PF2E.TraitSoulbound",spirit:"PF2E.TraitSpirit",sporeborn:"PF2E.TraitSporeborn",spriggan:"PF2E.TraitSpriggan",stheno:"PF2E.TraitStheno",summoned:"PF2E.TraitSummoned",swarm:"PF2E.TraitSwarm",tane:"PF2E.TraitTane",tanggal:"PF2E.TraitTanggal",time:"PF2E.TraitTime",titan:"PF2E.TraitTitan",troll:"PF2E.TraitTroll",troop:"PF2E.TraitTroop",undead:"PF2E.TraitUndead",urdefhan:"PF2E.TraitUrdefhan",vampire:"PF2E.TraitVampire",vanara:"PF2E.TraitVanara",velstrac:"PF2E.TraitVelstrac",wayang:"PF2E.TraitWayang",werecreature:"PF2E.TraitWerecreature",wight:"PF2E.TraitWight","wild-hunt":"PF2E.TraitWildHunt",wraith:"PF2E.TraitWraith",wyrwood:"PF2E.TraitWyrwood",xulgath:"PF2E.TraitXulgath",zombie:"PF2E.TraitZombie"},backgroundTraits={"pervasive-magic":"PF2E.TraitPervasiveMagic"},classTraits={alchemist:"PF2E.TraitAlchemist",barbarian:"PF2E.TraitBarbarian",bard:"PF2E.TraitBard",champion:"PF2E.TraitChampion",cleric:"PF2E.TraitCleric",druid:"PF2E.TraitDruid",fighter:"PF2E.TraitFighter",gunslinger:"PF2E.TraitGunslinger",inventor:"PF2E.TraitInventor",investigator:"PF2E.TraitInvestigator",kineticist:"PF2E.TraitKineticist",magus:"PF2E.TraitMagus",monk:"PF2E.TraitMonk",oracle:"PF2E.TraitOracle",psychic:"PF2E.TraitPsychic",ranger:"PF2E.TraitRanger",rogue:"PF2E.TraitRogue",sorcerer:"PF2E.TraitSorcerer",summoner:"PF2E.TraitSummoner",swashbuckler:"PF2E.TraitSwashbuckler",thaumaturge:"PF2E.TraitThaumaturge",witch:"PF2E.TraitWitch",wizard:"PF2E.TraitWizard"},damageTraits={...elementTraits,...energyDamageTypes,...sanctificationTraits,light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",radiation:"PF2E.TraitRadiation",spirit:"PF2E.TraitSpirit",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},spellTraits={...classTraits,...damageTraits,...elementTraits,...magicTraditions,...sanctificationTraits,amp:"PF2E.TraitAmp",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",beast:"PF2E.TraitBeast",cantrip:"PF2E.TraitCantrip",composition:"PF2E.TraitComposition",concentrate:"PF2E.TraitConcentrate",consecration:"PF2E.TraitConsecration",contingency:"PF2E.TraitContingency",curse:"PF2E.TraitCurse",cursebound:"PF2E.TraitCursebound",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",disease:"PF2E.TraitDisease",dream:"PF2E.TraitDream",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",exploration:"PF2E.TraitExploration",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",focus:"PF2E.TraitFocus",fortune:"PF2E.TraitFortune",fungus:"PF2E.TraitFungus",healing:"PF2E.TraitHealing",hex:"PF2E.TraitHex",illusion:"PF2E.TraitIllusion",incapacitation:"PF2E.TraitIncapacitation",incarnate:"PF2E.TraitIncarnate",incorporeal:"PF2E.TraitIncorporeal",inhaled:"PF2E.TraitInhaled",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",litany:"PF2E.TraitLitany",manipulate:"PF2E.TraitManipulate",mindless:"PF2E.TraitMindless",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",move:"PF2E.TraitMove",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",prediction:"PF2E.TraitPrediction",psyche:"PF2E.TraitPsyche",revelation:"PF2E.TraitRevelation",sanctified:"PF2E.TraitSanctified",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",spellshape:"PF2E.TraitSpellshape",stance:"PF2E.TraitStance",subtle:"PF2E.TraitSubtle",summon:"PF2E.TraitSummon",summoned:"PF2E.TraitSummoned",teleportation:"PF2E.TraitTeleportation","true-name":"PF2E.TraitTrueName",visual:"PF2E.TraitVisual"},weaponTraits={...ancestryTraits,...elementTraits,...energyDamageTypes,...magicTraditions,...sanctificationTraits,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",agile:"PF2E.TraitAgile",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",attached:"PF2E.TraitAttached","attached-to-shield":"PF2E.TraitAttachedToShield","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm",auditory:"PF2E.TraitAuditory",backstabber:"PF2E.TraitBackstabber",backswing:"PF2E.TraitBackswing",bomb:"PF2E.TraitBomb",brace:"PF2E.TraitBrace",brutal:"PF2E.TraitBrutal","capacity-2":"PF2E.TraitCapacity2","capacity-3":"PF2E.TraitCapacity3","capacity-4":"PF2E.TraitCapacity4","capacity-5":"PF2E.TraitCapacity5",climbing:"PF2E.TraitClimbing",clockwork:"PF2E.TraitClockwork",cobbled:"PF2E.TraitCobbled",combination:"PF2E.TraitCombination",concealable:"PF2E.TraitConcealable",concussive:"PF2E.TraitConcussive",consumable:"PF2E.TraitConsumable","critical-fusion":"PF2E.TraitCriticalFusion",cursed:"PF2E.TraitCursed","deadly-d4":"PF2E.TraitDeadlyD4","deadly-d6":"PF2E.TraitDeadlyD6","deadly-d8":"PF2E.TraitDeadlyD8","deadly-d10":"PF2E.TraitDeadlyD10","deadly-d12":"PF2E.TraitDeadlyD12",death:"PF2E.TraitDeath",disarm:"PF2E.TraitDisarm",disease:"PF2E.TraitDisease","double-barrel":"PF2E.TraitDoubleBarrel",emotion:"PF2E.TraitEmotion",extradimensional:"PF2E.TraitExtradimensional","fatal-aim-d10":"PF2E.TraitFatalAimD10","fatal-aim-d12":"PF2E.TraitFatalAimD12","fatal-d8":"PF2E.TraitFatalD8","fatal-d10":"PF2E.TraitFatalD10","fatal-d12":"PF2E.TraitFatalD12",fear:"PF2E.TraitFear",finesse:"PF2E.TraitFinesse",forceful:"PF2E.TraitForceful",fortune:"PF2E.TraitFortune","free-hand":"PF2E.TraitFreeHand",fungus:"PF2E.TraitFungus",grapple:"PF2E.TraitGrapple",hampering:"PF2E.TraitHampering",healing:"PF2E.TraitHealing",infused:"PF2E.TraitInfused",inhaled:"PF2E.TraitInhaled",injection:"PF2E.TraitInjection",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested","jousting-d6":"PF2E.TraitJoustingD6",kickback:"PF2E.TraitKickback",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mental:"PF2E.TraitMental",modular:"PF2E.TraitModular",monk:"PF2E.TraitMonk",nonlethal:"PF2E.TraitNonlethal",olfactory:"PF2E.TraitOlfactory",parry:"PF2E.TraitParry",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",propulsive:"PF2E.TraitPropulsive","ranged-trip":"PF2E.TraitRangedTrip",razing:"PF2E.TraitRazing",reach:"PF2E.TraitReach",recovery:"PF2E.TraitRecovery",relic:"PF2E.TraitRelic",repeating:"PF2E.TraitRepeating",resonant:"PF2E.TraitResonant",saggorak:"PF2E.TraitSaggorak","scatter-5":"PF2E.TraitScatter5","scatter-10":"PF2E.TraitScatter10","scatter-15":"PF2E.TraitScatter15","scatter-20":"PF2E.TraitScatter20",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",shove:"PF2E.TraitShove",spirit:"PF2E.TraitSpirit",splash:"PF2E.TraitSplash",staff:"PF2E.TraitStaff",sweep:"PF2E.TraitSweep",tech:"PF2E.TraitTech",teleportation:"PF2E.TraitTeleportation",tethered:"PF2E.TraitTethered",thrown:"PF2E.TraitThrown","thrown-10":"PF2E.TraitThrown10","thrown-15":"PF2E.TraitThrown15","thrown-20":"PF2E.TraitThrown20","thrown-30":"PF2E.TraitThrown30","thrown-40":"PF2E.TraitThrown40","thrown-60":"PF2E.TraitThrown60","thrown-80":"PF2E.TraitThrown80","thrown-100":"PF2E.TraitThrown100","thrown-200":"PF2E.TraitThrown200",training:"PF2E.TraitTraining",trip:"PF2E.TraitTrip",twin:"PF2E.TraitTwin","two-hand-d6":"PF2E.TraitTwoHandD6","two-hand-d8":"PF2E.TraitTwoHandD8","two-hand-d10":"PF2E.TraitTwoHandD10","two-hand-d12":"PF2E.TraitTwoHandD12",unarmed:"PF2E.TraitUnarmed",vehicular:"PF2E.TraitVehicular","versatile-acid":"PF2E.TraitVersatileAcid","versatile-b":"PF2E.TraitVersatileB","versatile-cold":"PF2E.TraitVersatileCold","versatile-electricity":"PF2E.TraitVersatileElectricity","versatile-fire":"PF2E.TraitVersatileFire","versatile-force":"PF2E.TraitVersatileForce","versatile-p":"PF2E.TraitVersatileP","versatile-poison":"PF2E.TraitVersatilePoison","versatile-s":"PF2E.TraitVersatileS","versatile-sonic":"PF2E.TraitVersatileSonic","versatile-spirit":"PF2E.TraitVersatileSpirit","versatile-vitality":"PF2E.TraitVersatileVitality","versatile-void":"PF2E.TraitVersatileVoid","volley-20":"PF2E.TraitVolley20","volley-30":"PF2E.TraitVolley30","volley-50":"PF2E.TraitVolley50"},preciousMaterials={abysium:"PF2E.PreciousMaterialAbysium",adamantine:"PF2E.PreciousMaterialAdamantine","cold-iron":"PF2E.PreciousMaterialColdIron",duskwood:"PF2E.PreciousMaterialDuskwood",djezet:"PF2E.PreciousMaterialDjezet",dragonhide:"PF2E.PreciousMaterialDragonhide","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPelt",inubrix:"PF2E.PreciousMaterialInubrix","keep-stone":"PF2E.PreciousMaterialKeepStone",dawnsilver:"PF2E.PreciousMaterialDawnsilver",noqual:"PF2E.PreciousMaterialNoqual",orichalcum:"PF2E.PreciousMaterialOrichalcum",peachwood:"PF2E.PreciousMaterialPeachwood",siccatite:"PF2E.PreciousMaterialSiccatite",silver:"PF2E.PreciousMaterialSilver",sisterstone:"PF2E.PreciousMaterialSisterstone","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDusk","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneScarlet","sovereign-steel":"PF2E.PreciousMaterialSovereignSteel",warpglass:"PF2E.PreciousMaterialWarpglass"},otherArmorTags={shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},otherConsumableTags={herbal:"PF2E.Item.Physical.OtherTag.Herbal"},otherWeaponTags={improvised:"PF2E.Item.Physical.OtherTag.Improvised",shoddy:"PF2E.Item.Physical.OtherTag.Shoddy"},rangeTraits=mapToObj(RANGE_TRAITS,trait=>[trait,`PF2E.Trait${sluggify(trait,{camel:"bactrian"})}`]),npcAttackTraits={...weaponTraits,...preciousMaterials,...rangeTraits,curse:"PF2E.TraitCurse","deadly-2d8":"PF2E.TraitDeadly2D8","deadly-3d8":"PF2E.TraitDeadly3D8","deadly-4d8":"PF2E.TraitDeadly4D8","deadly-2d10":"PF2E.TraitDeadly2D10","deadly-3d10":"PF2E.TraitDeadly3D10","deadly-4d10":"PF2E.TraitDeadly4D10","deadly-2d12":"PF2E.TraitDeadly2D12","deadly-3d12":"PF2E.TraitDeadly3D12","deadly-4d12":"PF2E.TraitDeadly4D12",incorporeal:"PF2E.TraitIncorporeal",radiation:"PF2E.TraitRadiation","reach-0":"PF2E.TraitReach0","reach-10":"PF2E.TraitReach10","reach-15":"PF2E.TraitReach15","reach-20":"PF2E.TraitReach20","reach-25":"PF2E.TraitReach25","reach-30":"PF2E.TraitReach30","reach-40":"PF2E.TraitReach40","reach-50":"PF2E.TraitReach50","reach-60":"PF2E.TraitReach60","reach-100":"PF2E.TraitReach100","reach-120":"PF2E.TraitReach120","reach-200":"PF2E.TraitReach200","reach-1000":"PF2E.TraitReach1000","reload-0":"PF2E.TraitReload0","reload-1":"PF2E.TraitReload1","reload-2":"PF2E.TraitReload2","reload-1-min":"PF2E.TraitReload1Min"},featTraits={...ancestryTraits,...classTraits,...damageTraits,...magicTraditions,...spellTraits,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",aftermath:"PF2E.TraitAftermath",alchemical:"PF2E.TraitAlchemical",archetype:"PF2E.TraitArchetype",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",circus:"PF2E.TraitCircus",class:"TYPES.Item.class",composite:"PF2E.TraitComposite",concentrate:"PF2E.TraitConcentrate",dedication:"PF2E.TraitDedication",detection:"PF2E.TraitDetection",deviant:"PF2E.TraitDeviant",downtime:"PF2E.TraitDowntime",emotion:"PF2E.TraitEmotion",evolution:"PF2E.TraitEvolution",esoterica:"PF2E.TraitEsoterica",exploration:"PF2E.TraitExploration",fear:"PF2E.TraitFear",finisher:"PF2E.TraitFinisher",flourish:"PF2E.TraitFlourish",fortune:"PF2E.TraitFortune",general:"PF2E.TraitGeneral",impulse:"PF2E.TraitImpulse",infusion:"PF2E.TraitInfusion",injury:"PF2E.TraitInjury",lineage:"PF2E.TraitLineage",manipulate:"PF2E.TraitManipulate",metamagic:"PF2E.TraitMetamagic",mindshift:"PF2E.TraitMindshift",modification:"PF2E.TraitModification",move:"PF2E.TraitMove",multiclass:"PF2E.TraitMulticlass",oath:"PF2E.TraitOath",olfactory:"PF2E.TraitOlfactory",open:"PF2E.TraitOpen",overflow:"PF2E.TraitOverflow","pervasive-magic":"PF2E.TraitPervasiveMagic",poison:"PF2E.TraitPoison",press:"PF2E.TraitPress",rage:"PF2E.TraitRage",reckless:"PF2E.TraitReckless",reflection:"PF2E.TraitReflection",secret:"PF2E.TraitSecret",skill:"PF2E.TraitSkill",social:"PF2E.TraitSocial",spellshot:"PF2E.TraitSpellshot",stamina:"PF2E.TraitStamina",stance:"PF2E.TraitStance",tandem:"PF2E.TraitTandem",time:"PF2E.TraitTime","true-name":"PF2E.TraitTrueName",unstable:"PF2E.TraitUnstable",vigilante:"PF2E.TraitVigilante",virulent:"PF2E.TraitVirulent",vitality:"PF2E.TraitVitality",void:"PF2E.TraitVoid"},consumableTraits={...spellTraits,additive1:"PF2E.TraitAdditive1",additive2:"PF2E.TraitAdditive2",additive3:"PF2E.TraitAdditive3",alchemical:"PF2E.TraitAlchemical",attack:"PF2E.TraitAttack",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura","bottled-breath":"PF2E.TraitBottledBreath",catalyst:"PF2E.TraitCatalyst",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",contact:"PF2E.TraitContact",curse:"PF2E.TraitCurse",cursed:"PF2E.TraitCursed",drug:"PF2E.TraitDrug",elixir:"PF2E.TraitElixir",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",fear:"PF2E.TraitFear",fey:"PF2E.TraitFey",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",infused:"PF2E.TraitInfused",ingested:"PF2E.TraitIngested",inhaled:"PF2E.TraitInhaled",injury:"PF2E.TraitInjury",kobold:"PF2E.TraitKobold",light:"PF2E.TraitLight",linguistic:"PF2E.TraitLinguistic",lozenge:"PF2E.TraitLozenge",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",misfortune:"PF2E.TraitMisfortune",missive:"PF2E.TraitMissive",morph:"PF2E.TraitMorph",mutagen:"PF2E.TraitMutagen",oil:"PF2E.TraitOil",olfactory:"PF2E.TraitOlfactory",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",possession:"PF2E.TraitPossession",potion:"PF2E.TraitPotion",precious:"PF2E.TraitPrecious",processed:"PF2E.TraitProcessed",scroll:"PF2E.TraitScroll",scrying:"PF2E.TraitScrying",spirit:"PF2E.TraitSpirit",sleep:"PF2E.TraitSleep",snare:"PF2E.TraitSnare",spellgun:"PF2E.TraitSpellgun",splash:"PF2E.TraitSplash",structure:"PF2E.TraitStructure",talisman:"PF2E.TraitTalisman",tea:"PF2E.TraitTea",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},actionTraits={...featTraits,...consumableTraits,...spellTraits,...pick(weaponTraits,["agile","propulsive","backswing","forceful","reach","sweep","thrown","volley-20","volley-30","volley-50"]),summon:"PF2E.TraitSummon"},hazardTraits={...damageTraits,...magicTraditions,aberration:"PF2E.TraitAberration",alchemical:"PF2E.TraitAlchemical",animal:"PF2E.TraitAnimal",aquatic:"PF2E.TraitAquatic",auditory:"PF2E.TraitAuditory",beast:"PF2E.TraitBeast",clockwork:"PF2E.TraitClockwork",consumable:"PF2E.TraitConsumable",curse:"PF2E.TraitCurse",environmental:"PF2E.TraitEnvironmental",fungus:"PF2E.TraitFungus",haunt:"PF2E.TraitHaunt",inhaled:"PF2E.TraitInhaled",kaiju:"PF2E.TraitKaiju",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",shadow:"PF2E.TraitShadow",steam:"PF2E.TraitSteam",summoned:"PF2E.TraitSummoned",technological:"PF2E.TraitTechnological",teleportation:"PF2E.TraitTeleportation",trap:"PF2E.TraitTrap",virulent:"PF2E.TraitVirulent",visual:"PF2E.TraitVisual"},vehicleTraits={artifact:"PF2E.TraitArtifact",clockwork:"PF2E.TraitClockwork",magical:"PF2E.TraitMagical",teleportation:"PF2E.TraitTeleportation"},equipmentTraits={...ancestryTraits,...elementTraits,...energyDamageTypes,...magicTraditions,...sanctificationTraits,additive0:"PF2E.TraitAdditive0",additive1:"PF2E.TraitAdditive1",adjusted:"PF2E.TraitAdjusted",adjustment:"PF2E.TraitAdjustment",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",censer:"PF2E.TraitCenser",clockwork:"PF2E.TraitClockwork",coda:"PF2E.TraitCoda",companion:"PF2E.TraitCompanion",contract:"PF2E.TraitContract",consecration:"PF2E.TraitConsecration",cursed:"PF2E.TraitCursed",darkness:"PF2E.TraitDarkness",death:"PF2E.TraitDeath",detection:"PF2E.TraitDetection",eidolon:"PF2E.TraitEidolon",emotion:"PF2E.TraitEmotion",expandable:"PF2E.TraitExpandable",extradimensional:"PF2E.TraitExtradimensional",fear:"PF2E.TraitFear",figurehead:"PF2E.TraitFigurehead",focused:"PF2E.TraitFocused",fortune:"PF2E.TraitFortune",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",grimoire:"PF2E.TraitGrimoire","harrow-court":"PF2E.TraitHarrowCourt",healing:"PF2E.TraitHealing",incapacitation:"PF2E.TraitIncapacitation",incorporeal:"PF2E.TraitIncorporeal",infused:"PF2E.TraitInfused",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",mechanical:"PF2E.TraitMechanical",mental:"PF2E.TraitMental",misfortune:"PF2E.TraitMisfortune",morph:"PF2E.TraitMorph",mounted:"PF2E.TraitMounted",nonlethal:"PF2E.TraitNonlethal",plant:"PF2E.TraitPlant",poison:"PF2E.TraitPoison",polymorph:"PF2E.TraitPolymorph",portable:"PF2E.TraitPortable",precious:"PF2E.TraitPrecious",prediction:"PF2E.TraitPrediction",relic:"PF2E.TraitRelic",revelation:"PF2E.TraitRevelation",saggorak:"PF2E.TraitSaggorak",scrying:"PF2E.TraitScrying",shadow:"PF2E.TraitShadow",sleep:"PF2E.TraitSleep",spellgun:"PF2E.TraitSpellgun",spellheart:"PF2E.TraitSpellheart",spirit:"PF2E.TraitSpirit",staff:"PF2E.TraitStaff",steam:"PF2E.TraitSteam",structure:"PF2E.TraitStructure",tattoo:"PF2E.TraitTattoo",teleportation:"PF2E.TraitTeleportation",visual:"PF2E.TraitVisual",wand:"PF2E.TraitWand"},shieldTraits={...sanctificationTraits,...elementTraits,...magicTraditions,"deflecting-bludgeoning":"PF2E.TraitDeflectingBludgeoning","deflecting-physical-ranged":"PF2E.TraitDeflectingPhysicalRanged","deflecting-piercing":"PF2E.TraitDeflectingPiercing","deflecting-slashing":"PF2E.TraitDeflectingSlashing",foldaway:"PF2E.TraitFoldaway",harnessed:"PF2E.TraitHarnessed","hefty-2":"PF2E.TraitHefty2",inscribed:"PF2E.TraitInscribed","integrated-1d6-b":"PF2E.TraitIntegrated1d6B","integrated-1d6-p":"PF2E.TraitIntegrated1d6P","integrated-1d6-s":"PF2E.TraitIntegrated1d6S","integrated-1d6-s-versatile-p":"PF2E.TraitIntegrated1d6SVersatileP","launching-dart":"PF2E.TraitLaunching",magical:"PF2E.TraitMagical","shield-throw-20":"PF2E.TraitShieldThrow20","shield-throw-30":"PF2E.TraitShieldThrow30"},armorTraits={...sanctificationTraits,...elementTraits,...magicTraditions,adjusted:"PF2E.TraitAdjusted",alchemical:"PF2E.TraitAlchemical",apex:"PF2E.TraitApex",aquadynamic:"PF2E.TraitAquadynamic",artifact:"PF2E.TraitArtifact",auditory:"PF2E.TraitAuditory",aura:"PF2E.TraitAura",barding:"PF2E.TraitBarding",bulwark:"PF2E.TraitBulwark",clockwork:"PF2E.TraitClockwork",comfort:"PF2E.TraitComfort",companion:"PF2E.TraitCompanion",cursed:"PF2E.TraitCursed","entrench-melee":"PF2E.TraitEntrenchMelee","entrench-ranged":"PF2E.TraitEntrenchRanged",extradimensional:"PF2E.TraitExtradimensional",focused:"PF2E.TraitFocused",force:"PF2E.TraitForce",flexible:"PF2E.TraitFlexible",healing:"PF2E.TraitHealing",hindering:"PF2E.TraitHindering",inscribed:"PF2E.TraitInscribed",intelligent:"PF2E.TraitIntelligent",invested:"PF2E.TraitInvested",laminar:"PF2E.TraitLaminar",light:"PF2E.TraitLight",magical:"PF2E.TraitMagical",noisy:"PF2E.TraitNoisy",plant:"PF2E.TraitPlant",ponderous:"PF2E.TraitPonderous"},rangeDescriptions=mapToObj(RANGE_TRAITS,trait=>[trait,"PF2E.TraitDescriptionRange"]),kingmakerTraits={...actionTraits,army:"PF2E.Kingmaker.Trait.army",cavalry:"PF2E.Kingmaker.Trait.cavalry",civic:"PF2E.Kingmaker.Trait.civic",commerce:"PF2E.Kingmaker.Trait.commerce",infantry:"PF2E.Kingmaker.Trait.infantry",kingdom:"PF2E.Kingmaker.Trait.kingdom",leadership:"PF2E.Kingmaker.Trait.leadership",maneuver:"PF2E.Kingmaker.Trait.maneuver",morale:"PF2E.Kingmaker.Trait.morale",region:"PF2E.Kingmaker.Trait.region",siege:"PF2E.Kingmaker.Trait.siege",skirmisher:"PF2E.Kingmaker.Trait.skirmisher",upkeep:"PF2E.Kingmaker.Trait.upkeep"},kingmakerDescriptions={cavalry:"PF2E.Kingmaker.TraitDescription.cavalry",infantry:"PF2E.Kingmaker.TraitDescription.infantry",siege:"PF2E.Kingmaker.TraitDescription.siege",skirmisher:"PF2E.Kingmaker.TraitDescription.skirmisher"},preciousMaterialDescriptions={abysium:"PF2E.PreciousMaterialAbysiumDescription",adamantine:"PF2E.PreciousMaterialAdamantineDescription","cold-iron":"PF2E.PreciousMaterialColdIronDescription",duskwood:"PF2E.PreciousMaterialDuskwoodDescription",djezet:"PF2E.PreciousMaterialDjezetDescription",dragonhide:"PF2E.PreciousMaterialDragonhideDescription","grisantian-pelt":"PF2E.PreciousMaterialGrisantianPeltDescription",inubrix:"PF2E.PreciousMaterialInubrixDescription",dawnsilver:"PF2E.PreciousMaterialDawnsilverDescription",noqual:"PF2E.PreciousMaterialNoqualDescription",orichalcum:"PF2E.PreciousMaterialOrichalcumDescription",siccatite:"PF2E.PreciousMaterialSiccatiteDescription",silver:"PF2E.PreciousMaterialSilverDescription",sisterstone:"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-dusk":"PF2E.PreciousMaterialSisterstoneDescription","sisterstone-scarlet":"PF2E.PreciousMaterialSisterstoneDescription","sovereign-steel":"PF2E.PreciousMaterialSovereignSteelDescription",warpglass:"PF2E.PreciousMaterialWarpglassDescription"},traitDescriptions={...kingmakerDescriptions,aasimar:"PF2E.TraitDescriptionAasimar",aberration:"PF2E.TraitDescriptionAberration",abjuration:"PF2E.TraitDescriptionAbjuration",acid:"PF2E.TraitDescriptionAcid",additive0:"PF2E.TraitDescriptionAdditive",additive1:"PF2E.TraitDescriptionAdditive",additive2:"PF2E.TraitDescriptionAdditive",additive3:"PF2E.TraitDescriptionAdditive",adjusted:"PF2E.TraitDescriptionAdjusted",adjustment:"PF2E.TraitDescriptionAdjustment",aeon:"PF2E.TraitDescriptionAeon",aesir:"PF2E.TraitDescriptionAesir",aftermath:"PF2E.TraitDescriptionAftermath",agathion:"PF2E.TraitDescriptionAgathion",agile:"PF2E.TraitDescriptionAgile",air:"PF2E.TraitDescriptionAir",aiuvarin:"PF2E.TraitDescriptionAiuvarin",alchemical:"PF2E.TraitDescriptionAlchemical",alchemist:"PF2E.TraitDescriptionAlchemist",amphibious:"PF2E.TraitDescriptionAmphibious",anadi:"PF2E.TraitDescriptionAnadi",android:"PF2E.TraitDescriptionAndroid",apex:"PF2E.TraitDescriptionApex",aphorite:"PF2E.TraitDescriptionAphorite",aquadynamic:"PF2E.TraitDescriptionAquadynamic",arcane:"PF2E.TraitDescriptionArcane",archetype:"PF2E.TraitDescriptionArchetype",ardande:"PF2E.TraitDescriptionArdande",artifact:"PF2E.TraitDescriptionArtifact",attached:"PF2E.TraitDescriptionAttached","attached-to-crossbow-or-firearm":"PF2E.TraitDescriptionAttached","attached-to-shield":"PF2E.TraitDescriptionAttached",attack:"PF2E.TraitDescriptionAttack",auditory:"PF2E.TraitDescriptionAuditory",aura:"PF2E.TraitDescriptionAura",automaton:"PF2E.TraitDescriptionAutomaton",azarketi:"PF2E.TraitDescriptionAzarketi",backstabber:"PF2E.TraitDescriptionBackstabber",backswing:"PF2E.TraitDescriptionBackswing",barbarian:"PF2E.TraitDescriptionBarbarian",bard:"PF2E.TraitDescriptionBard",beastkin:"PF2E.TraitDescriptionBeastkin",bomb:"PF2E.TraitDescriptionBomb","bottled-breath":"PF2E.TraitDescriptionBottledBreath",brace:"PF2E.TraitDescriptionBrace",brutal:"PF2E.TraitDescriptionBrutal",bulwark:"PF2E.TraitDescriptionBulwark",cantrip:"PF2E.TraitDescriptionCantrip","capacity-2":"PF2E.TraitDescriptionCapacity","capacity-3":"PF2E.TraitDescriptionCapacity","capacity-4":"PF2E.TraitDescriptionCapacity","capacity-5":"PF2E.TraitDescriptionCapacity",catalyst:"PF2E.TraitDescriptionCatalyst",catfolk:"PF2E.TraitDescriptionCatfolk",censer:"PF2E.TraitDescriptionCenser",champion:"PF2E.TraitDescriptionChampion",changeling:"PF2E.TraitDescriptionChangeling",class:"PF2E.TraitDescriptionClass",cleric:"PF2E.TraitDescriptionCleric",climbing:"PF2E.TraitDescriptionClimbing",clockwork:"PF2E.TraitDescriptionClockwork",cobbled:"PF2E.TraitDescriptionCobbled",coda:"PF2E.TraitDescriptionCoda",cold:"PF2E.TraitDescriptionCold",combination:"PF2E.TraitDescriptionCombination",comfort:"PF2E.TraitDescriptionComfort",common:"PF2E.TraitDescriptionCommon",companion:"PF2E.TraitDescriptionCompanion",complex:"PF2E.TraitDescriptionComplex",composite:"PF2E.TraitDescriptionComposite",composition:"PF2E.TraitDescriptionComposition",concealable:"PF2E.TraitDescriptionConcealable",concentrate:"PF2E.TraitDescriptionConcentrate",concussive:"PF2E.TraitDescriptionConcussive",conrasu:"PF2E.TraitDescriptionConrasu",consecration:"PF2E.TraitDescriptionConsecration",consumable:"PF2E.TraitDescriptionConsumable",contact:"PF2E.TraitDescriptionContact",contingency:"PF2E.TraitDescriptionContingency",contract:"PF2E.TraitDescriptionContract","critical-fusion":"PF2E.TraitDescriptionCriticalFusion",curse:"PF2E.TraitDescriptionCurse",cursebound:"PF2E.TraitDescriptionCursebound",cursed:"PF2E.TraitDescriptionCursed",darkness:"PF2E.TraitDescriptionDarkness",darvakka:"PF2E.TraitDescriptionDarvakka","deadly-2d10":"PF2E.TraitDescriptionDeadly","deadly-2d12":"PF2E.TraitDescriptionDeadly","deadly-2d8":"PF2E.TraitDescriptionDeadly","deadly-3d10":"PF2E.TraitDescriptionDeadly","deadly-3d12":"PF2E.TraitDescriptionDeadly","deadly-3d8":"PF2E.TraitDescriptionDeadly","deadly-4d10":"PF2E.TraitDescriptionDeadly","deadly-4d12":"PF2E.TraitDescriptionDeadly","deadly-4d8":"PF2E.TraitDescriptionDeadly","deadly-d10":"PF2E.TraitDescriptionDeadly","deadly-d12":"PF2E.TraitDescriptionDeadly","deadly-d6":"PF2E.TraitDescriptionDeadly","deadly-d8":"PF2E.TraitDescriptionDeadly","deadly-d4":"PF2E.TraitDescriptionDeadly",death:"PF2E.TraitDescriptionDeath","deflecting-bludgeoning":"PF2E.TraitDescriptionDeflecting","deflecting-physical-ranged":"PF2E.TraitDescriptionDeflecting","deflecting-slashing":"PF2E.TraitDescriptionDeflecting",dedication:"PF2E.TraitDescriptionDedication",detection:"PF2E.TraitDescriptionDetection",deviant:"PF2E.TraitDescriptionDeviant",dhampir:"PF2E.TraitDescriptionDhampir",disarm:"PF2E.TraitDescriptionDisarm",disease:"PF2E.TraitDescriptionDisease",divination:"PF2E.TraitDescriptionDivination",divine:"PF2E.TraitDescriptionDivine","double-barrel":"PF2E.TraitDescriptionDoubleBarrel",downtime:"PF2E.TraitDescriptionDowntime",dromaar:"PF2E.TraitDescriptionDromaar",drug:"PF2E.TraitDescriptionDrug",druid:"PF2E.TraitDescriptionDruid",duskwalker:"PF2E.TraitDescriptionDuskwalker",dwarf:"PF2E.TraitDescriptionDwarf",earth:"PF2E.TraitDescriptionEarth",eidolon:"PF2E.TraitDescriptionEidolon",electricity:"PF2E.TraitDescriptionElectricity",elf:"PF2E.TraitDescriptionElf",elixir:"PF2E.TraitDescriptionElixir",emotion:"PF2E.TraitDescriptionEmotion","entrench-melee":"PF2E.TraitDescriptionEntrench","entrench-ranged":"PF2E.TraitDescriptionEntrench",environment:"PF2E.TraitDescriptionEnvironment",esoterica:"PF2E.TraitDescriptionEsoterica",evolution:"PF2E.TraitDescriptionEvolution",expandable:"PF2E.TraitDescriptionExpandable",exploration:"PF2E.TraitDescriptionExploration",extradimensional:"PF2E.TraitDescriptionExtradimensional","fatal-aim-d10":"PF2E.TraitDescriptionFatalAim","fatal-aim-d12":"PF2E.TraitDescriptionFatalAim","fatal-d10":"PF2E.TraitDescriptionFatal","fatal-d12":"PF2E.TraitDescriptionFatal","fatal-d8":"PF2E.TraitDescriptionFatal",fear:"PF2E.TraitDescriptionFear",fetchling:"PF2E.TraitDescriptionFetchling",fey:"PF2E.TraitDescriptionFey",fighter:"PF2E.TraitDescriptionFighter",figurehead:"PF2E.TraitDescriptionFigurehead",finesse:"PF2E.TraitDescriptionFinesse",finisher:"PF2E.TraitDescriptionFinisher",fire:"PF2E.TraitDescriptionFire",fleshwarp:"PF2E.TraitDescriptionFleshwarp",flexible:"PF2E.TraitDescriptionFlexible",flourish:"PF2E.TraitDescriptionFlourish",focus:"PF2E.TraitDescriptionFocus",focused:"PF2E.TraitDescriptionFocused",foldaway:"PF2E.TraitDescriptionFoldaway",force:"PF2E.TraitDescriptionForce",forceful:"PF2E.TraitDescriptionForceful",fortune:"PF2E.TraitDescriptionFortune","free-hand":"PF2E.TraitDescriptionFreeHand",fulu:"PF2E.TraitDescriptionFulu",fungus:"PF2E.TraitDescriptionFungus",gadget:"PF2E.TraitDescriptionGadget",ganzi:"PF2E.TraitDescriptionGanzi",general:"PF2E.TraitDescriptionGeneral",genie:"PF2E.TraitDescriptionGenie",geniekin:"PF2E.TraitDescriptionGeniekin",ghoran:"PF2E.TraitDescriptionGhoran",ghul:"PF2E.TraitDescriptionGhul",gnoll:"PF2E.TraitDescriptionGnoll",gnome:"PF2E.TraitDescriptionGnome",goblin:"PF2E.TraitDescriptionGoblin",goloma:"PF2E.TraitDescriptionGoloma",grapple:"PF2E.TraitDescriptionGrapple",grimoire:"PF2E.TraitDescriptionGrimoire",grippli:"PF2E.TraitDescriptionGrippli",gunslinger:"PF2E.TraitDescriptionGunslinger",halfling:"PF2E.TraitDescriptionHalfling","jousting-d6":"PF2E.TraitDescriptionJousting",hampering:"PF2E.TraitDescriptionHampering",harnessed:"PF2E.TraitDescriptionHarnessed",haunt:"PF2E.TraitDescriptionHaunt",healing:"PF2E.TraitDescriptionHealing","hefty-14":"PF2E.TraitDescriptionHefty",hex:"PF2E.TraitDescriptionHex",hindering:"PF2E.TraitDescriptionHindering",hobgoblin:"PF2E.TraitDescriptionHobgoblin",holy:"PF2E.TraitDescriptionHoly",human:"PF2E.TraitDescriptionHuman",humanoid:"PF2E.TraitDescriptionHumanoid",naari:"PF2E.TraitDescriptionNaari",illusion:"PF2E.TraitDescriptionIllusion",impulse:"PF2E.TraitDescriptionImpulse",incapacitation:"PF2E.TraitDescriptionIncapacitation",incarnate:"PF2E.TraitDescriptionIncarnate",incorporeal:"PF2E.TraitDescriptionIncorporeal",infused:"PF2E.TraitDescriptionInfused",infusion:"PF2E.TraitDescriptionInfusion",ingested:"PF2E.TraitDescriptionIngested",inhaled:"PF2E.TraitDescriptionInhaled",injection:"PF2E.TraitDescriptionInjection",injury:"PF2E.TraitDescriptionInjury",inscribed:"PF2E.TraitDescriptionInscribed","integrated-1d6-b":"PF2E.TraitDescriptionIntegrated","integrated-1d6-p":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s":"PF2E.TraitDescriptionIntegrated","integrated-1d6-s-versatile-p":"PF2E.TraitDescriptionIntegrated",intelligent:"PF2E.TraitDescriptionIntelligent",inventor:"PF2E.TraitDescriptionInventor",invested:"PF2E.TraitDescriptionInvested",investigator:"PF2E.TraitDescriptionInvestigator",kashrishi:"PF2E.TraitDescriptionKashrishi","keep-stone":"PF2E.PreciousMaterialKeepStoneDescription",kickback:"PF2E.TraitDescriptionKickback",kineticist:"PF2E.TraitDescriptionKineticist",kitsune:"PF2E.TraitDescriptionKitsune",kobold:"PF2E.TraitDescriptionKobold",laminar:"PF2E.TraitDescriptionLaminar","launching-dart":"PF2E.TraitDescriptionLaunching",leshy:"PF2E.TraitDescriptionLeshy",light:"PF2E.TraitDescriptionLight",linguistic:"PF2E.TraitDescriptionLinguistic",litany:"PF2E.TraitDescriptionLitany",lizardfolk:"PF2E.TraitDescriptionLizardfolk",lozenge:"PF2E.TraitDescriptionLozenge",magical:"PF2E.TraitDescriptionMagical",magus:"PF2E.TraitDescriptionMagus",manipulate:"PF2E.TraitDescriptionManipulate",mechanical:"PF2E.TraitDescriptionMechanical",mental:"PF2E.TraitDescriptionMental",metal:"PF2E.TraitDescriptionMetal",mindless:"PF2E.TraitDescriptionMindless",mindshift:"PF2E.TraitDescriptionMindshift",minion:"PF2E.TraitDescriptionMinion",misfortune:"PF2E.TraitDescriptionMisfortune",missive:"PF2E.TraitDescriptionMissive",modification:"PF2E.TraitDescriptionModification",modular:"PF2E.TraitDescriptionModular",monk:"PF2E.TraitDescriptionMonk",morph:"PF2E.TraitDescriptionMorph",mounted:"PF2E.TraitDescriptionMounted",move:"PF2E.TraitDescriptionMove",multiclass:"PF2E.TraitDescriptionMulticlass",mutagen:"PF2E.TraitDescriptionMutagen",nagaji:"PF2E.TraitDescriptionNagaji",nephilim:"PF2E.TraitDescriptionNephilim",nindoru:"PF2E.TraitDescriptionNindoru",noisy:"PF2E.TraitDescriptionNoisy",nonlethal:"PF2E.TraitDescriptionNonlethal",oath:"PF2E.TraitDescriptionOath",occult:"PF2E.TraitDescriptionOccult",oil:"PF2E.TraitDescriptionOil",olfactory:"PF2E.TraitDescriptionOlfactory",open:"PF2E.TraitDescriptionOpen",oracle:"PF2E.TraitDescriptionOracle",orc:"PF2E.TraitDescriptionOrc",oread:"PF2E.TraitDescriptionOread",overflow:"PF2E.TraitDescriptionOverflow",parry:"PF2E.TraitDescriptionParry",peachwood:"PF2E.PreciousMaterialPeachwoodDescription",plant:"PF2E.TraitDescriptionPlant",poison:"PF2E.TraitDescriptionPoison",polymorph:"PF2E.TraitDescriptionPolymorph",ponderous:"PF2E.TraitDescriptionPonderous",poppet:"PF2E.TraitDescriptionPoppet",portable:"PF2E.TraitDescriptionPortable",possession:"PF2E.TraitDescriptionPossession",potion:"PF2E.TraitDescriptionPotion",precious:"PF2E.TraitDescriptionPrecious",prediction:"PF2E.TraitDescriptionPrediction",press:"PF2E.TraitDescriptionPress",primal:"PF2E.TraitDescriptionPrimal",propulsive:"PF2E.TraitDescriptionPropulsive",psyche:"PF2E.TraitDescriptionPsyche",psychic:"PF2E.TraitDescriptionPsychic",radiation:"PF2E.TraitDescriptionRadiation",rage:"PF2E.TraitDescriptionRage",ranger:"PF2E.TraitDescriptionRanger",...rangeDescriptions,"ranged-trip":"PF2E.TraitDescriptionRangedTrip",rare:"PF2E.TraitDescriptionRare",ratfolk:"PF2E.TraitDescriptionRatfolk",razing:"PF2E.TraitDescriptionRazing",reach:"PF2E.TraitDescriptionReach","reach-0":"PF2E.TraitDescriptionReach","reach-10":"PF2E.TraitDescriptionReach","reach-100":"PF2E.TraitDescriptionReach","reach-120":"PF2E.TraitDescriptionReach","reach-1000":"PF2E.TraitDescriptionReach","reach-15":"PF2E.TraitDescriptionReach","reach-20":"PF2E.TraitDescriptionReach","reach-200":"PF2E.TraitDescriptionReach","reach-25":"PF2E.TraitDescriptionReach","reach-30":"PF2E.TraitDescriptionReach","reach-40":"PF2E.TraitDescriptionReach","reach-50":"PF2E.TraitDescriptionReach","reach-60":"PF2E.TraitDescriptionReach",recovery:"PF2E.TraitDescriptionRecovery",reflection:"PF2E.TraitDescriptionReflection",relic:"PF2E.TraitDescriptionRelic",reload:"PF2E.TraitDescriptionReload","reload-0":"PF2E.TraitDescriptionReload","reload-1":"PF2E.TraitDescriptionReload","reload-1-min":"PF2E.TraitDescriptionReload","reload-2":"PF2E.TraitDescriptionReload",repeating:"PF2E.TraitDescriptionRepeating",resonant:"PF2E.TraitDescriptionResonant",revelation:"PF2E.TraitDescriptionRevelation",rogue:"PF2E.TraitDescriptionRogue",saggorak:"PF2E.TraitDescriptionSaggorak",sanctified:"PF2E.TraitDescriptionSanctified","scatter-10":"PF2E.TraitDescriptionScatter","scatter-15":"PF2E.TraitDescriptionScatter","scatter-20":"PF2E.TraitDescriptionScatter","scatter-5":"PF2E.TraitDescriptionScatter",scroll:"PF2E.TraitDescriptionScroll",scrying:"PF2E.TraitDescriptionScrying",secret:"PF2E.TraitDescriptionSecret",shadow:"PF2E.TraitDescriptionShadow","shield-throw-20":"PF2E.TraitDescriptionShieldThrow","shield-throw-30":"PF2E.TraitDescriptionShieldThrow",shisk:"PF2E.TraitDescriptionShisk",shoony:"PF2E.TraitDescriptionShoony",shove:"PF2E.TraitDescriptionShove",skeleton:"PF2E.TraitDescriptionSkeleton",skill:"PF2E.TraitDescriptionSkill",sleep:"PF2E.TraitDescriptionSleep",snare:"PF2E.TraitDescriptionSnare",social:"PF2E.TraitDescriptionSocial",sonic:"PF2E.TraitDescriptionSonic",sorcerer:"PF2E.TraitDescriptionSorcerer",spellgun:"PF2E.TraitDescriptionSpellgun",spellheart:"PF2E.TraitDescriptionSpellheart",spellshape:"PF2E.TraitDescriptionSpellshape",spellshot:"PF2E.TraitNoDescription",spirit:"PF2E.TraitDescriptionSpirit",splash:"PF2E.TraitDescriptionSplash","splash-10":"PF2E.TraitDescriptionSplash10",sprite:"PF2E.TraitDescriptionSprite",staff:"PF2E.TraitDescriptionStaff",stance:"PF2E.TraitDescriptionStance",steam:"PF2E.TraitDescriptionSteam",strix:"PF2E.TraitDescriptionStrix",structure:"PF2E.TraitDescriptionStructure",subtle:"PF2E.TraitDescriptionSubtle",suli:"PF2E.TraitDescriptionSuli",summon:"PF2E.TraitDescriptionSummon",summoned:"PF2E.TraitDescriptionSummoned",summoner:"PF2E.TraitDescriptionSummoner",swashbuckler:"PF2E.TraitDescriptionSwashbuckler",sweep:"PF2E.TraitDescriptionSweep",sylph:"PF2E.TraitDescriptionSylph",talisman:"PF2E.TraitDescriptionTalisman",talos:"PF2E.TraitDescriptionTalos",tandem:"PF2E.TraitDescriptionTandem",tattoo:"PF2E.TraitDescriptionTattoo",tea:"PF2E.TraitDescriptionTea",tech:"PF2E.TraitDescriptionTech",telepathy:"PF2E.TraitDescriptionTelepathy",teleportation:"PF2E.TraitDescriptionTeleportation",tengu:"PF2E.TraitDescriptionTengu",tethered:"PF2E.TraitDescriptionTethered",thaumaturge:"PF2E.TraitDescriptionThaumaturge",thrown:"PF2E.TraitDescriptionThrown","thrown-10":"PF2E.TraitDescriptionThrown","thrown-100":"PF2E.TraitDescriptionThrown","thrown-15":"PF2E.TraitDescriptionThrown","thrown-20":"PF2E.TraitDescriptionThrown","thrown-200":"PF2E.TraitDescriptionThrown","thrown-25":"PF2E.TraitDescriptionThrown","thrown-30":"PF2E.TraitDescriptionThrown","thrown-40":"PF2E.TraitDescriptionThrown","thrown-50":"PF2E.TraitDescriptionThrown","thrown-60":"PF2E.TraitDescriptionThrown","thrown-80":"PF2E.TraitDescriptionThrown",tiefling:"PF2E.TraitDescriptionTiefling",time:"PF2E.TraitDescriptionTime",training:"PF2E.TraitDescriptionTraining",trap:"PF2E.TraitDescriptionTrap",trip:"PF2E.TraitDescriptionTrip","true-name":"PF2E.TraitDescriptionTrueName",twin:"PF2E.TraitDescriptionTwin","two-hand-d10":"PF2E.TraitDescriptionTwoHand","two-hand-d12":"PF2E.TraitDescriptionTwoHand","two-hand-d6":"PF2E.TraitDescriptionTwoHand","two-hand-d8":"PF2E.TraitDescriptionTwoHand",unarmed:"PF2E.TraitDescriptionUnarmed",uncommon:"PF2E.TraitDescriptionUncommon",undine:"PF2E.TraitDescriptionUndine",undead:"PF2E.TraitDescriptionUndead",unholy:"PF2E.TraitDescriptionUnholy",unique:"PF2E.TraitDescriptionUnique",unstable:"PF2E.TraitDescriptionUnstable",vanara:"PF2E.TraitDescriptionVanara",vishkanya:"PF2E.TraitDescriptionVishkanya",vehicular:"PF2E.TraitDescriptionVehicular","versatile-acid":"PF2E.TraitDescriptionVersatile","versatile-b":"PF2E.TraitDescriptionVersatile","versatile-cold":"PF2E.TraitDescriptionVersatile","versatile-electricity":"PF2E.TraitDescriptionVersatile","versatile-fire":"PF2E.TraitDescriptionVersatile","versatile-force":"PF2E.TraitDescriptionVersatile","versatile-p":"PF2E.TraitDescriptionVersatile","versatile-poison":"PF2E.TraitDescriptionVersatile","versatile-s":"PF2E.TraitDescriptionVersatile","versatile-sonic":"PF2E.TraitDescriptionVersatile","versatile-spirit":"PF2E.TraitDescriptionVersatile","versatile-vitality":"PF2E.TraitDescriptionVersatile","versatile-void":"PF2E.TraitDescriptionVersatile",virulent:"PF2E.TraitDescriptionVirulent",visual:"PF2E.TraitDescriptionVisual",vitality:"PF2E.TraitDescriptionVitality",void:"PF2E.TraitDescriptionVoid","volley-20":"PF2E.TraitDescriptionVolley","volley-30":"PF2E.TraitDescriptionVolley","volley-50":"PF2E.TraitDescriptionVolley",wand:"PF2E.TraitDescriptionWand",water:"PF2E.TraitDescriptionWater",witch:"PF2E.TraitDescriptionWitch",wizard:"PF2E.TraitDescriptionWizard",wood:"PF2E.TraitDescriptionWood",...preciousMaterialDescriptions},damageCategoriesUnique={persistent:"PF2E.ConditionTypePersistentShort",precision:"PF2E.Damage.Precision",splash:"PF2E.TraitSplash"},materialDamageEffects=pick(preciousMaterials,["abysium","adamantine","cold-iron","dawnsilver","djezet","duskwood","inubrix","keep-stone","noqual","orichalcum","peachwood","siccatite","silver","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),damageCategories={...damageCategoriesUnique,...materialDamageEffects,alignment:"PF2E.Alignment",energy:"PF2E.TraitEnergy",physical:"PF2E.TraitPhysical"},physicalDamageTypes={bleed:"PF2E.TraitBleed",bludgeoning:"PF2E.TraitBludgeoning",piercing:"PF2E.TraitPiercing",slashing:"PF2E.TraitSlashing"},damageTypes={...energyDamageTypes,...physicalDamageTypes,mental:"PF2E.TraitMental",poison:"PF2E.TraitPoison",spirit:"PF2E.TraitSpirit",untyped:"PF2E.TraitUntyped"},damageRollFlavors=[...DAMAGE_TYPES].reduce((result,key)=>(result[key]=`PF2E.Damage.RollFlavor.${key}`,result),{}),materialIWR=mapValues$1(omit(materialDamageEffects,["keep-stone","peachwood","sisterstone-dusk","sisterstone-scarlet","sovereign-steel","warpglass"]),(_v,k)=>`PF2E.Damage.IWR.Type.${k}`),sanctifiedIWR={holy:"PF2E.Damage.IWR.Type.holy",unholy:"PF2E.Damage.IWR.Type.unholy"},immunityTypes={...materialIWR,...sanctifiedIWR,acid:"PF2E.Damage.RollFlavor.acid",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",clumsy:"PF2E.Damage.IWR.Type.clumsy",cold:"PF2E.Damage.RollFlavor.cold",confused:"PF2E.Damage.IWR.Type.confused",controlled:"PF2E.Damage.IWR.Type.controlled","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",curse:"PF2E.Damage.IWR.Type.curse",custom:"",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",energy:"PF2E.Damage.IWR.Type.energy",enfeebled:"PF2E.Damage.IWR.Type.enfeebled",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",fleeing:"PF2E.Damage.IWR.Type.fleeing",force:"PF2E.Damage.RollFlavor.force",frightened:"PF2E.Damage.IWR.Type.frightened",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",light:"PF2E.Damage.IWR.Type.light",magic:"PF2E.Damage.IWR.Type.magic",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.IWR.Type.metal","misfortune-effects":"PF2E.Damage.IWR.Type.misfortune-effects","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","object-immunities":"PF2E.Damage.IWR.Type.object-immunities","off-guard":"PF2E.Damage.IWR.Type.off-guard",olfactory:"PF2E.Damage.IWR.Type.olfactory",paralyzed:"PF2E.Damage.IWR.Type.paralyzed","persistent-damage":"PF2E.Damage.IWR.Type.persistent-damage",petrified:"PF2E.Damage.IWR.Type.petrified",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",polymorph:"PF2E.Damage.IWR.Type.polymorph",possession:"PF2E.Damage.IWR.Type.possession",precision:"PF2E.Damage.RollFlavor.precision",prone:"PF2E.Damage.IWR.Type.prone",radiation:"PF2E.Damage.IWR.Type.radiation",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",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",spirit:"PF2E.Damage.RollFlavor.spirit",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",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",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",water:"PF2E.Damage.IWR.Type.water",wood:"PF2E.Damage.IWR.Type.wood",wounded:"PF2E.Damage.IWR.Type.wounded"},weaknessTypes={...materialIWR,...sanctifiedIWR,acid:"PF2E.Damage.RollFlavor.acid",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",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",emotion:"PF2E.Damage.IWR.Type.emotion",energy:"PF2E.Damage.IWR.Type.energy",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",glass:"PF2E.Damage.IWR.Type.glass",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","persistent-damage":"PF2E.Damage.IWR.Type.persistent-damage",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",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",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","splash-damage":"PF2E.Damage.IWR.Type.splash-damage","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks","vampire-weaknesses":"PF2E.Damage.IWR.Type.vampire-weaknesses",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-fear":"PF2E.Damage.IWR.Type.vorpal-fear","vulnerable-to-sunlight":"PF2E.Damage.IWR.Type.vulnerable-to-sunlight",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},resistanceTypes={...materialIWR,...sanctifiedIWR,acid:"PF2E.Damage.RollFlavor.acid",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",cold:"PF2E.Damage.RollFlavor.cold","critical-hits":"PF2E.Damage.IWR.Type.critical-hits",custom:"","damage-from-spells":"PF2E.Damage.IWR.Type.damage-from-spells",earth:"PF2E.Damage.RollFlavor.earth",electricity:"PF2E.Damage.RollFlavor.electricity",energy:"PF2E.Damage.IWR.Type.energy",fire:"PF2E.Damage.RollFlavor.fire",force:"PF2E.Damage.RollFlavor.force","ghost-touch":"PF2E.Damage.IWR.Type.ghost-touch",light:"PF2E.Damage.IWR.Type.light",magical:"PF2E.Damage.IWR.Type.magical",mental:"PF2E.Damage.RollFlavor.mental",metal:"PF2E.Damage.RollFlavor.metal","non-magical":"PF2E.Damage.IWR.Type.non-magical",nonlethal:"PF2E.Damage.IWR.Type.nonlethal","nonlethal-attacks":"PF2E.Damage.IWR.Type.nonlethal-attacks","persistent-damage":"PF2E.Damage.IWR.Type.persistent-damage",physical:"PF2E.Damage.IWR.Type.physical",piercing:"PF2E.Damage.RollFlavor.piercing",plant:"PF2E.Damage.IWR.Type.plant",poison:"PF2E.Damage.RollFlavor.poison",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",slashing:"PF2E.Damage.RollFlavor.slashing",sonic:"PF2E.Damage.RollFlavor.sonic",spells:"PF2E.Damage.IWR.Type.spells",spirit:"PF2E.Damage.RollFlavor.spirit","unarmed-attacks":"PF2E.Damage.IWR.Type.unarmed-attacks",vitality:"PF2E.Damage.RollFlavor.vitality",void:"PF2E.Damage.RollFlavor.void",vorpal:"PF2E.Damage.IWR.Type.vorpal","vorpal-adamantine":"PF2E.Damage.IWR.Type.vorpal-adamantine",water:"PF2E.Damage.IWR.Type.water",weapons:"PF2E.Damage.IWR.Type.weapons","weapons-shedding-bright-light":"PF2E.Damage.IWR.Type.weapons-shedding-bright-light",wood:"PF2E.Damage.IWR.Type.wood"},ATTRIBUTE_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(["bleed","good","evil","lawful","chaotic","spirit","vitality","void"]),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));Object.fromEntries(Object.entries(SKILL_DICTIONARY).map(([abbrev,value])=>[value,abbrev]));const DC_SLUGS=new Set(["ac","armor","perception",...SAVE_TYPES,...SKILL_LONG_FORMS]),SKILL_EXPANDED={acrobatics:{attribute:"dex",shortForm:"acr"},arcana:{attribute:"int",shortForm:"arc"},athletics:{attribute:"str",shortForm:"ath"},crafting:{attribute:"int",shortForm:"cra"},deception:{attribute:"cha",shortForm:"dec"},diplomacy:{attribute:"cha",shortForm:"dip"},intimidation:{attribute:"cha",shortForm:"itm"},medicine:{attribute:"wis",shortForm:"med"},nature:{attribute:"wis",shortForm:"nat"},occultism:{attribute:"int",shortForm:"occ"},performance:{attribute:"cha",shortForm:"prf"},religion:{attribute:"wis",shortForm:"rel"},society:{attribute:"int",shortForm:"soc"},stealth:{attribute:"dex",shortForm:"ste"},survival:{attribute:"wis",shortForm:"sur"},thievery:{attribute:"dex",shortForm:"thi"}},MOVEMENT_TYPES=["land","burrow","climb","fly","swim"],SIZE_LINKABLE_ACTOR_TYPES=new Set([...CREATURE_ACTOR_TYPES,"vehicle"]);class Migration672RemoveNPCBaseProperties extends MigrationBase{static{__name(this,"Migration672RemoveNPCBaseProperties")}static{__name2(this,"Migration672RemoveNPCBaseProperties")}static version=.672;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)}}class Migration673RemoveBulwarkREs extends MigrationBase{static{__name(this,"Migration673RemoveBulwarkREs")}static{__name2(this,"Migration673RemoveBulwarkREs")}static version=.673;hasRuleElement(rules){return rules.some(r=>typeof r.key=="string"&&r.key.endsWith("FlatModifier")&&isObject(r.predicate)&&!!r.predicate.all?.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)}}}const HOMEBREW_TRAIT_KEYS=["creatureTraits","featTraits","languages","spellTraits","weaponCategories","weaponGroups","baseWeapons","weaponTraits","equipmentTraits"],TRAIT_PROPAGATIONS={creatureTraits:["ancestryTraits"],equipmentTraits:["armorTraits","consumableTraits"],featTraits:["actionTraits"],weaponTraits:["npcAttackTraits"]};function itemIsOfType(item,...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,item.type):item.type===t)}__name(itemIsOfType,"itemIsOfType"),__name2(itemIsOfType,"itemIsOfType");function reduceItemName(label){return label.includes(":")?label.replace(/^[^:]+:\s*|\s*\([^)]+\)$/g,""):label}__name(reduceItemName,"reduceItemName"),__name2(reduceItemName,"reduceItemName");const{fields:fields$2}=foundry.data;class LaxSchemaField extends fields$2.SchemaField{static{__name(this,"LaxSchemaField")}static{__name2(this,"LaxSchemaField")}_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}}class StrictSchemaField extends fields$2.SchemaField{static{__name(this,"StrictSchemaField")}static{__name2(this,"StrictSchemaField")}_cast(value){return value}_cleanType(data,options){if(!isObject$1(data))throw Error(`${this.name} is not an object`);return super._cleanType(data,options)}}class StrictStringField extends fields$2.StringField{static{__name(this,"StrictStringField")}static{__name2(this,"StrictStringField")}_cast(value){return value}}class StrictNumberField extends fields$2.NumberField{static{__name(this,"StrictNumberField")}static{__name2(this,"StrictNumberField")}_cast(value){return value}}class StrictBooleanField extends fields$2.BooleanField{static{__name(this,"StrictBooleanField")}static{__name2(this,"StrictBooleanField")}_cast(value){return value}}class StrictArrayField extends fields$2.ArrayField{static{__name(this,"StrictArrayField")}static{__name2(this,"StrictArrayField")}_cast(value){return value}_cleanType(value){return Array.isArray(value)?super._cleanType(value):value}initialize(value,model,options){return Array.isArray(value)?super.initialize(value,model,options):null}}class StrictObjectField extends fields$2.ObjectField{static{__name(this,"StrictObjectField")}static{__name2(this,"StrictObjectField")}_cast(value){return value}}class DataUnionField extends fields$2.DataField{static{__name(this,"DataUnionField")}static{__name2(this,"DataUnionField")}fields;constructor(fields2,options){super(options),this.fields=fields2}_cast(value){return typeof value=="string"&&(value=value.trim()),value}clean(value,options){return Array.isArray(value)&&this.fields.some(f=>f instanceof foundry.data.fields.ArrayField)?this.fields.find(f=>f instanceof StrictArrayField)?.clean(value,options)??value:super.clean(value,options)}validate(value,options){const{DataModelValidationFailure}=foundry.data.validation,{StringField}=foundry.data.fields;for(const field of this.fields)if(!(field.validate(value,options)instanceof DataModelValidationFailure)){if(field instanceof StringField&&typeof value!="string")continue;return}return this.fields[0].validate(value,options)}initialize(value,model,options){return this.fields.find(f=>!f.validate(value))?.initialize(value,model,options)}}class SlugField extends StrictStringField{static{__name(this,"SlugField")}static{__name2(this,"SlugField")}constructor(options={}){options.blank=!1,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}}class PredicateStatementField extends fields$2.DataField{static{__name(this,"PredicateStatementField")}static{__name2(this,"PredicateStatementField")}constructor(options={}){super({...options,required:!0,nullable:!1,initial:void 0,validationError:"must be a recognized predication statement"})}_validateType(value){return StatementValidator.isStatement(value)}_cast(value){return value}_cleanType(value){return typeof value=="string"?value.trim():value}}class PredicateField extends StrictArrayField{static{__name(this,"PredicateField")}static{__name2(this,"PredicateField")}constructor(options={}){super(new PredicateStatementField,{label:"PF2E.RuleEditor.General.Predicate",...options})}initialize(value,model,options){const statements=super.initialize(value,model,options);return Array.isArray(statements)?new PredicatePF2e(...statements):statements}}class RecordField extends fields$2.ObjectField{static{__name(this,"RecordField")}static{__name2(this,"RecordField")}static recursive=!0;keyField;valueField;constructor(keyField,valueField,options){if(super(options),!this._isValidKeyFieldType(keyField))throw new Error("key field must be a StringField or a NumberField");if(this.keyField=keyField,!(valueField instanceof fields$2.DataField))throw new Error(`${this.name} must have a DataField as its contained field`);this.valueField=valueField}_isValidKeyFieldType(keyField){if(keyField instanceof fields$2.StringField||keyField instanceof fields$2.NumberField){if(keyField.options.required!==!0||keyField.options.nullable===!0)throw new Error("key field must be required and non-nullable");return!0}return!1}_validateValues(values,options){const validationFailure=foundry.data.validation.DataModelValidationFailure,failures=new validationFailure;for(const[key,value]of Object.entries(values)){if(key.startsWith("-=")&&options?.partial)continue;const keyFailure=this.keyField.validate(key,options);keyFailure&&failures.elements.push({id:key,failure:keyFailure});const valueFailure=this.valueField.validate(value,options);valueFailure&&failures.elements.push({id:`${key}-value`,failure:valueFailure})}if(failures.elements.length)return failures}_cleanType(values,options){for(const[key,value]of Object.entries(values))values[key]=this.valueField.clean(value,options);return values}_validateType(values,options){return isObject$1(values)?this._validateValues(values,options):new foundry.data.validation.DataModelValidationFailure({message:"must be an Object"})}initialize(values,model,options){if(!values)return values;const data={};for(const[key,value]of Object.entries(values))data[key]=this.valueField.initialize(value,model,options);return data}}class RuleElementPF2e extends foundry.abstract.DataModel{static{__name(this,"RuleElementPF2e")}static{__name2(this,"RuleElementPF2e")}sourceIndex;suppressWarnings;static validActorTypes=["army","character","familiar","hazard","npc","party","vehicle"];constructor(source,options){super(source,{parent:options.parent,strict:options.strict??!0,fallback:!1});const{item}=this;if(this.suppressWarnings=options.suppressWarnings??!this.actor.id,this.sourceIndex=options.sourceIndex??null,!tupleHasValue(this.constructor.validActorTypes,item.actor.type)){const actorType=game.i18n.localize(`TYPES.Actor.${item.actor.type}`);this.failValidation(`this rule element type cannot be applied to a ${actorType}`),source.ignored=!0}this.label=typeof source.label=="string"?game.i18n.format(this.resolveInjectedProperties(source.label),{actor:item.actor.name,item:item.name,origin:item.isOfType("effect")?item.origin?.name??null:null}):item.name,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(){const{fields:fields2}=foundry.data;return{key:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),slug:new SlugField({required:!0,nullable:!0,label:"PF2E.RuleEditor.General.Slug"}),label:new fields2.StringField({required:!1,nullable:!1,blank:!1,initial:void 0,label:"PF2E.RuleEditor.General.Label"}),priority:new fields2.NumberField({required:!0,nullable:!1,integer:!0,initial:100}),ignored:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),predicate:new PredicateField,requiresEquipped:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),requiresInvestment:new fields2.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 item(){return this.parent}get actor(){return this.parent.actor}get token(){const actor=this.actor;if(actor.token)return actor.token;const tokens=actor.getActiveTokens();return tokens.find(token=>token.controlled)?.document??tokens.shift()?.document??null}getReducedLabel(label=this.label){return reduceItemName(label)}validate(options={}){try{return super.validate(options)}catch(error){if(error instanceof foundry.data.validation.DataModelValidationError){const message=error.message.replace(/validation errors|Joint Validation Error/,`validation errors on item ${this.item.name} (${this.item.uuid})`);return console.warn(message),!1}else throw error}}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}`);const{DataModelValidationFailure}=foundry.data.validation;this.validationFailures.joint??=new DataModelValidationFailure({message:fullMessage,unresolved:!0})}this.ignored=!0}resolveInjectedProperties(source,{warn=!0}={}){if(source===null||typeof source=="number"||typeof source=="string"&&!source.includes("{"))return source;if(Array.isArray(source))for(let i=0;i<source.length;i++)source[i]=this.resolveInjectedProperties(source[i],{warn});else if(isObject$1(source)){for(const[key,value]of Object.entries(source))(typeof value=="string"||isObject(value))&&(source[key]=this.resolveInjectedProperties(value,{warn}));return source}else if(typeof source=="string")return source.replace(/{(actor|item|rule)\|(.*?)}/g,(_match,key,prop)=>{const data=key==="rule"?this:key==="actor"||key==="item"?this[key]:this.item,value=foundry.utils.getProperty(data,prop);return value===void 0&&(this.ignored=!0,warn&&this.failValidation(`Failed to resolve injected property "${source}"`)),String(value)});return source}resolveValue(value,defaultValue=0,{evaluate=!0,resolvables={},warn=!0}={}){if(value??=defaultValue??null,typeof value=="number"||typeof value=="boolean"||value===null)return value;value=this.resolveInjectedProperties(value,{warn});const resolvedFromBracket=this.isBracketedValue(value)?this.#resolveBracketedValue(value,defaultValue):value;if(typeof resolvedFromBracket=="number")return resolvedFromBracket;if(resolvedFromBracket instanceof Object)return defaultValue instanceof Object?foundry.utils.mergeObject(defaultValue,resolvedFromBracket,{inplace:!1}):resolvedFromBracket;if(typeof resolvedFromBracket=="string"){const saferEval=__name2(formula=>{try{const unresolveds=formula.match(/@[a-z.]+/gi)??[];if(unresolveds.length>0){const shouldWarn=warn&&!unresolveds.every(u=>u.startsWith("@target.")||u.startsWith("@actor.conditions."));return this.ignored=!0,shouldWarn&&this.failValidation(`unable to resolve formula, "${formula}"`),Number(defaultValue)}return Roll.safeEval(formula)}catch{return this.failValidation(`unable to evaluate formula, "${formula}"`),0}},"saferEval");this.actor.isOfType("character")&&(resolvables.armor=this.actor.wornArmor);const trimmed=resolvedFromBracket.trim();return(trimmed.includes("@")||/^-?\d+$/.test(trimmed))&&evaluate?saferEval(Roll.replaceFormulaData(trimmed,{actor:this.actor,item:this.item,...resolvables})):trimmed}return defaultValue}isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)&&(typeof value.field=="string"||!("fields"in value))}#resolveBracketedValue(value,defaultValue){const bracketNumber=(()=>{if(!value.field)return this.actor.level;const field=String(value.field),separator=field.indexOf("|"),source=field.substring(0,separator),{actor,item}=this;switch(source){case"actor":return Number(foundry.utils.getProperty(actor,field.substring(separator+1)))||0;case"item":return Number(foundry.utils.getProperty(item,field.substring(separator+1)))||0;case"rule":return Number(foundry.utils.getProperty(this,field.substring(separator+1)))||0;default:return Number(foundry.utils.getProperty(actor,field.substring(0)))||0}})(),brackets=value.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}})();return brackets.find(bracket=>{const start=bracket.start??0,end=bracket.end??1/0;return start<=bracketNumber&&end>=bracketNumber})?.value??bracketFallthrough}}class ResolvableValueField extends foundry.data.fields.DataField{static{__name(this,"ResolvableValueField")}static{__name2(this,"ResolvableValueField")}_validateType(value){return value!==null&&["string","number","object","boolean"].includes(typeof value)}_cast(value){return value}#coerceNumber(value){const trimmed=value.trim();return/^-?\d+(?:\.\d+)?$/.test(trimmed)?Number(trimmed):trimmed||0}_cleanType(value){if(typeof value=="string")return this.#coerceNumber(value);if(isObject(value)&&"brackets"in value){value.field||="actor|level";const brackets=value.brackets=compact(Object.values(value.brackets??{}));for(const bracket of brackets)bracket.start===null&&delete bracket.start,bracket.end===null&&delete bracket.end,bracket.value=typeof bracket.value=="string"?this.#coerceNumber(bracket.value):bracket.value}return value}}class ActorTraitsRuleElement extends RuleElementPF2e{static{__name(this,"ActorTraitsRuleElement")}static{__name2(this,"ActorTraitsRuleElement")}static validActorTypes=["character","npc","familiar","hazard","vehicle"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),add:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1})),remove:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}))}}constructor(data,options){super({...data,priority:99},options)}get#traitsDictionary(){switch(this.actor.type){case"character":case"familiar":case"npc":return CONFIG.PF2E.creatureTraits;case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:throw ErrorPF2e("unexpected actor type")}}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)),traitsDictionary=this.#traitsDictionary;for(const trait of newTraits){if(!(trait in traitsDictionary))return this.failValidation(`${trait} is not a recognized trait`);traits.value.push(trait),this.actor.rollOptions.all[`self:trait:${trait}`]=!0,["construct","undead"].includes(trait)&&this.#handleModeAffectingTrait()}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}`],["construct","undead"].includes(trait)&&this.#handleModeAffectingTrait()}}#handleModeAffectingTrait(){const{actor}=this,{rollOptions}=actor;for(const mode of["construct","living","undead"])delete rollOptions.all[`self:mode:${mode}`];rollOptions.all[`self:mode:${actor.modeOfBeing}`]=!0}}class DegreeOfSuccess{static{__name(this,"DegreeOfSuccess")}static{__name2(this,"DegreeOfSuccess")}value;unadjusted;adjustment;dieResult;rollTotal;dc;constructor(roll,dc,dosAdjustments=null){roll instanceof Roll?(this.dieResult=(roll.isDeterministic?roll.terms.find(t=>t instanceof NumericTerm):roll.dice.find(d=>d instanceof Die&&d.faces===20))?.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=this.#calculateDegreeOfSuccess(),this.adjustment=this.#getDegreeAdjustment(this.unadjusted,dosAdjustments),this.value=this.adjustment?this.#adjustDegreeOfSuccess(this.adjustment.amount,this.unadjusted):this.unadjusted}static CRITICAL_FAILURE=0;static FAILURE=1;static SUCCESS=2;static CRITICAL_SUCCESS=3;#getDegreeAdjustment(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}#adjustDegreeOfSuccess(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)}}#adjustDegreeByDieValue(degree){return this.dieResult===20?this.#adjustDegreeOfSuccess(DEGREE_ADJUSTMENT_AMOUNTS.INCREASE,degree):this.dieResult===1?this.#adjustDegreeOfSuccess(DEGREE_ADJUSTMENT_AMOUNTS.LOWER,degree):degree}#calculateDegreeOfSuccess(){const dc=this.dc.value;return this.rollTotal-dc>=10?this.#adjustDegreeByDieValue(DegreeOfSuccess.CRITICAL_SUCCESS):dc-this.rollTotal>=10?this.#adjustDegreeByDieValue(DegreeOfSuccess.CRITICAL_FAILURE):this.rollTotal>=dc?this.#adjustDegreeByDieValue(DegreeOfSuccess.SUCCESS):this.#adjustDegreeByDieValue(DegreeOfSuccess.FAILURE)}}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{static{__name(this,"AdjustDegreeOfSuccessRuleElement")}static{__name2(this,"AdjustDegreeOfSuccessRuleElement")}static validActorTypes=["character","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),adjustment:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["all",...DEGREE_OF_SUCCESS_STRINGS]}),new fields2.StringField({required:!0,nullable:!1,choices:degreeAdjustmentAmountString}),{required:!0,nullable:!1})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),adjustments=this.adjustment,stringToAdjustment={"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:stringToAdjustment[adjustment]}),accumulated},{});(this.actor.synthetics.degreeOfSuccessAdjustments[selector]??=[]).push({adjustments:record,predicate:this.predicate})}}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 AELikeRuleElement extends RuleElementPF2e{static{__name(this,"AELikeRuleElement")}static{__name2(this,"AELikeRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=this.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(this.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),path:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),phase:new fields2.StringField({required:!1,nullable:!1,choices:foundry.utils.deepClone(this.PHASES),initial:"applyAEs"}),value:new ResolvableValueField({required:!0,nullable:!0,initial:void 0}),merge:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0})}}static CHANGE_MODE_DEFAULT_PRIORITIES={multiply:10,add:20,subtract:20,remove:20,downgrade:30,upgrade:40,override:50};static PHASES=["applyAEs","beforeDerived","afterDerived","beforeRoll"];static#SKILL_LONG_FORM_PATH=(()=>{const skillLongForms=Array.from(SKILL_LONG_FORMS).join("|");return new RegExp(String.raw`^system\.skills\.(${skillLongForms})\b`)})();static validateJoint(data){if(super.validateJoint(data),data.merge){if(data.mode!=="override")throw new foundry.data.validation.DataModelValidationError(' merge: `mode` must be "override"');if(!isObject(data.value))throw new foundry.data.validation.DataModelValidationError(" merge: `value` must an object")}}#rewriteSkillLongFormPath(path){return path.replace(AELikeRuleElement.#SKILL_LONG_FORM_PATH,(match,group)=>objectHasKey(SKILL_EXPANDED,group)?`system.skills.${SKILL_EXPANDED[group].shortForm}`:match)}#pathIsValid(path){const actor=this.item.actor;return path.length>0&&!/\bnull\b/.test(path)&&(path.startsWith("flags.")||[path,path.replace(/\.[-\w]+$/,""),path.replace(/\.?[-\w]+\.[-\w]+$/,"")].some(path2=>foundry.utils.getProperty(actor,path2)!==void 0))}async preCreate(){this.phase==="applyAEs"&&this.#applyAELike()}onApplyActiveEffects(){this.phase==="applyAEs"&&this.#applyAELike()}beforePrepareData(){this.phase==="beforeDerived"&&this.#applyAELike()}afterPrepareData(){this.phase==="afterDerived"&&this.#applyAELike()}beforeRoll(_domains,rollOptions){this.phase==="beforeRoll"&&this.#applyAELike(rollOptions)}#applyAELike(rollOptions){if(this.ignored)return;const path=this.#rewriteSkillLongFormPath(this.resolveInjectedProperties(this.path));if(this.ignored)return;if(!this.#pathIsValid(path))return this.failValidation(`no data found at or near "${path}"`);if(rollOptions??=this.predicate.length>0?new Set(this.actor.getRollOptions()):new Set,!this.test(rollOptions))return;const{actor}=this,current=foundry.utils.getProperty(actor,path),change=this.resolveValue(this.value),newValue=AELikeRuleElement.getNewValue(this.mode,current,change,this.merge);if(newValue instanceof foundry.data.validation.DataModelValidationFailure)return this.failValidation(newValue.asError().message);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{foundry.utils.setProperty(actor,path,newValue),this.#logChange(change)}catch(error){error instanceof Error?this.failValidation(error.message):console.warn(error)}}static getNewValue(mode,current,change,merge=!1){const{DataModelValidationFailure}=foundry.data.validation,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:new DataModelValidationFailure({invalidValue:value,fallback:!1})},"addOrSubtract");switch(mode){case"multiply":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.trunc((current??0)*change):new DataModelValidationFailure({invalidValue:current,fallback:!1});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"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.min(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"upgrade":return typeof change!="number"?new DataModelValidationFailure({invalidValue:change,fallback:!1}):typeof current=="number"||current===void 0?Math.max(current??0,change):new DataModelValidationFailure({invalidValue:current,fallback:!1});case"override":return merge&&isObject(current)&&isObject(change)?foundry.utils.mergeObject(current,change):change;default:return null}}#logChange(value){const{item,mode}=this;if(!(typeof value=="boolean"||typeof value=="number"||typeof value=="string"||value===null))return;const level=item.isOfType("feat")?Number(/-(\d+)$/.exec(item.system.location??"")?.[1])||item.level:"level"in item&&typeof item.level=="number"?item.level:null,{autoChanges}=this.actor.system;(autoChanges[this.path]??=[]).push({mode,level,value,source:this.item.name})}}class AdjustModifierRuleElement extends RuleElementPF2e{static{__name(this,"AdjustModifierRuleElement")}static{__name2(this,"AdjustModifierRuleElement")}applications=0;constructor(source,options){source.suppress&&(source.mode="override"),super(source,options),typeof source.selector=="string"&&this.selectors.length===0&&(this.selectors=[source.selector]),this.suppress??=!1,this.maxApplications??=1/0}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>PRIORITIES[String(d.mode)]??50,{...baseSchema,mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),selector:new fields2.StringField({required:!1,blank:!1,initial:void 0}),selectors:new StrictArrayField(new fields2.StringField({required:!0,blank:!1})),relabel:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),suppress:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),maxApplications:new fields2.NumberField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!0,initial:null})}}static validateJoint(data){super.validateJoint(data);const{DataModelValidationError}=foundry.data.validation;if(data.suppress===!0){if(typeof data.maxApplications=="number")throw new DataModelValidationError(" use of `maxApplications` in combination with `suppress` is not currently supported")}else if(data.value===null&&!data.damageType)throw new DataModelValidationError(" value: must be provided unless damageType is provided or suppress is true")}beforePrepareData(){if(this.ignored)return;const predicate=new PredicatePF2e(this.resolveInjectedProperties(foundry.utils.deepClone([...this.predicate]))),adjustment={slug:this.slug,test:options=>predicate.test([...options,...this.item.getRollOptions("parent")]),suppress:this.suppress,getNewValue:current=>{if(this.value===null)return current;const change=this.resolveValue(this.value);return typeof change!="number"||Number.isNaN(change)?(this.failValidation("value: must resolve to a number"),current):this.ignored?current:(this.applications+=1,this.applications===this.maxApplications&&(this.ignored=!0),Math.trunc(AELikeRuleElement.getNewValue(this.mode,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))){if(selector==="null")continue;(this.actor.synthetics.modifierAdjustments[selector]??=[]).push(adjustment)}}}class AdjustStrikeRuleElement extends RuleElementPF2e{static{__name(this,"AdjustStrikeRuleElement")}static{__name2(this,"AdjustStrikeRuleElement")}static validActorTypes=["character","familiar","npc"];constructor(data,options){super({...data,priority:110},options)}static VALID_PROPERTIES=new Set(["materials","property-runes","range-increment","traits","weapon-traits"]);static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:keys.strict(AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES),initial:void 0}),property:new fields2.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})}}beforePrepareData(){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.range?.increment;if(typeof rangeIncrement!="number")return this.failValidation("A weapon that meets the definition lacks a range increment.");const newRangeIncrement=AELikeRuleElement.getNewValue(this.mode,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)&&!(weapon.isOfType("melee")&&objectHasKey(CONFIG.PF2E.npcAttackTraits,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][-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(!["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(RUNE_DATA.weapon.property,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,RUNE_DATA.weapon.property)}}}})();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)}}function createDamageFormula(damage,degree=DEGREE_OF_SUCCESS.SUCCESS){if(damage={...foundry.utils.deepClone(omit(damage,["dice"])),dice:damage.dice.map(d=>d.clone())},degree===DEGREE_OF_SUCCESS.CRITICAL_FAILURE)return null;degree===DEGREE_OF_SUCCESS.FAILURE&&(damage.dice=damage.dice.filter(d=>d.category==="splash"),damage.modifiers=damage.modifiers.filter(m=>m.damageCategory==="splash"));const critical=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS;if(!damage.base.length)return null;applyDamageDiceOverrides(damage.base,damage.dice,{critical,maxIncreases:damage.maxIncreases});const typeMap=new Map;for(const baseEntry of damage.base){const list=typeMap.get(baseEntry.damageType)??[];if(typeMap.set(baseEntry.damageType,list),baseEntry.terms)list.push(...baseEntry.terms.map(t=>({...baseEntry,...t,label:null,critical:null})));else if(baseEntry.diceNumber&&baseEntry.dieSize||baseEntry.modifier){const{diceNumber,dieSize,damageType}=baseEntry,modifier=baseEntry.modifier??0,label=(()=>{const diceSection=diceNumber?`${diceNumber}${dieSize}`:null;if(!diceSection)return String(modifier);const displayedModifier=modifier?Math.abs(modifier):null,operator=modifier<0?" - ":" + ";return[diceSection,displayedModifier].filter(p=>p!==null).join(operator)})();list.push({label,dice:diceNumber&&dieSize?{number:diceNumber,faces:Number(dieSize.replace("d",""))}:null,modifier,critical:null,damageType,category:baseEntry.category,materials:baseEntry.materials??[]})}}const BONUS_BASE_LABELS=["PF2E.ConditionTypePersistent"].map(l=>game.i18n.localize(l)),outcomeMatches=__name2(m=>critical||m.critical!==!0,"outcomeMatches");for(const dice of damage.dice.filter(d=>d.enabled&&outcomeMatches(d))){const matchingBase=damage.base.find(b=>b.damageType===dice.damageType)??damage.base[0],baseDieSize=Number(matchingBase.dieSize?.replace("d",""))||matchingBase.terms?.[0].dice?.faces,faces=Number(dice.dieSize?.replace("d",""))||baseDieSize||null,damageType=dice.damageType??matchingBase.damageType;if(dice.diceNumber>0&&faces){const list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(dice.label)?null:`${dice.label} +${dice.diceNumber}d${faces}`,dice:{number:dice.diceNumber,faces},modifier:0,damageType,category:dice.category,critical:dice.critical}),typeMap.set(damageType,list)}}for(const modifier of damage.modifiers.filter(m=>m.enabled&&outcomeMatches(m))){const bonusableDamage=[...damage.base,...damage.dice,...damage.modifiers.filter(m=>m.value>0&&m.type==="untyped")],matchingDamage=modifier.kind==="modifier"?bonusableDamage.find(b=>b.damageType===(modifier.damageType??b.damageType))??damage.base.at(0):bonusableDamage.find(b=>b.damageType===(modifier.damageType??b.damageType)&&b.category===modifier.category);if(!matchingDamage)continue;const damageType=modifier.damageType??matchingDamage.damageType??"untyped",list=typeMap.get(damageType)??[];list.push({label:BONUS_BASE_LABELS.includes(modifier.label)?null:`${modifier.label} ${signedInteger(modifier.value)}`,dice:null,modifier:modifier.value,damageType,category:modifier.damageCategory,critical:modifier.critical}),typeMap.set(damageType,list)}const instances=[instancesFromTypeMap(typeMap,{degree,kinds:damage.kinds}),instancesFromTypeMap(typeMap,{degree,persistent:!0})].flat(),commaSeparated=instances.map(i=>i.formula).join(","),breakdown=instances.flatMap(i=>i.breakdown);return{formula:`{${commaSeparated}}`,breakdown}}__name(createDamageFormula,"createDamageFormula"),__name2(createDamageFormula,"createDamageFormula");function instancesFromTypeMap(typeMap,{degree,kinds=new Set(["damage"]),persistent=!1}){return Array.from(typeMap.entries()).flatMap(([damageType,typePartials])=>{const partials=typePartials.filter(p=>p.category==="persistent"===persistent);if(partials.length===0)return[];const groups=groupBy(partials,partial=>partial.category),nonCriticalDamage=(()=>{const criticalInclusion=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?[CRITICAL_INCLUSION.DOUBLE_ON_CRIT]:[CRITICAL_INCLUSION.DOUBLE_ON_CRIT,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT],doubleDice=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&criticalInclusion.includes(null)&&game.settings.get("pf2e","critRule")==="doubledice",double=degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&!doubleDice;return sumExpression(createPartialFormulas(groups,{criticalInclusion,doubleDice}),{double})})(),criticalDamage=(()=>{if(degree!==DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)return null;const criticalInclusion=[CRITICAL_INCLUSION.CRITICAL_ONLY,CRITICAL_INCLUSION.DONT_DOUBLE_ON_CRIT];return sumExpression(createPartialFormulas(groups,{criticalInclusion}))})(),summedDamage=sumExpression(degree?[nonCriticalDamage,criticalDamage]:[nonCriticalDamage]),enclosed=ensureValidFormulaHead(summedDamage)||"0";if(enclosed==="0"&&persistent)return[];const flavor=(()=>{const kindFlavor=kinds.has("damage")?kinds.has("healing")?["damage","healing"]:[]:["healing"],typeFlavor=damageType==="untyped"&&!persistent?[]:[damageType],persistentFlavor=persistent?["persistent"]:[],materialFlavor=typePartials.flatMap(p=>p.materials??[]),allFlavor=[kindFlavor,typeFlavor,persistentFlavor,materialFlavor].flat().join(",");return allFlavor.length>0?`[${allFlavor}]`:""})(),breakdown=(()=>{const flattenedDamage=[null,"persistent","precision","splash"].flatMap(c=>{const partials2=groups.get(c)??[],breakdownDamage2=partials2.filter(e=>e.label!==null),leadingTerms=partials2.filter(p=>p.label===null&&(p.modifier||p.dice?.number||partials2.every(pp=>pp.label===null)));if(leadingTerms.length){const append=c==="splash"?` ${game.i18n.localize("PF2E.TraitSplash")}`:"",label=createSimpleFormula(leadingTerms)+append;breakdownDamage2.unshift({...leadingTerms[0],label})}return breakdownDamage2}),breakdownDamage=flattenedDamage.filter(d=>d.critical!==!0);if(degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&breakdownDamage.push(...flattenedDamage.filter(d=>d.critical===!0)),breakdownDamage.length===0)return[];const damageTypeLabel=breakdownDamage[0].category==="persistent"?game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType)}):game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]??damageType),labelParts=breakdownDamage.map(d=>d.label);return labelParts[0]=`${labelParts[0].replace(/^\s+\+/,"")} ${damageTypeLabel}`,labelParts})(),formula=enclosed&&flavor?`${enclosed}${flavor}`:enclosed;return formula?{formula,breakdown}:[]})}__name(instancesFromTypeMap,"instancesFromTypeMap"),__name2(instancesFromTypeMap,"instancesFromTypeMap");function createPartialFormulas(partials,{criticalInclusion,doubleDice=!1}){return[null,"persistent","precision","splash"].flatMap(category=>{const requestedPartials=(partials.get(category)??[]).filter(p=>criticalInclusion.includes(p.critical)),term=(()=>{const expression=createSimpleFormula(requestedPartials,{doubleDice});return expression==="0"?"":["precision","splash"].includes(category??"")&&hasOperators(expression)?`(${expression})`:expression})();return(term&&category&&category!=="persistent"?term.endsWith("]")?`(${term})[${category}]`:`${term}[${category}]`:term)||[]})}__name(createPartialFormulas,"createPartialFormulas"),__name2(createPartialFormulas,"createPartialFormulas");function combinePartialTerms(terms){const modifier=terms.reduce((total,p)=>total+p.modifier,0),constantTerm=modifier?{dice:null,modifier}:null,dice=sortBy(terms.filter(p=>!!p.dice&&p.dice.number>0),t=>-t.dice.faces),combinedDice=[...groupBy(dice,t=>t.dice.faces).values()].map(terms2=>({modifier:0,dice:{...terms2[0].dice,number:sumBy(terms2,t=>t.dice.number)}})),combined=compact([...combinedDice,constantTerm]);return combined.length?combined:[{dice:null,modifier:0}]}__name(combinePartialTerms,"combinePartialTerms"),__name2(combinePartialTerms,"combinePartialTerms");function createSimpleFormula(terms,{doubleDice}={}){terms=combinePartialTerms(terms);const constant=terms.find(t=>!!t.modifier)?.modifier??0;return[terms.filter(t=>!!t.dice&&t.dice.number>0).map(term=>{const number=doubleDice?term.dice.number*2:term.dice.number,faces=term.dice.faces;return doubleDice?`${number}d${faces}[doubled]`:`${number}d${faces}`}).join(" + "),Math.abs(constant)].filter(e=>!!e).map(e=>typeof e=="number"&&doubleDice?`2 * ${e}`:e).join(constant>0?" + ":" - ")||"0"}__name(createSimpleFormula,"createSimpleFormula"),__name2(createSimpleFormula,"createSimpleFormula");function parseTermsFromSimpleFormula(formula,options){return(formula instanceof Roll?formula:new Roll(formula,options?.rollData)).terms.reduceRight((result,term)=>{if(term.expression===" + ")return result;if(term.expression===" - "){const termToModify=result[0];return termToModify&&(termToModify.modifier&&(termToModify.modifier*=-1),termToModify.dice&&(termToModify.dice.number*=-1)),result}return result.unshift({modifier:term instanceof NumericTerm?term.number:0,dice:term instanceof Die?{faces:term.faces,number:term.number}:null}),result},[])}__name(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula"),__name2(parseTermsFromSimpleFormula,"parseTermsFromSimpleFormula");function sumExpression(terms,{double=!1}={}){if(terms.every(t=>!t))return null;const summed=terms.filter(p=>!!p).join(" + ")||null,enclosed=double&&hasOperators(summed)?`(${summed})`:summed;return double?`2 * ${enclosed}`:enclosed}__name(sumExpression,"sumExpression"),__name2(sumExpression,"sumExpression");function hasOperators(formula){return/[-+*/]/.test(formula??"")}__name(hasOperators,"hasOperators"),__name2(hasOperators,"hasOperators");function ensureValidFormulaHead(formula){if(!formula)return null;const isWrapped=/^\(.*\)$/.test(formula),isSimple=/^\d+(d\d+)?$/.test(formula);return isWrapped||isSimple?formula:`(${formula})`}__name(ensureValidFormulaHead,"ensureValidFormulaHead"),__name2(ensureValidFormulaHead,"ensureValidFormulaHead");class ArithmeticExpression extends RollTerm{static{__name(this,"ArithmeticExpression")}static{__name2(this,"ArithmeticExpression")}operator;operands;constructor(termData){super(termData),this.operator=termData.operator,this.operands=termData.operands.slice(0,2).map(datum=>{if(datum instanceof RollTerm)return datum;const TermCls=CONFIG.Dice.termTypes[datum.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===datum.class)??Die;return simplifyTerm(TermCls.fromData(datum))})}static SERIALIZE_ATTRIBUTES=["operator","operands"];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&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this))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)}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()]}}}class Grouping extends RollTerm{static{__name(this,"Grouping")}static{__name2(this,"Grouping")}term;constructor(termData){const TermCls=CONFIG.Dice.termTypes[termData.term.class??""]??Object.values(CONFIG.Dice.terms).find(t=>t.name===termData.term.class)??NumericTerm,childTerm=simplifyTerm(TermCls.fromData(termData.term));childTerm instanceof Grouping?(super(childTerm.toJSON()),this.term=childTerm.term):(super(termData),this.term=childTerm,this.#dataIsCriticalDoubling(termData.term)&&(this.options.crit=!0)),this._evaluated=termData.evaluated??this.term._evaluated??!0}static SERIALIZE_ATTRIBUTES=["term"];static fromData(data){return super.fromData({...data,class:"Grouping"})}get dice(){if(this.term instanceof DiceTerm)return[this.term];const childDice="dice"in this.term?this.term.dice:null;return Array.isArray(childDice)&&childDice.every(d=>d instanceof DiceTerm)?childDice:[]}get expression(){return this.isDeterministic&&typeof this.total=="number"&&!Number.isNaN(this.total)&&!isFlavoredArithmetic(this.term)?this.total.toString():this.term instanceof DiceTerm||this.term instanceof MathTerm?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(){const thisTotal=this.total;return typeof thisTotal=="number"&&this.options.crit?thisTotal/2:this.term instanceof ArithmeticExpression||this.term instanceof Grouping?this.term.critImmuneTotal:thisTotal}get isDeterministic(){return this.term.isDeterministic}get minimumValue(){return DamageInstance.getValue(this.term,"minimum")}get expectedValue(){return DamageInstance.getValue(this.term)}get maximumValue(){return DamageInstance.getValue(this.term,"maximum")}#dataIsCriticalDoubling(data){return"operator"in data&&data.operator==="*"&&"operands"in data&&Array.isArray(data.operands)&&data.operands.length===2&&data.operands.every(o=>isObject$1(o))&&data.operands[0].number===2}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}}class IntermediateDie extends RollTerm{static{__name(this,"IntermediateDie")}static{__name2(this,"IntermediateDie")}number;faces;die;constructor(data){super(data);const setTerm=__name2(termData=>{if(typeof termData=="number")return termData;const TermCls=CONFIG.Dice.termTypes[termData.class??"NumericTerm"],term=simplifyTerm(TermCls.fromData(termData));return term instanceof NumericTerm?term.number:term.isDeterministic?Roll.safeEval(term.formula):term instanceof Grouping?(term.isIntermediate=!0,term):(term instanceof MathTerm||console.warn(`Unexpected term type: ${term.constructor.name}`),term)},"setTerm");this.number=setTerm(data.number),this.faces=setTerm(data.faces),this.die=(()=>data.die?Die.fromData({...data.die,class:"Die"}):typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):null)()}static SERIALIZE_ATTRIBUTES=["number","faces","die"];get expression(){return this.die?.expression??`${this.number}d${this.faces}`}get total(){return this.isDeterministic?Number(this.number)*Number(this.faces):this.die?.total}get dice(){return this.die?[this.die]:[]}get isDeterministic(){return this.number===0||this.faces===0||this.faces===1}get minimumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"minimum")}get expectedValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}))}get maximumValue(){return DamageInstance.getValue(this.die??new Die({number:Number(this.number),faces:Number(this.faces)}),"maximum")}async _evaluate(){return typeof this.number!="number"&&(this.number=(await this.number.evaluate({async:!0})).total),typeof this.faces!="number"&&(this.faces=(await this.faces.evaluate({async:!0})).total),this.die=await new Die({number:this.number,faces:this.faces,options:this.options}).evaluate({async:!0}),this._evaluated=!0,this}toJSON(){return this.die?this.die.toJSON():typeof this.number=="number"&&typeof this.faces=="number"?Die.fromData({class:"Die",number:this.number,faces:this.faces,evaluated:this._evaluated,options:this.options}):{...super.toJSON(),number:typeof this.number=="number"?this.number:this.number.toJSON(),faces:typeof this.faces=="number"?this.faces:this.faces.toJSON()}}}class InstancePool extends PoolTerm{static{__name(this,"InstancePool")}static{__name2(this,"InstancePool")}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}}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)}},FACES=[4,6,8,10,12];function applyDamageDiceOverrides(baseEntries,dice,options={}){const critical=options.critical??!1,maxIncreases=options.maxIncreases??1/0,overrideDice=dice.filter(d=>!d.ignored&&!!d.override);if(overrideDice.length)for(const base of baseEntries){const die=base.terms?.find(t=>!!t.dice);if(base.terms&&!die)continue;const adjustments=overrideDice.filter(m=>(m.critical===null||critical&&m.critical||!critical&&!m.critical)&&(!m.damageType||m.damageType===base.damageType)),numUpgrades=Math.min(maxIncreases,adjustments.filter(d=>d.override?.upgrade).length),numDowngrades=Math.min(maxIncreases,adjustments.filter(d=>d.override?.downgrade).length),delta=numUpgrades-numDowngrades;for(let i=0;i<Math.abs(delta);i++)if(die){const direction=delta>0?1:-1;die.dice.faces=FACES[FACES.indexOf(die.dice.faces)+direction]??die.dice.faces}else base.dieSize&&(base.dieSize=delta>0?nextDamageDieSize({upgrade:base.dieSize}):nextDamageDieSize({downgrade:base.dieSize}));for(const adjustment of adjustments)if(adjustment.override){base.damageType=adjustment.override.damageType??base.damageType;for(const die2 of dice.filter(d=>/^(?:deadly|fatal)-/.test(d.slug)))die2.damageType=adjustment.override.damageType??die2.damageType;if(die){if(die.dice.number=adjustment.override.diceNumber??die.dice.number,adjustment.override.dieSize){const faces=Number(/\d{1,2}/.exec(adjustment.override.dieSize)?.shift());Number.isInteger(faces)&&(die.dice.faces=faces)}}else base.dieSize=adjustment.override.dieSize??base.dieSize,base.diceNumber=adjustment.override.diceNumber??base.diceNumber}}}__name(applyDamageDiceOverrides,"applyDamageDiceOverrides"),__name2(applyDamageDiceOverrides,"applyDamageDiceOverrides");function extractBaseDamage(roll){function recursiveExtractTerms(expression,{category=null}={}){if(category=setHasElement(DAMAGE_CATEGORIES_UNIQUE,expression.options.flavor)?expression.options.flavor:category,expression instanceof Grouping)return recursiveExtractTerms(expression.term,{category});if(expression instanceof Die)return[{dice:pick(expression,["number","faces"]),modifier:0,category}];if(expression instanceof IntermediateDie){if(typeof expression.number!="number"||typeof expression.faces!="number")throw ErrorPF2e("Unable to parse DamageRoll with non-deterministic intermediate expressions.");return[{dice:{number:expression.number,faces:expression.faces},modifier:0,category}]}if(expression.isDeterministic)return[{dice:null,modifier:DamageInstance.getValue(expression,"expected"),category}];if(expression instanceof ArithmeticExpression){const operator=expression.operator;if(operator==="*"||operator==="/")throw ErrorPF2e(`Cannot use ${operator} on non-deterministic artithmetic terms`);const leftTerms=recursiveExtractTerms(expression.operands[0],{category}),rightTerms=recursiveExtractTerms(expression.operands[1],{category});if(operator==="-")for(const term of rightTerms)term.dice&&(term.dice.number*=-1),term.modifier*=-1;const groups=groupBy$1([...leftTerms,...rightTerms],t=>t.category??"");return Object.values(groups).flatMap(terms=>{const category2=terms[0].category;return combinePartialTerms(terms).map(t=>({...t,category:category2}))})}throw expression.isDeterministic?ErrorPF2e("Unrecognized roll term type "+expression.constructor.name):ErrorPF2e(`Unable to parse DamageRoll with non-deterministic ${expression.constructor.name}.`)}return __name(recursiveExtractTerms,"recursiveExtractTerms"),__name2(recursiveExtractTerms,"recursiveExtractTerms"),roll.instances.flatMap(instance=>{const category=setHasElement(DAMAGE_CATEGORIES_UNIQUE,instance.category)?instance.category:null,terms=recursiveExtractTerms(instance.head,{category});return Object.values(groupBy$1(terms,t=>t.category??"")).map(terms2=>{const category2=instance.persistent?"persistent":terms2[0].category;return{damageType:instance.type,category:category2,terms:terms2.map(t=>omit(t,["category"]))}})})}__name(extractBaseDamage,"extractBaseDamage"),__name2(extractBaseDamage,"extractBaseDamage");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 simplifyTerm(term){if(term instanceof IntermediateDie)return term.die??term;const shouldPreserve=__name2(t=>!t.isDeterministic||t instanceof NumericTerm||isFlavoredArithmetic(t),"shouldPreserve");if(shouldPreserve(term)||term instanceof Grouping&&shouldPreserve(term.term))return term;try{const total=term.total??Roll.defaultImplementation.safeEval(term.expression);if(typeof total!="number"||Number.isNaN(total))throw Error(`Unable to evaluate deterministic term: ${term.expression}`);return NumericTerm.fromData({class:"NumericTerm",number:total,evaluated:term._evaluated,options:term.options})}catch{return term}}__name(simplifyTerm,"simplifyTerm"),__name2(simplifyTerm,"simplifyTerm");function isFlavoredArithmetic(term){return term instanceof ArithmeticExpression&&term.operands.some(o=>o.options.flavor)}__name(isFlavoredArithmetic,"isFlavoredArithmetic"),__name2(isFlavoredArithmetic,"isFlavoredArithmetic");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=!1}={}){const firstTerm=roll instanceof DamageRoll&&roll.instances[0]?.head instanceof IntermediateDie?roll.instances[0]?.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");class AbstractDamageRoll extends Roll{static{__name(this,"AbstractDamageRoll")}static{__name2(this,"AbstractDamageRoll")}static replaceFormulaData(formula,data,options={}){return super.replaceFormulaData(formula.trim(),data,options).replace(/(?<![a-z])\((\d+)\)/gi,"$1")}_evaluateSync(){throw ErrorPF2e("Damage rolls must be evaluated asynchronously")}}class DamageRoll extends AbstractDamageRoll{static{__name(this,"DamageRoll")}static{__name2(this,"DamageRoll")}roller;constructor(formula,data={},options={}){formula=formula.trim();const wrapped=formula.startsWith("{")?formula:`{${formula}}`;if(super(wrapped,data,options),this.roller=game.users.get(options.rollerId??"")??null,tupleHasValue(["double-damage","double-dice"],options.critRule))for(const instance of this.instances)instance.critRule=options.critRule;else delete options.critRule;if(options.evaluatePersistent)for(const instance of this.instances)instance.options.evaluatePersistent=!0}static CHAT_TEMPLATE="systems/pf2e/templates/dice/damage-roll.hbs";static TOOLTIP_TEMPLATE="systems/pf2e/templates/dice/damage-tooltip.hbs";static parse(formula,data){const replaced=this.replaceFormulaData(formula,data,{missing:"0"}),poolData=(()=>{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.replace(/@([a-z.0-9_-]+)/gi,"1"));return isObject(result)&&"class"in result&&["PoolTerm","InstancePool"].includes(String(result.class))}catch{return!1}}static classifyDice(data){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=CONFIG.Dice.terms[term.faces]?.name;if(!termClassName)throw ErrorPF2e(`No matching DiceTerm class for "${term.faces}"`);term.class=termClassName}}get pool(){const firstTerm=this.terms.at(0);return firstTerm instanceof InstancePool?firstTerm:null}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(){return this.pool?.rolls.filter(r=>r instanceof DamageInstance)??[]}get kinds(){return new Set(this.instances.flatMap(i=>Array.from(i.kinds)))}get materials(){return new Set(this.instances.flatMap(i=>Array.from(i.materials)))}get dice(){const{instances}=this;return instances.length>0?instances.flatMap(i=>i.dice):super.dice}get minimumValue(){return this.instances.reduce((sum,i)=>sum+i.minimumValue,0)}get expectedValue(){return this.instances.reduce((sum,i)=>sum+i.expectedValue,0)}get maximumValue(){return this.instances.reduce((sum,i)=>sum+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||this.options.evaluatePersistent)&&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 formula=isPrivate?"???":(await Promise.all(instances.map(i=>i.render()))).join(" + "),total=this.total??NaN,damageKinds=this.kinds,chatData={formula,user:game.user.id,tooltip:isPrivate||this.dice.length===0?"":await this.getTooltip(),instances:isPrivate?[]:instances,total:isPrivate?"?":Math.floor(total*100/100),increasedFrom:this.options.increasedFrom,splashOnly:!!this.options.splashOnly,damageOnly:!damageKinds.has("healing"),healingOnly:!damageKinds.has("damage"),allPersistent:this.instances.every(i=>i.persistent),persistentEvaluated:this.instances.some(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:[foundry.utils.deepClone(multiplierTerm),rightOperand]});return[2,3].includes(multiplier)&&(expression.options.crit=multiplier),DamageInstance.fromTerms([expression],foundry.utils.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],foundry.utils.deepClone(firstInstance.options))}return DamageRoll.fromTerms([InstancePool.fromRolls(instanceClones)])}}class DamageInstance extends AbstractDamageRoll{static{__name(this,"DamageInstance")}static{__name2(this,"DamageInstance")}kinds;type;persistent;materials;critRule=null;constructor(formula,data={},options={}){super(formula.trim(),data,options);const flavorIdentifiers=options.flavor?.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=new Set(flavorIdentifiers.filter(i=>objectHasKey(CONFIG.PF2E.materialDamageEffects,i))),!this.persistent&&this.materials.size===0&&["vitality","void","untyped"].includes(this.type)&&flavorIdentifiers.includes("healing")?flavorIdentifiers.includes("damage")?this.kinds=new Set(["damage","healing"]):this.kinds=new Set(["healing"]):this.kinds=new Set(["damage"])}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);const roll=super.fromData(data);return roll.terms=roll.terms.map(t=>simplifyTerm(t)),roll}static getValue(term,type="expected"){if(term instanceof NumericTerm)return term.number;if(term instanceof MathTerm)try{return Roll.safeEval(term.formula)}catch{return 0}switch(type){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":[],Array.from(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({tooltips=!0}={}){const span=document.createElement("span");if(span.classList.add(this.type,"damage","instance","color"),tooltips&&(span.dataset.tooltip=this.typeLabel),span.append(this.#renderFormula()),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}#renderFormula(){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}get dice(){return this._dice.concat(this.terms.reduce((dice,term)=>(term instanceof DiceTerm?dice.push(term):(term instanceof Grouping||term instanceof ArithmeticExpression||term instanceof IntermediateDie)&&dice.push(...term.dice),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.total===void 0)return;const{head}=this,undoubledTotal=head instanceof ArithmeticExpression||head instanceof Grouping?head.critImmuneTotal??0:this.total;if(this.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((sum,r)=>sum+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}}Promise.resolve().then(()=>{const Evaluator=function(){}.constructor;new Evaluator("AbstractDamageRoll",`// Generated by Peggy 3.0.2.
|
|
//
|
|
// https://peggyjs.org/
|
|
(function() {
|
|
"use strict";
|
|
|
|
|
|
function createNumericTerm(number, { flavor = null, truncate = false } = {}) {
|
|
number = truncate ? Math.trunc(number) : number;
|
|
const formula = flavor ? \`\${number}[\${flavor}]\` : number.toString();
|
|
const obj = {
|
|
class: "NumericTerm",
|
|
number,
|
|
formula,
|
|
evaluated: false,
|
|
};
|
|
if (flavor) obj.options = { flavor };
|
|
|
|
return obj;
|
|
}
|
|
|
|
function peg$subclass(child, parent) {
|
|
function C() { this.constructor = child; }
|
|
C.prototype = parent.prototype;
|
|
child.prototype = new C();
|
|
}
|
|
|
|
function peg$SyntaxError(message, expected, found, location) {
|
|
var self = Error.call(this, message);
|
|
// istanbul ignore next Check is a necessary evil to support older environments
|
|
if (Object.setPrototypeOf) {
|
|
Object.setPrototypeOf(self, peg$SyntaxError.prototype);
|
|
}
|
|
self.expected = expected;
|
|
self.found = found;
|
|
self.location = location;
|
|
self.name = "SyntaxError";
|
|
return self;
|
|
}
|
|
|
|
peg$subclass(peg$SyntaxError, Error);
|
|
|
|
function peg$padEnd(str, targetLength, padString) {
|
|
padString = padString || " ";
|
|
if (str.length > targetLength) { return str; }
|
|
targetLength -= str.length;
|
|
padString += padString.repeat(targetLength);
|
|
return str + padString.slice(0, targetLength);
|
|
}
|
|
|
|
peg$SyntaxError.prototype.format = function(sources) {
|
|
var str = "Error: " + this.message;
|
|
if (this.location) {
|
|
var src = null;
|
|
var k;
|
|
for (k = 0; k < sources.length; k++) {
|
|
if (sources[k].source === this.location.source) {
|
|
src = sources[k].text.split(/\\r\\n|\\n|\\r/g);
|
|
break;
|
|
}
|
|
}
|
|
var s = this.location.start;
|
|
var offset_s = (this.location.source && (typeof this.location.source.offset === "function"))
|
|
? this.location.source.offset(s)
|
|
: s;
|
|
var loc = this.location.source + ":" + offset_s.line + ":" + offset_s.column;
|
|
if (src) {
|
|
var e = this.location.end;
|
|
var filler = peg$padEnd("", offset_s.line.toString().length, ' ');
|
|
var line = src[s.line - 1];
|
|
var last = s.line === e.line ? e.column : line.length + 1;
|
|
var hatLen = (last - s.column) || 1;
|
|
str += "\\n --> " + loc + "\\n"
|
|
+ filler + " |\\n"
|
|
+ offset_s.line + " | " + line + "\\n"
|
|
+ filler + " | " + peg$padEnd("", s.column - 1, ' ')
|
|
+ peg$padEnd("", hatLen, "^");
|
|
} else {
|
|
str += "\\n 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();
|
|
}
|
|
|
|
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); });
|
|
}
|
|
|
|
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); });
|
|
}
|
|
|
|
function describeExpectation(expectation) {
|
|
return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
|
|
}
|
|
|
|
function describeExpected(expected) {
|
|
var descriptions = expected.map(describeExpectation);
|
|
var i, j;
|
|
|
|
descriptions.sort();
|
|
|
|
if (descriptions.length > 0) {
|
|
for (i = 1, j = 1; i < descriptions.length; i++) {
|
|
if (descriptions[i - 1] !== descriptions[i]) {
|
|
descriptions[j] = descriptions[i];
|
|
j++;
|
|
}
|
|
}
|
|
descriptions.length = j;
|
|
}
|
|
|
|
switch (descriptions.length) {
|
|
case 1:
|
|
return descriptions[0];
|
|
|
|
case 2:
|
|
return descriptions[0] + " or " + descriptions[1];
|
|
|
|
default:
|
|
return descriptions.slice(0, -1).join(", ")
|
|
+ ", or "
|
|
+ descriptions[descriptions.length - 1];
|
|
}
|
|
}
|
|
|
|
function describeFound(found) {
|
|
return found ? "\\"" + literalEscape(found) + "\\"" : "end of input";
|
|
}
|
|
|
|
return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
|
|
};
|
|
|
|
function peg$parse(input, options) {
|
|
options = options !== undefined ? options : {};
|
|
|
|
var peg$FAILED = {};
|
|
var peg$source = options.grammarSource;
|
|
|
|
var peg$startRuleFunctions = { Expression: peg$parseExpression };
|
|
var peg$startRuleFunction = peg$parseExpression;
|
|
|
|
var peg$c0 = "+";
|
|
var peg$c1 = "-";
|
|
var peg$c2 = "*";
|
|
var peg$c3 = "/";
|
|
var peg$c4 = "(";
|
|
var peg$c5 = ",";
|
|
var peg$c6 = ")";
|
|
var peg$c7 = "{";
|
|
var peg$c8 = "}";
|
|
var peg$c9 = "[";
|
|
var peg$c10 = "]";
|
|
var peg$c11 = ".";
|
|
|
|
var peg$r0 = /^[dD]/;
|
|
var peg$r1 = /^[\\-+]/;
|
|
var peg$r2 = /^[0-9]/;
|
|
var peg$r3 = /^[a-z$_]/i;
|
|
var peg$r4 = /^[a-z$_0-9]/i;
|
|
var peg$r5 = /^[^ (){}[\\]+\\-*\\/,]/;
|
|
var peg$r6 = /^[^[\\]]/;
|
|
var peg$r7 = /^[ ]/;
|
|
|
|
var peg$e0 = peg$literalExpectation("+", false);
|
|
var peg$e1 = peg$literalExpectation("-", false);
|
|
var peg$e2 = peg$literalExpectation("*", false);
|
|
var peg$e3 = peg$literalExpectation("/", false);
|
|
var peg$e4 = peg$literalExpectation("(", false);
|
|
var peg$e5 = peg$literalExpectation(",", false);
|
|
var peg$e6 = peg$literalExpectation(")", false);
|
|
var peg$e7 = peg$classExpectation(["d", "D"], false, false);
|
|
var peg$e8 = peg$literalExpectation("{", false);
|
|
var peg$e9 = peg$literalExpectation("}", false);
|
|
var peg$e10 = peg$literalExpectation("[", false);
|
|
var peg$e11 = peg$literalExpectation("]", false);
|
|
var peg$e12 = peg$classExpectation(["-", "+"], false, false);
|
|
var peg$e13 = peg$classExpectation([["0", "9"]], false, false);
|
|
var peg$e14 = peg$literalExpectation(".", false);
|
|
var peg$e15 = peg$classExpectation([["a", "z"], "$", "_"], false, true);
|
|
var peg$e16 = peg$classExpectation([["a", "z"], "$", "_", ["0", "9"]], false, true);
|
|
var peg$e17 = peg$classExpectation([" ", "(", ")", "{", "}", "[", "]", "+", "-", "*", "/", ","], true, false);
|
|
var peg$e18 = peg$otherExpectation("string");
|
|
var peg$e19 = peg$classExpectation(["[", "]"], true, false);
|
|
var peg$e20 = peg$otherExpectation("whitespace");
|
|
var peg$e21 = peg$classExpectation([" "], false, false);
|
|
|
|
var peg$f0 = function(head, tail) {
|
|
return tail.reduce((result, elements) => {
|
|
const operator = elements[1];
|
|
const operands = [
|
|
result,
|
|
elements.find((e) => typeof e === "number" || e instanceof Object && e.class)
|
|
].map((e) => typeof e === "number" ? createNumericTerm(e, { truncate: true }) : e);
|
|
return {
|
|
class: "ArithmeticExpression",
|
|
formula: text(),
|
|
operator,
|
|
operands,
|
|
evaluated: false,
|
|
};
|
|
}, head);
|
|
};
|
|
var peg$f1 = function(head, tail) {
|
|
return tail.reduce((result, elements) => {
|
|
const operator = elements[1];
|
|
const 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: false,
|
|
};
|
|
}, head);
|
|
};
|
|
var peg$f2 = 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: false,
|
|
};
|
|
};
|
|
var peg$f3 = 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: false,
|
|
}
|
|
: {
|
|
class: "DiceTerm",
|
|
formula: text(),
|
|
number: number ?? 1,
|
|
faces,
|
|
evaluated: false,
|
|
};
|
|
|
|
if (modifiers) obj.modifiers = modifiers;
|
|
if (flavor) obj.options = { flavor };
|
|
|
|
return obj;
|
|
};
|
|
var peg$f4 = function(expression, flavor) {
|
|
const obj = {
|
|
class: "Grouping",
|
|
formula: text(),
|
|
term: typeof expression === "number" ? createNumericTerm(expression) : expression,
|
|
evaluated: false,
|
|
};
|
|
if (flavor) obj.options = { flavor };
|
|
|
|
return obj;
|
|
};
|
|
var peg$f5 = function(head, tail, modifiers, flavor) {
|
|
const headTerm = typeof head === "number" ? createNumericTerm(head) : head;
|
|
const tailTerms = tail.map((t) => typeof t === "number" ? createNumericTerm(t) : t);
|
|
const terms = [headTerm.formula, ...tailTerms.map((t) => t.formula)];
|
|
const firstRoll = {
|
|
class: "DamageInstance",
|
|
formula: headTerm.formula,
|
|
terms: [headTerm],
|
|
evaluated: false
|
|
};
|
|
if (headTerm.options?.flavor) {
|
|
firstRoll.options = { flavor: headTerm.options.flavor };
|
|
}
|
|
|
|
const rolls = [
|
|
firstRoll,
|
|
...tailTerms.map((term) => {
|
|
const obj = {
|
|
class: "DamageInstance",
|
|
formula: term.formula,
|
|
terms: [term],
|
|
evaluated: false,
|
|
};
|
|
if (term.options?.flavor) {
|
|
obj.options = { flavor: term.options.flavor };
|
|
}
|
|
|
|
return obj;
|
|
}),
|
|
];
|
|
|
|
const obj = {
|
|
class: "InstancePool",
|
|
formula: text(),
|
|
terms,
|
|
rolls,
|
|
evaluated: false,
|
|
};
|
|
|
|
if (flavor) obj.options = { flavor };
|
|
if (modifiers) obj.modifiers = modifiers;
|
|
|
|
return obj;
|
|
};
|
|
var peg$f6 = function(string) {
|
|
return string;
|
|
};
|
|
var peg$f7 = function() {
|
|
const numified = Number(text());
|
|
return input === text() ? createNumericTerm(numified) : numified;
|
|
};
|
|
var peg$f8 = function(number, flavor) {
|
|
return createNumericTerm(number, { flavor });
|
|
};
|
|
var peg$f9 = function() {
|
|
return Array.from(text().matchAll(/([A-z]+)([^A-z\\s()+\\-*\\/]+)?/g)).map((m) => m[0]);
|
|
};
|
|
var peg$currPos = 0;
|
|
var peg$savedPos = 0;
|
|
var peg$posDetailsCache = [{ line: 1, column: 1 }];
|
|
var peg$maxFailPos = 0;
|
|
var peg$maxFailExpected = [];
|
|
var peg$silentFails = 0;
|
|
|
|
var 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);
|
|
}
|
|
|
|
function offset() {
|
|
return peg$savedPos;
|
|
}
|
|
|
|
function range() {
|
|
return {
|
|
source: peg$source,
|
|
start: peg$savedPos,
|
|
end: peg$currPos
|
|
};
|
|
}
|
|
|
|
function location() {
|
|
return peg$computeLocation(peg$savedPos, peg$currPos);
|
|
}
|
|
|
|
function expected(description, location) {
|
|
location = location !== undefined
|
|
? location
|
|
: peg$computeLocation(peg$savedPos, peg$currPos);
|
|
|
|
throw peg$buildStructuredError(
|
|
[peg$otherExpectation(description)],
|
|
input.substring(peg$savedPos, peg$currPos),
|
|
location
|
|
);
|
|
}
|
|
|
|
function error(message, location) {
|
|
location = location !== undefined
|
|
? location
|
|
: peg$computeLocation(peg$savedPos, peg$currPos);
|
|
|
|
throw peg$buildSimpleError(message, location);
|
|
}
|
|
|
|
function peg$literalExpectation(text, ignoreCase) {
|
|
return { type: "literal", text: text, ignoreCase: ignoreCase };
|
|
}
|
|
|
|
function peg$classExpectation(parts, inverted, ignoreCase) {
|
|
return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase };
|
|
}
|
|
|
|
function peg$anyExpectation() {
|
|
return { type: "any" };
|
|
}
|
|
|
|
function peg$endExpectation() {
|
|
return { type: "end" };
|
|
}
|
|
|
|
function peg$otherExpectation(description) {
|
|
return { type: "other", description: description };
|
|
}
|
|
|
|
function peg$computePosDetails(pos) {
|
|
var details = peg$posDetailsCache[pos];
|
|
var p;
|
|
|
|
if (details) {
|
|
return details;
|
|
} else {
|
|
p = pos - 1;
|
|
while (!peg$posDetailsCache[p]) {
|
|
p--;
|
|
}
|
|
|
|
details = peg$posDetailsCache[p];
|
|
details = {
|
|
line: details.line,
|
|
column: details.column
|
|
};
|
|
|
|
while (p < pos) {
|
|
if (input.charCodeAt(p) === 10) {
|
|
details.line++;
|
|
details.column = 1;
|
|
} else {
|
|
details.column++;
|
|
}
|
|
|
|
p++;
|
|
}
|
|
|
|
peg$posDetailsCache[pos] = details;
|
|
|
|
return details;
|
|
}
|
|
}
|
|
|
|
function peg$computeLocation(startPos, endPos, offset) {
|
|
var startPosDetails = peg$computePosDetails(startPos);
|
|
var endPosDetails = peg$computePosDetails(endPos);
|
|
|
|
var res = {
|
|
source: peg$source,
|
|
start: {
|
|
offset: startPos,
|
|
line: startPosDetails.line,
|
|
column: startPosDetails.column
|
|
},
|
|
end: {
|
|
offset: endPos,
|
|
line: endPosDetails.line,
|
|
column: endPosDetails.column
|
|
}
|
|
};
|
|
if (offset && peg$source && (typeof peg$source.offset === "function")) {
|
|
res.start = peg$source.offset(res.start);
|
|
res.end = peg$source.offset(res.end);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
function peg$fail(expected) {
|
|
if (peg$currPos < peg$maxFailPos) { return; }
|
|
|
|
if (peg$currPos > peg$maxFailPos) {
|
|
peg$maxFailPos = peg$currPos;
|
|
peg$maxFailExpected = [];
|
|
}
|
|
|
|
peg$maxFailExpected.push(expected);
|
|
}
|
|
|
|
function peg$buildSimpleError(message, location) {
|
|
return new peg$SyntaxError(message, null, null, location);
|
|
}
|
|
|
|
function peg$buildStructuredError(expected, found, location) {
|
|
return new peg$SyntaxError(
|
|
peg$SyntaxError.buildMessage(expected, found),
|
|
expected,
|
|
found,
|
|
location
|
|
);
|
|
}
|
|
|
|
function peg$parseExpression() {
|
|
var s0, s1, s2, s3, s4, s5, s6, s7;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parsePool();
|
|
if (s1 === peg$FAILED) {
|
|
s1 = peg$parseTerm();
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = [];
|
|
s3 = peg$currPos;
|
|
s4 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 43) {
|
|
s5 = peg$c0;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e0); }
|
|
}
|
|
if (s5 === peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 45) {
|
|
s5 = peg$c1;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e1); }
|
|
}
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parse_();
|
|
s7 = peg$parsePool();
|
|
if (s7 === peg$FAILED) {
|
|
s7 = peg$parseTerm();
|
|
}
|
|
if (s7 !== peg$FAILED) {
|
|
s4 = [s4, s5, s6, s7];
|
|
s3 = s4;
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
while (s3 !== peg$FAILED) {
|
|
s2.push(s3);
|
|
s3 = peg$currPos;
|
|
s4 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 43) {
|
|
s5 = peg$c0;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e0); }
|
|
}
|
|
if (s5 === peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 45) {
|
|
s5 = peg$c1;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e1); }
|
|
}
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parse_();
|
|
s7 = peg$parsePool();
|
|
if (s7 === peg$FAILED) {
|
|
s7 = peg$parseTerm();
|
|
}
|
|
if (s7 !== peg$FAILED) {
|
|
s4 = [s4, s5, s6, s7];
|
|
s3 = s4;
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f0(s1, s2);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseTerm() {
|
|
var s0, s1, s2, s3, s4, s5, s6, s7;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parseTermOperand();
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = [];
|
|
s3 = peg$currPos;
|
|
s4 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 42) {
|
|
s5 = peg$c2;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e2); }
|
|
}
|
|
if (s5 === peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 47) {
|
|
s5 = peg$c3;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e3); }
|
|
}
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parse_();
|
|
s7 = peg$parseTermOperand();
|
|
if (s7 !== peg$FAILED) {
|
|
s4 = [s4, s5, s6, s7];
|
|
s3 = s4;
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
while (s3 !== peg$FAILED) {
|
|
s2.push(s3);
|
|
s3 = peg$currPos;
|
|
s4 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 42) {
|
|
s5 = peg$c2;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e2); }
|
|
}
|
|
if (s5 === peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 47) {
|
|
s5 = peg$c3;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e3); }
|
|
}
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parse_();
|
|
s7 = peg$parseTermOperand();
|
|
if (s7 !== peg$FAILED) {
|
|
s4 = [s4, s5, s6, s7];
|
|
s3 = s4;
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s3;
|
|
s3 = peg$FAILED;
|
|
}
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f1(s1, s2);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseTermOperand() {
|
|
var s0;
|
|
|
|
s0 = peg$parseDiceTerm();
|
|
if (s0 === peg$FAILED) {
|
|
s0 = peg$parseMathTerm();
|
|
if (s0 === peg$FAILED) {
|
|
s0 = peg$parseGrouping();
|
|
if (s0 === peg$FAILED) {
|
|
s0 = peg$parseFlavoredNumber();
|
|
if (s0 === peg$FAILED) {
|
|
s0 = peg$parseNumber();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseMathTerm() {
|
|
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parseIdentifier();
|
|
if (s1 !== peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 40) {
|
|
s2 = peg$c4;
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e4); }
|
|
}
|
|
if (s2 !== peg$FAILED) {
|
|
s3 = peg$parse_();
|
|
s4 = peg$parseExpression();
|
|
if (s4 === peg$FAILED) {
|
|
s4 = null;
|
|
}
|
|
s5 = peg$parse_();
|
|
s6 = [];
|
|
s7 = peg$currPos;
|
|
s8 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 44) {
|
|
s9 = peg$c5;
|
|
peg$currPos++;
|
|
} else {
|
|
s9 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e5); }
|
|
}
|
|
if (s9 !== peg$FAILED) {
|
|
s10 = peg$parse_();
|
|
s11 = peg$parseExpression();
|
|
if (s11 !== peg$FAILED) {
|
|
s7 = s11;
|
|
} else {
|
|
peg$currPos = s7;
|
|
s7 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s7;
|
|
s7 = peg$FAILED;
|
|
}
|
|
while (s7 !== peg$FAILED) {
|
|
s6.push(s7);
|
|
s7 = peg$currPos;
|
|
s8 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 44) {
|
|
s9 = peg$c5;
|
|
peg$currPos++;
|
|
} else {
|
|
s9 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e5); }
|
|
}
|
|
if (s9 !== peg$FAILED) {
|
|
s10 = peg$parse_();
|
|
s11 = peg$parseExpression();
|
|
if (s11 !== peg$FAILED) {
|
|
s7 = s11;
|
|
} else {
|
|
peg$currPos = s7;
|
|
s7 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s7;
|
|
s7 = peg$FAILED;
|
|
}
|
|
}
|
|
s7 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 41) {
|
|
s8 = peg$c6;
|
|
peg$currPos++;
|
|
} else {
|
|
s8 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e6); }
|
|
}
|
|
if (s8 !== peg$FAILED) {
|
|
peg$savedPos = s0;
|
|
s0 = peg$f2(s1, s4, s6);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseDiceTerm() {
|
|
var s0, s1, s2, s3, s4, s5;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parseGrouping();
|
|
if (s1 === peg$FAILED) {
|
|
s1 = peg$parseMathTerm();
|
|
if (s1 === peg$FAILED) {
|
|
s1 = peg$parseNumber();
|
|
}
|
|
}
|
|
if (s1 === peg$FAILED) {
|
|
s1 = null;
|
|
}
|
|
if (peg$r0.test(input.charAt(peg$currPos))) {
|
|
s2 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e7); }
|
|
}
|
|
if (s2 !== peg$FAILED) {
|
|
s3 = peg$parseGrouping();
|
|
if (s3 === peg$FAILED) {
|
|
s3 = peg$parseMathTerm();
|
|
if (s3 === peg$FAILED) {
|
|
s3 = peg$parseNumber();
|
|
if (s3 === peg$FAILED) {
|
|
s3 = peg$parseIdentifier();
|
|
}
|
|
}
|
|
}
|
|
if (s3 !== peg$FAILED) {
|
|
s4 = peg$parseModifiers();
|
|
if (s4 === peg$FAILED) {
|
|
s4 = null;
|
|
}
|
|
s5 = peg$parseFlavor();
|
|
if (s5 === peg$FAILED) {
|
|
s5 = null;
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f3(s1, s3, s4, s5);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseGrouping() {
|
|
var s0, s1, s2, s3, s4, s5, s6;
|
|
|
|
s0 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 40) {
|
|
s1 = peg$c4;
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e4); }
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = peg$parse_();
|
|
s3 = peg$parseExpression();
|
|
if (s3 !== peg$FAILED) {
|
|
s4 = peg$parse_();
|
|
if (input.charCodeAt(peg$currPos) === 41) {
|
|
s5 = peg$c6;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e6); }
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parseFlavor();
|
|
if (s6 === peg$FAILED) {
|
|
s6 = null;
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f4(s3, s6);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parsePool() {
|
|
var s0, s1, s2, s3, s4, s5, s6, s7, s8;
|
|
|
|
s0 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 123) {
|
|
s1 = peg$c7;
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e8); }
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = peg$parse_();
|
|
s3 = peg$parseExpression();
|
|
if (s3 !== peg$FAILED) {
|
|
s4 = [];
|
|
s5 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 44) {
|
|
s6 = peg$c5;
|
|
peg$currPos++;
|
|
} else {
|
|
s6 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e5); }
|
|
}
|
|
if (s6 !== peg$FAILED) {
|
|
s7 = peg$parse_();
|
|
s8 = peg$parseExpression();
|
|
if (s8 !== peg$FAILED) {
|
|
s5 = s8;
|
|
} else {
|
|
peg$currPos = s5;
|
|
s5 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s5;
|
|
s5 = peg$FAILED;
|
|
}
|
|
while (s5 !== peg$FAILED) {
|
|
s4.push(s5);
|
|
s5 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 44) {
|
|
s6 = peg$c5;
|
|
peg$currPos++;
|
|
} else {
|
|
s6 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e5); }
|
|
}
|
|
if (s6 !== peg$FAILED) {
|
|
s7 = peg$parse_();
|
|
s8 = peg$parseExpression();
|
|
if (s8 !== peg$FAILED) {
|
|
s5 = s8;
|
|
} else {
|
|
peg$currPos = s5;
|
|
s5 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s5;
|
|
s5 = peg$FAILED;
|
|
}
|
|
}
|
|
if (input.charCodeAt(peg$currPos) === 125) {
|
|
s5 = peg$c8;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e9); }
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = peg$parseModifiers();
|
|
if (s6 === peg$FAILED) {
|
|
s6 = null;
|
|
}
|
|
s7 = peg$parseFlavor();
|
|
if (s7 === peg$FAILED) {
|
|
s7 = null;
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f5(s3, s4, s6, s7);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseFlavor() {
|
|
var s0, s1, s2, s3;
|
|
|
|
s0 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 91) {
|
|
s1 = peg$c9;
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e10); }
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = peg$currPos;
|
|
s3 = peg$parseFlavorString();
|
|
if (s3 !== peg$FAILED) {
|
|
s2 = input.substring(s2, peg$currPos);
|
|
} else {
|
|
s2 = s3;
|
|
}
|
|
if (s2 !== peg$FAILED) {
|
|
if (input.charCodeAt(peg$currPos) === 93) {
|
|
s3 = peg$c10;
|
|
peg$currPos++;
|
|
} else {
|
|
s3 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e11); }
|
|
}
|
|
if (s3 !== peg$FAILED) {
|
|
peg$savedPos = s0;
|
|
s0 = peg$f6(s2);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseNumber() {
|
|
var s0, s1, s2, s3, s4, s5, s6, s7;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parse_();
|
|
if (peg$r1.test(input.charAt(peg$currPos))) {
|
|
s2 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e12); }
|
|
}
|
|
if (s2 === peg$FAILED) {
|
|
s2 = null;
|
|
}
|
|
s3 = [];
|
|
if (peg$r2.test(input.charAt(peg$currPos))) {
|
|
s4 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s4 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e13); }
|
|
}
|
|
if (s4 !== peg$FAILED) {
|
|
while (s4 !== peg$FAILED) {
|
|
s3.push(s4);
|
|
if (peg$r2.test(input.charAt(peg$currPos))) {
|
|
s4 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s4 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e13); }
|
|
}
|
|
}
|
|
} else {
|
|
s3 = peg$FAILED;
|
|
}
|
|
if (s3 !== peg$FAILED) {
|
|
s4 = peg$currPos;
|
|
if (input.charCodeAt(peg$currPos) === 46) {
|
|
s5 = peg$c11;
|
|
peg$currPos++;
|
|
} else {
|
|
s5 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e14); }
|
|
}
|
|
if (s5 !== peg$FAILED) {
|
|
s6 = [];
|
|
if (peg$r2.test(input.charAt(peg$currPos))) {
|
|
s7 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s7 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e13); }
|
|
}
|
|
if (s7 !== peg$FAILED) {
|
|
while (s7 !== peg$FAILED) {
|
|
s6.push(s7);
|
|
if (peg$r2.test(input.charAt(peg$currPos))) {
|
|
s7 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s7 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e13); }
|
|
}
|
|
}
|
|
} else {
|
|
s6 = peg$FAILED;
|
|
}
|
|
if (s6 !== peg$FAILED) {
|
|
s5 = [s5, s6];
|
|
s4 = s5;
|
|
} else {
|
|
peg$currPos = s4;
|
|
s4 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s4;
|
|
s4 = peg$FAILED;
|
|
}
|
|
if (s4 === peg$FAILED) {
|
|
s4 = null;
|
|
}
|
|
peg$savedPos = s0;
|
|
s0 = peg$f7();
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseFlavoredNumber() {
|
|
var s0, s1, s2;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$parseNumber();
|
|
if (s1 !== peg$FAILED) {
|
|
s2 = peg$parseFlavor();
|
|
if (s2 !== peg$FAILED) {
|
|
peg$savedPos = s0;
|
|
s0 = peg$f8(s1, s2);
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
} else {
|
|
peg$currPos = s0;
|
|
s0 = peg$FAILED;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseIdentifier() {
|
|
var s0, s1, s2, s3, s4;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = peg$currPos;
|
|
if (peg$r3.test(input.charAt(peg$currPos))) {
|
|
s2 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e15); }
|
|
}
|
|
if (s2 !== peg$FAILED) {
|
|
s3 = [];
|
|
if (peg$r4.test(input.charAt(peg$currPos))) {
|
|
s4 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s4 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e16); }
|
|
}
|
|
while (s4 !== peg$FAILED) {
|
|
s3.push(s4);
|
|
if (peg$r4.test(input.charAt(peg$currPos))) {
|
|
s4 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s4 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e16); }
|
|
}
|
|
}
|
|
s2 = [s2, s3];
|
|
s1 = s2;
|
|
} else {
|
|
peg$currPos = s1;
|
|
s1 = peg$FAILED;
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
s0 = input.substring(s0, peg$currPos);
|
|
} else {
|
|
s0 = s1;
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseModifiers() {
|
|
var s0, s1, s2;
|
|
|
|
s0 = peg$currPos;
|
|
s1 = [];
|
|
if (peg$r5.test(input.charAt(peg$currPos))) {
|
|
s2 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e17); }
|
|
}
|
|
if (s2 !== peg$FAILED) {
|
|
while (s2 !== peg$FAILED) {
|
|
s1.push(s2);
|
|
if (peg$r5.test(input.charAt(peg$currPos))) {
|
|
s2 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s2 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e17); }
|
|
}
|
|
}
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
peg$savedPos = s0;
|
|
s1 = peg$f9();
|
|
}
|
|
s0 = s1;
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parseFlavorString() {
|
|
var s0, s1;
|
|
|
|
peg$silentFails++;
|
|
s0 = [];
|
|
if (peg$r6.test(input.charAt(peg$currPos))) {
|
|
s1 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e19); }
|
|
}
|
|
if (s1 !== peg$FAILED) {
|
|
while (s1 !== peg$FAILED) {
|
|
s0.push(s1);
|
|
if (peg$r6.test(input.charAt(peg$currPos))) {
|
|
s1 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e19); }
|
|
}
|
|
}
|
|
} else {
|
|
s0 = peg$FAILED;
|
|
}
|
|
peg$silentFails--;
|
|
if (s0 === peg$FAILED) {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e18); }
|
|
}
|
|
|
|
return s0;
|
|
}
|
|
|
|
function peg$parse_() {
|
|
var s0, s1;
|
|
|
|
peg$silentFails++;
|
|
s0 = [];
|
|
if (peg$r7.test(input.charAt(peg$currPos))) {
|
|
s1 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e21); }
|
|
}
|
|
while (s1 !== peg$FAILED) {
|
|
s0.push(s1);
|
|
if (peg$r7.test(input.charAt(peg$currPos))) {
|
|
s1 = input.charAt(peg$currPos);
|
|
peg$currPos++;
|
|
} else {
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e21); }
|
|
}
|
|
}
|
|
peg$silentFails--;
|
|
s1 = peg$FAILED;
|
|
if (peg$silentFails === 0) { peg$fail(peg$e20); }
|
|
|
|
return s0;
|
|
}
|
|
|
|
peg$result = peg$startRuleFunction();
|
|
|
|
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
|
|
return peg$result;
|
|
} else {
|
|
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
|
|
peg$fail(peg$endExpectation());
|
|
}
|
|
|
|
throw peg$buildStructuredError(
|
|
peg$maxFailExpected,
|
|
peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
|
|
peg$maxFailPos < input.length
|
|
? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)
|
|
: peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
|
|
);
|
|
}
|
|
}
|
|
|
|
AbstractDamageRoll.parser = { SyntaxError: peg$SyntaxError, parse: peg$parse };
|
|
})()
|
|
`).call(void 0,AbstractDamageRoll)});const{fields:fields$1,validation}=foundry.data;class ItemAlterationValidator extends fields$1.SchemaField{static{__name(this,"ItemAlterationValidator")}static{__name2(this,"ItemAlterationValidator")}#validateForItem;operableOnInstances;operableOnSource;constructor(fields2,options={}){super(fields2,options),options.validateForItem&&(this.#validateForItem=options.validateForItem),this.operableOnInstances=options.operableOnInstances??!0,this.operableOnSource=options.operableOnSource??!0}isValid(data){const{item,alteration}=data,failure=this.validate(alteration);if(failure)throw new validation.DataModelValidationError(failure);if(item.type!==alteration.itemType)return!1;const forItemFailure=this.#validateForItem?.(item);if(forItemFailure)throw new validation.DataModelValidationError(forItemFailure);if(!this.operableOnInstances&&item instanceof ItemPF2e)throw new validation.DataModelValidationError("may only be applied to source data");if(!this.operableOnSource&&!(item instanceof ItemPF2e))throw new validation.DataModelValidationError("may only be applied to existing items");return!0}}const itemHasCounterBadge=__name2(item=>{if(!(itemIsOfType(item,"condition")?typeof item.system.value.value=="number":itemIsOfType(item,"effect")?item.system.badge?.type==="counter":!1))throw new foundry.data.validation.DataModelValidationError("effect lacks a badge")},"itemHasCounterBadge"),ITEM_ALTERATION_VALIDATORS={"ac-bonus":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor","shield"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),"badge-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["effect"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override"]}),value:new fields$1.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),"badge-value":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition","effect"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem:itemHasCounterBadge}),bulk:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new StrictNumberField({required:!0,nullable:!1,choices:[0,.1,...Array.fromRange(100,1)],initial:void 0})}),category:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:["light","heavy","medium"],initial:void 0})}),"dex-cap":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),"check-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),hardness:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"hp-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,nullable:!1,positive:!0,initial:void 0})}),"material-type":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:Array.from(PRECIOUS_MATERIAL_TYPES),initial:void 0})}),"pd-recovery-dc":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0,initial:void 0})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),"persistent-damage":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["condition"]}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.SchemaField({formula:new fields$1.StringField({required:!0,blank:!1,validate:value=>DamageRoll.validate(String(value))}),damageType:new fields$1.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes}),dc:new fields$1.NumberField({required:!0,integer:!0,positive:!0,nullable:!1,initial:15})},{nullable:!1})},{validateForItem(item){if(item.system.slug!=="persistent-damage")return new foundry.data.validation.DataModelValidationFailure({message:"item must be a persistent damage condition"})}}),rarity:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:Array.from(PHYSICAL_ITEM_TYPES)}),mode:new fields$1.StringField({required:!0,choices:["override"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:RARITIES})}),"frequency-max":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"]}),value:new fields$1.NumberField({required:!0,integer:!0,nullable:!1,positive:!0})}),"frequency-per":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["action","feat"]}),mode:new fields$1.StringField({required:!0,choices:["downgrade","override","upgrade"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>Object.keys(CONFIG.PF2E.frequencies),initial:void 0})}),"other-tags":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:()=>keys.strict(CONFIG.PF2E.Item.documentClasses)}),mode:new fields$1.StringField({required:!0,choices:["add","subtract","remove"]}),value:new SlugField({required:!0,nullable:!1,blank:!1,initial:void 0})}),"speed-penalty":new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor","shield"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,initial:void 0})}),strength:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","downgrade","override","remove","subtract","upgrade"]}),value:new StrictNumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})}),traits:new ItemAlterationValidator({itemType:new fields$1.StringField({required:!0,choices:["armor"]}),mode:new fields$1.StringField({required:!0,choices:["add","remove","subtract"]}),value:new fields$1.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.armorTraits,initial:void 0})})};class ItemAlteration extends foundry.abstract.DataModel{static{__name(this,"ItemAlteration")}static{__name2(this,"ItemAlteration")}static VALID_PROPERTIES=["ac-bonus","badge-max","badge-value","bulk","category","check-penalty","dex-cap","hardness","hp-max","material-type","pd-recovery-dc","persistent-damage","rarity","frequency-max","frequency-per","other-tags","speed-penalty","strength","traits"];static defineSchema(){const{fields:fields2}=foundry.data;return{mode:new fields2.StringField({required:!0,choices:["add","downgrade","multiply","override","remove","subtract","upgrade"],initial:void 0}),property:new fields2.StringField({required:!0,choices:this.VALID_PROPERTIES,initial:void 0}),value:new ResolvableValueField}}get actor(){return this.parent.actor}resolveValue(...args){return this.parent.resolveValue(...args)}applyTo(item){const data={item,alteration:{mode:this.mode,itemType:item.type,value:this.value=this.parent.resolveValue(this.value)}},{DataModelValidationFailure}=foundry.data.validation;switch(this.property){case"ac-bonus":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const item2=data.item,newValue=AELikeRuleElement.getNewValue(this.mode,item2.system.acBonus,data.alteration.value),itemBonus=itemIsOfType(item2,"armor")&&this.mode==="override"?item2.system.runes.potency:0;item2.system.acBonus=Math.max(newValue,0)+itemBonus,this.#adjustCreatureShieldData(item2);return}case"badge-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,{badge}=effect.system;if(badge?.type!=="counter"||typeof badge.value!="number"||typeof badge.max!="number")return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.max,data.alteration.value),hardMax=badge.labels?.length??newValue,min=badge.min??0;badge.max=Math.clamped(newValue,min,hardMax),badge.value=Math.clamped(badge.value,min,badge.max)||0;return}case"badge-value":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const effect=data.item,badge=itemIsOfType(effect,"condition")?effect.system.value:effect.system.badge??{value:0};if(typeof badge.value!="number")return;const newValue=AELikeRuleElement.getNewValue(this.mode,badge.value,data.alteration.value),max="max"in badge?badge.max??1/0:1/0,min="min"in badge?badge.min??0:0;badge.value=Math.clamped(newValue,min,max)||0;return}case"bulk":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=Number(data.alteration.value)||0,!validator.isValid(data))return;data.item.system.bulk.value=data.alteration.value,data.item instanceof foundry.abstract.DataModel&&(data.item.system.bulk=prepareBulkData(data.item));return}case"category":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.category=data.alteration.value);return}case"check-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.checkPenalty,data.alteration.value);data.item.system.checkPenalty=Math.min(newValue,0);return}case"dex-cap":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.dexCap,data.alteration.value);data.item.system.dexCap=Math.max(newValue,0);return}case"hardness":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{system}=data.item,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,system.hardness,value);system.hardness=Math.max(newValue,0),this.#adjustCreatureShieldData(data.item)}return}case"hp-max":{if(ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)){const{hp}=data.item.system,{value}=data.alteration,newValue=AELikeRuleElement.getNewValue(this.mode,hp.max,value);hp.max=Math.max(Math.trunc(newValue),1),"brokenThreshold"in hp&&(hp.brokenThreshold=Math.floor(hp.max/2)),this.#adjustCreatureShieldData(data.item)}return}case"persistent-damage":{const pdObject=isObject(data.alteration.value)?data.alteration.value:{dc:NaN},dc=Math.trunc(Math.abs(Number(pdObject?.dc)||15));data.alteration.value={...pdObject,dc};const validator=ITEM_ALTERATION_VALIDATORS[this.property];validator.isValid(data)&&(data.item.system.persistent=validator.initialize(data.alteration).value);return}case"material-type":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.material.type=data.alteration.value,data.item.system.material.grade="standard","_source"in data.item&&(data.item.name=game.pf2e.system.generateItemName(data.item)));return}case"rarity":{ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)&&(data.item.system.traits.rarity=data.alteration.value);return}case"pd-recovery-dc":{const validator=ITEM_ALTERATION_VALIDATORS[this.property];if(data.alteration.value=this.resolveValue(data.alteration.value)||15,validator.isValid(data)&&data.item.system.persistent){const{persistent}=data.item.system,newValue=AELikeRuleElement.getNewValue(this.mode,persistent.dc,data.alteration.value);persistent.dc=Math.max(newValue,0)}return}case"frequency-max":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;data.item.system.frequency??={max:1,per:"day"};const frequency=data.item.system.frequency,newValue=AELikeRuleElement.getNewValue(this.mode,frequency.max,data.alteration.value);frequency.max=newValue,frequency.value=Math.clamped(frequency.value??newValue,0,newValue);return}case"frequency-per":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;data.item.system.frequency??={max:1,per:"day"};const newValue=this.#getNewInterval(this.mode,data.item.system.frequency.per,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();data.item.system.frequency.per=newValue;return}case"other-tags":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const otherTags=data.item.system.traits.otherTags,newValue=AELikeRuleElement.getNewValue(this.mode,otherTags,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();this.mode==="add"?otherTags.includes(newValue)||otherTags.push(newValue):["subtract","remove"].includes(this.mode)&&otherTags.splice(otherTags.indexOf(newValue),1);return}case"speed-penalty":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.speedPenalty,data.alteration.value);data.item.system.speedPenalty=Math.min(newValue,0);return}case"strength":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data)||data.item.system.strength===null)return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.strength,data.alteration.value);data.item.system.strength=Math.max(newValue,-2);return}case"traits":{if(!ITEM_ALTERATION_VALIDATORS[this.property].isValid(data))return;const newValue=AELikeRuleElement.getNewValue(this.mode,data.item.system.traits.value,data.alteration.value);if(newValue instanceof DataModelValidationFailure)throw newValue.asError();const traits=data.item.system.traits.value;this.mode==="add"?traits.includes(newValue)||traits.push(newValue):["subtract","remove"].includes(this.mode)&&traits.splice(traits.indexOf(newValue),1);return}}}#adjustCreatureShieldData(item){if("actor"in item&&item.actor?.isOfType("character","npc")&&item.isOfType("shield")){const{heldShield}=item.actor;if(item===heldShield){const shieldData=item.actor.attributes.shield;shieldData.ac=item.system.acBonus,shieldData.hardness=item.system.hardness,shieldData.hp.max=item.system.hp.max,shieldData.brokenThreshold=Math.floor(item.system.hp.max/2)}}}#getNewInterval(mode,current,newValue){const{DataModelValidationFailure}=foundry.data.validation;if(!objectHasKey(CONFIG.PF2E.frequencies,newValue))return new DataModelValidationFailure({invalidValue:current,fallback:!1});if(mode==="override")return newValue;function getDuration(key){return key==="turn"||key==="round"?Duration.fromISO("PT6S"):key==="day"?Duration.fromISO("PT24H"):Duration.fromISO(key)}__name(getDuration,"getDuration"),__name2(getDuration,"getDuration");const newIsLonger=newValue==="round"&¤t==="turn"||newValue==="PT24H"&¤t==="day"||getDuration(newValue)>getDuration(current);return mode==="upgrade"&&newIsLonger||mode==="downgrade"&&!newIsLonger?newValue:current}}class AuraRuleElement extends RuleElementPF2e{static{__name(this,"AuraRuleElement")}static{__name2(this,"AuraRuleElement")}constructor(source,options){super(source,options),this.slug??=this.item.slug??sluggify(this.item.name);for(const effect of this.effects)effect.removeOnExit??=Array.isArray(effect.events)?effect.events.includes("enter"):!1}static defineSchema(){const{fields:fields2}=foundry.data,auraTraitField=new StrictStringField({required:!0,nullable:!1,initial:void 0,choices:{...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits}}),effectSchemaField=new fields2.SchemaField({uuid:new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0}),affects:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:"all",choices:["allies","enemies","all"],label:"PF2E.RuleEditor.Aura.Effects.Affects"}),events:new StrictArrayField(new StrictStringField({required:!0,blank:!1,nullable:!1,initial:void 0,choices:["enter","turn-start","turn-end"]}),{required:!0,nullable:!1,initial:["enter"],label:"PF2E.RuleEditor.Aura.Effects.Events"}),save:new fields2.SchemaField({type:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0,choices:SAVE_TYPES,label:"PF2E.RuleEditor.Aura.Effects.Type"}),dc:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"PF2E.Check.DC.Unspecific"})},{required:!0,nullable:!0,initial:null,label:"PF2E.SavesHeader"}),predicate:new PredicateField({required:!1,nullable:!1}),removeOnExit:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Effects.RemoveOnExit"}),includesSelf:new StrictBooleanField({required:!1,nullable:!1,initial:d=>d.affects!=="enemies",label:"PF2E.RuleEditor.Aura.Effects.IncludesSelf"}),alterations:new StrictArrayField(new fields2.EmbeddedDataField(ItemAlteration))}),xyPairSchema=__name2(({integer})=>({x:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.X"}),y:new StrictNumberField({required:!0,integer,nullable:!1,initial:void 0,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Y"})}),"xyPairSchema"),appearanceSchema={border:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"#000000",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:.75,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!0,initial:()=>({color:"#000000",alpha:.75}),label:"PF2E.RuleEditor.Aura.Appearance.Border"}),highlight:new fields2.SchemaField({color:new DataUnionField([new StrictStringField({required:!0,nullable:!1,choices:["user-color"],initial:void 0}),new fields2.ColorField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:"user-color",label:"PF2E.RuleEditor.Aura.Appearance.Color"}),alpha:new fields2.AlphaField({required:!1,nullable:!1,initial:.25,label:"PF2E.RuleEditor.General.Opacity"})},{required:!1,nullable:!1,initial:()=>({color:"user-color",alpha:.25}),label:"PF2E.RuleEditor.Aura.Appearance.Highlight"}),texture:new fields2.SchemaField({src:new StrictStringField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),alpha:new fields2.AlphaField({required:!0,nullable:!1,initial:1,label:"PF2E.RuleEditor.General.Opacity"}),scale:new StrictNumberField({required:!0,nullable:!1,positive:!0,initial:1,label:"Scale"}),translation:new fields2.SchemaField(xyPairSchema({integer:!0}),{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Translation.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Translation.Hint"}),loop:new StrictBooleanField({required:!1,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Appearance.Loop.Label",hint:"PF2E.RuleEditor.Aura.Appearance.Loop.Hint"}),playbackRate:new StrictNumberField({required:!1,nullable:!1,positive:!0,max:4,initial:1,label:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Label",hint:"PF2E.RuleEditor.Aura.Appearance.PlaybackRate.Hint"})},{required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Appearance.Texture"})};return{...super.defineSchema(),radius:new ResolvableValueField({required:!0,nullable:!1,initial:5,label:"PF2E.RuleEditor.Aura.Basic.Radius"}),level:new ResolvableValueField({required:!1,nullable:!0,initial:null,label:"PF2E.RuleEditor.Aura.Basic.Level.Label",hint:"PF2E.RuleEditor.Aura.Basic.Level.Hint"}),traits:new StrictArrayField(auraTraitField,{required:!0,nullable:!1,label:"PF2E.TraitsLabel"}),effects:new StrictArrayField(effectSchemaField,{required:!0,nullable:!1,label:"PF2E.RuleEditor.Aura.Effects.Label"}),appearance:new fields2.SchemaField(appearanceSchema,{required:!0,nullable:!1,initial:()=>({border:{color:"#000000",alpha:.75},highlight:{color:"user-color",alpha:.25},texture:null}),label:"PF2E.RuleEditor.Aura.Appearance.Label"}),mergeExisting:new StrictBooleanField({required:!0,nullable:!1,initial:!0,label:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Label",hint:"PF2E.RuleEditor.Aura.Basic.MergeExisting.Hint"})}}afterPrepareData(){if(!this.test())return;const radius=Math.clamped(Math.ceil(Number(this.resolveValue(this.radius))/5)*5,5,240);if(Number.isInteger(radius)&&radius>0){const level=this.resolveValue(this.level,null),data={slug:this.slug,radius,level:typeof level=="number"?Math.trunc(level):this.item.isOfType("effect")?this.item.level:null,effects:this.#processEffects(),traits:uniq(this.traits.filter(t=>t!=="aura")).sort(),appearance:this.#processAppearanceData()};for(const effect of data.effects){const indexEntry=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"')}const existing=this.actor.auras.get(this.slug);if(existing&&this.mergeExisting){existing.radius=data.radius,existing.traits=uniq([...existing.traits,...data.traits]).sort(),existing.appearance=data.appearance;for(const effect of data.effects){const existingIndex=existing.effects.findIndex(e=>e.uuid===effect.uuid);existingIndex!==-1?existing.effects.splice(existingIndex,1,effect):existing.effects.push(effect)}}else this.actor.auras.set(this.slug,data)}}#processEffects(){return this.effects.map(e=>({...e,uuid:this.resolveInjectedProperties(e.uuid),save:null}))}#processAppearanceData(){const appearance=foundry.utils.deepClone(this.appearance),{border,highlight,texture}=appearance,textureSrc=(()=>{if(!texture)return null;const maybeTextureSrc=this.resolveInjectedProperties(texture.src);return isImageOrVideoPath(maybeTextureSrc)?maybeTextureSrc:"icons/svg/hazard.svg"})();return border&&(border.color=border.color==="user-color"?userColorForActor(this.actor):border.color),highlight.color=highlight.color==="user-color"?userColorForActor(this.actor):highlight.color,{border:border&&{color:Number(Color.fromString(border.color)),alpha:border.alpha},highlight:{color:Number(Color.fromString(highlight.color)),alpha:highlight.alpha},texture:texture?.alpha&&textureSrc?{...texture,src:textureSrc}:null}}}class BaseSpeedRuleElement extends RuleElementPF2e{static{__name(this,"BaseSpeedRuleElement")}static{__name2(this,"BaseSpeedRuleElement")}static validActorTypes=["character","familiar","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:void 0}),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})}}constructor(data,options){super(data,options),this.selector=this.selector?.trim().replace(/-speed$/,""),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("A value must be a number, string, or bracketed value")}beforePrepareData(){if(this.ignored)return;const speedType=this.resolveInjectedProperties(this.selector);if(!tupleHasValue(MOVEMENT_TYPES,speedType))return this.failValidation("Unrecognized or missing selector");const speed=this.#createMovementType(speedType);(this.actor.synthetics.movementTypes[speedType]??=[]).push(speed)}#createMovementType(type){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=type!=="land"&&typeof this.value=="string"&&/attributes\.speed\.(?:value|total)/.test(this.value);return value>0?{type,value,source:this.item.name,derivedFromLand}:null}}}const ALLIANCES=new Set(["party","opposition",null]),SAVING_THROW_DEFAULT_ATTRIBUTES={fortitude:"con",reflex:"dex",will:"wis"},SIZE_TO_REACH={tiny:0,sm:5,med:5,lg:5,huge:10,grg:15},SENSES_WITH_MANDATORY_ACUITIES={darkvision:"precise",heatsight:"precise",greaterDarkvision:"precise",lowLightVision:"precise",seeInvisibility:"precise"},LANGUAGES=["adlet","akitonian","aklo","alghollthu","amurrun","anadi","ancient-osiriani","androffan","anugobu","arboreal","arcadian","azlanti","boggard","calda","caligni","chthonian","common","cyclops","daemonic","destrachan","diabolic","draconic","drooni","dwarven","dziriak","ekujae","elder-thing","elven","empyrean","erutaki","fey","formian","garundi","girtablilu","gnomish","goblin","goloma","grioth","grippli","halfling","hallit","hwan","iblydan","ikeshti","immolis","iruxi","jistkan","jotun","jyoti","kaava","kashrishi","kelish","kholo","kibwani","kitsune","kovintal","lirgeni","mahwek","migo","minaten","minkaian","muan","munavri","mwangi","mzunu","nagaji","necril","ocotan","okaiyan","orcish","orvian","osiriani","petran","protean","pyric","rasu","ratajin","razatlani","requian","russian","sakvroth","samsaran","sasquatch","senzar","shadowtongue","shae","shisk","shoanti","shobhad","shoony","shory","skald","sphinx","strix","sussuran","taldane","talican","tekritanin","tengu","thalassic","thassilonian","tien","utopian","vanara","varisian","varki","vishkanyan","vudrani","wildsong","wyrwood","xanmba","yithian","ysoki"];class CreatureSensePF2e{static{__name(this,"CreatureSensePF2e")}static{__name2(this,"CreatureSensePF2e")}type;acuity;value;source;get range(){return Number(this.value)||1/0}constructor(data){this.type=data.type,this.acuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,this.type)?SENSES_WITH_MANDATORY_ACUITIES[this.type]:data.acuity??"precise",this.value=data.value??"",this.source=data.source||void 0}get label(){const buildLabel=__name2((type,acuity,range22)=>{const senses2=CONFIG.PF2E.senses,sense=game.i18n.localize(senses2[type]??"")||type,acuityLabel=acuity?game.i18n.localize(CONFIG.PF2E.senseAcuity[acuity]):null;return acuity&&range22?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuityAndRange",{sense,acuity:acuityLabel,range:range22}):acuity?game.i18n.format("PF2E.Actor.Creature.Sense.WithAcuity",{sense,acuity:acuityLabel}):sense},"buildLabel"),range2=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,range2);default:return buildLabel(this.type,this.acuity,range2)}}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)}}const SENSE_ACUITIES=["precise","imprecise","vague"],SENSE_TYPES=new Set(["darkvision","echolocation","greaterDarkvision","heatsight","lifesense","lowLightVision","motionsense","scent","seeInvisibility","spiritsense","thoughtsense","tremorsense","wavesense"]),CONDITION_SLUGS=new Set(["blinded","broken","clumsy","concealed","confused","controlled","dazzled","deafened","doomed","drained","dying","encumbered","enfeebled","fascinated","fatigued","fleeing","friendly","frightened","grabbed","helpful","hidden","hostile","immobilized","indifferent","invisible","malevolence","observed","off-guard","paralyzed","persistent-damage","petrified","prone","quickened","restrained","sickened","slowed","stunned","stupefied","unconscious","undetected","unfriendly","unnoticed","wounded"]);class IWR{static{__name(this,"IWR")}static{__name2(this,"IWR")}type;exceptions;definition;source;#customLabel;constructor(data){this.type=data.type,this.exceptions=foundry.utils.deepClone(data.exceptions??[]),this.definition=data.definition??null,this.source=data.source??null,this.#customLabel=this.type==="custom"?data.customLabel??null:null}get applicationLabel(){const type=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,...exceptions,value:""}).replace(/\s+/g," ").trim()}get typeLabel(){return game.i18n.localize(this.#customLabel??this.typeLabels[this.type])}describe(iwrType){if(isObject(iwrType))return iwrType.definition;switch(iwrType){case"air":case"earth":case"metal":case"radiation":case"visual":case"water":case"wood":return[`item:trait:${iwrType}`];case"all-damage":return["damage"];case"area-damage":return["area-damage"];case"arrow-vulnerability":return["item:group:bow"];case"auditory":return["item:trait:auditory"];case"axe-vulnerability":return["item:group:axe"];case"custom":return this.definition??[];case"damage-from-spells":return["damage","item:type:spell","impulse"];case"disease":return["item:trait:disease"];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[{or:["item:rune:property:astral","item:rune:property:ghost-touch","item:rune:property:greater-astral"]}];case"holy":return[{or:["origin:action:trait:holy","item:trait:holy"]}];case"magical":return[{or:["item:magical","origin:action:trait:magical",...MAGIC_TRADITIONS.map(t=>`origin:action:trait:${t}`)]}];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","damage:type:spirit",{and:["item:type:condition",{or:["item:slug:doomed","item:slug:drained","item:slug:fatigued","item:slug:paralyzed","item:slug:sickened","item:slug:unconscious"]}]}]}];case"persistent-damage":return[{or:["damage:category:persistent",{and:["item:type:condition","item:slug:persistent-damage"]}]}];case"precision":case"splash-damage":return[`damage:component:${iwrType==="splash-damage"?"splash":"precision"}`];case"spells":return["damage",{or:["item:type:spell","item:from-spell","impulse"]}];case"unarmed-attacks":return["item:category:unarmed"];case"unholy":return[{or:["origin:action:trait:unholy","item:trait:unholy"]}];default:{if(iwrType in CONFIG.PF2E.damageTypes)return[`damage:type:${iwrType}`];if(setHasElement(CONDITION_SLUGS,iwrType))return["item:type:condition",`item:slug:${iwrType}`];if(objectHasKey(CONFIG.PF2E.materialDamageEffects,iwrType))switch(iwrType){case"adamantine":return[{or:["damage:material:adamantine","damage:material:keep-stone"]}];case"cold-iron":return[{or:["damage:material:cold-iron","damage:material:sovereign-steel"]}];case"duskwood":return[{or:["damage:material:duskwood",{and:["self:mode:undead","damage:material:peachwood"]}]}];case"silver":return[{or:["damage:material:silver","damage:material:dawnsilver"]}];default:return[`damage:material:${iwrType}`]}return[`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:foundry.utils.deepClone(this.exceptions),source:this.source,label:this.label}}createFormatData({list,prefix}){return list.slice(0,4).map((exception,index)=>{const label=typeof exception=="string"?this.typeLabels[exception]:exception.label;return{[`${prefix}${index+1}`]:game.i18n.localize(label)}}).reduce((accum,obj)=>({...accum,...obj}),{})}test(statements){return this.predicate.test(statements)}}class Immunity extends IWR{static{__name(this,"Immunity")}static{__name2(this,"Immunity")}typeLabels=CONFIG.PF2E.immunityTypes;get label(){return this.applicationLabel}}class Weakness extends IWR{static{__name(this,"Weakness")}static{__name2(this,"Weakness")}typeLabels=CONFIG.PF2E.weaknessTypes;value;constructor(data){super(data),this.value=data.value}get label(){const type=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,value:this.value,...exceptions})}toObject(){return{...super.toObject(),value:this.value}}}class Resistance extends IWR{static{__name(this,"Resistance")}static{__name2(this,"Resistance")}typeLabels=CONFIG.PF2E.resistanceTypes;value;doubleVs;constructor(data){super(data),this.value=data.value,this.doubleVs=foundry.utils.deepClone(data.doubleVs??[])}get label(){const type=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,value:this.value,...exceptions,...doubleVs})}get applicationLabel(){const type=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,value:"",...exceptions,...doubleVs}).replace(/\s+/g," ").trim()}toObject(){return{...super.toObject(),value:this.value,doubleVs:foundry.utils.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}}const NON_DAMAGE_WEAKNESSES=new Set(["air","earth","ghost-touch","holy","metal","plant","radiation","salt-water","salt","spells","unholy","water","wood"]);class AttackTraitHelpers{static{__name(this,"AttackTraitHelpers")}static{__name2(this,"AttackTraitHelpers")}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({item}){const{actor}=item;if(!actor)throw ErrorPF2e("The weapon must be embedded");return item.system.traits.value.flatMap(trait=>{const unannotatedTrait=this.getUnannotatedTrait(trait);switch(unannotatedTrait){case"volley":{if(!item.range?.increment)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("sweep-bonus")});case"backswing":return new ModifierPF2e({slug:unannotatedTrait,label:this.getLabel(trait),modifier:1,type:"circumstance",predicate:new PredicatePF2e("backswing-bonus")});default:return[]}})}}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","nonlethal-attacks","paralyzed","poison","sickened","spirit","unconscious"];for(const immunityType of constructImmunities)immunities.some(i=>i.type===immunityType)||immunities.push(new Immunity({type:immunityType,source:game.i18n.localize("PF2E.TraitConstruct")}))}traits.has("mindless")&&!immunities.some(i=>i.type==="mental")&&immunities.push(new Immunity({type:"mental",source:game.i18n.localize("PF2E.TraitMindless")}))}__name(setImmunitiesFromTraits,"setImmunitiesFromTraits"),__name2(setImmunitiesFromTraits,"setImmunitiesFromTraits");function imposeEncumberedCondition(actor){if(game.pf2e.settings.encumbrance&&actor.inventory.bulk.isEncumbered&&actor.conditions.bySlug("encumbered").length===0){const source=game.pf2e.ConditionManager.getCondition("encumbered").toObject(),encumbered=new ConditionPF2e(foundry.utils.mergeObject(source,{_id:"xxxENCUMBEREDxxx"}),{parent:actor});actor.conditions.set(encumbered.id,encumbered),encumbered.prepareSiblingData(),encumbered.prepareActorData();for(const rule of encumbered.prepareRuleElements())rule.onApplyActiveEffects?.(),rule.beforePrepareData?.()}}__name(imposeEncumberedCondition,"imposeEncumberedCondition"),__name2(imposeEncumberedCondition,"imposeEncumberedCondition");class WeaponTraitToggles{static{__name(this,"WeaponTraitToggles")}static{__name2(this,"WeaponTraitToggles")}#weapon;constructor(weapon){this.#weapon=weapon}get modular(){const options=this.#resolveOptions("modular"),sourceSelection=this.#weapon._source.system.traits.toggles?.modular?.selection,selection=tupleHasValue(options,sourceSelection)?sourceSelection:options.includes(this.#weapon.system.damage.damageType)?this.#weapon.system.damage.damageType:null;return{options,selection}}get versatile(){const options=this.#resolveOptions("versatile"),sourceSelection=this.#weapon._source.system.traits.toggles?.versatile?.selection??null,selection=tupleHasValue(options,sourceSelection)?sourceSelection:null;return{options,selection}}#resolveOptions(toggle){const types=this.#weapon.system.traits.value.filter(t=>t.startsWith(toggle)).flatMap(trait=>{if(trait==="modular")return["bludgeoning","piercing","slashing"];const damageType=/^versatile-(\w+)$/.exec(trait)?.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=>this.#weapon.system.damage.damageType!==t)}}async function toggleWeaponTrait({weapon,trait,selection}){if(weapon.system.traits.toggles[trait].selection===selection)return!1;const item=weapon.actor?.items.get(weapon.id);return item?.isOfType("weapon")&&item===weapon?await item.update({[`system.traits.toggles.${trait}.selection`]:selection}):item?.isOfType("weapon")&&weapon.altUsageType==="melee"?item.update({[`system.meleeUsage.traitToggles.${trait}`]:selection}):trait==="versatile"&&item?.isOfType("shield")?item.update({"system.traits.integrated.versatile.selection":selection}):await item?.rules.find(r=>r.key==="Strike"&&!r.ignored&&r.slug===weapon.slug)?.toggleTrait({trait,selection}),!0}__name(toggleWeaponTrait,"toggleWeaponTrait"),__name2(toggleWeaponTrait,"toggleWeaponTrait");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]]),simpleDCs=new Map([["untrained",10],["trained",15],["expert",20],["master",30],["legendary",40]]),simpleDCsWithoutLevel=new Map([["untrained",10],["trained",15],["expert",20],["master",25],["legendary",30]]);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,{pwol,rarity="common"}={}){pwol??=game.pf2e.settings.variants.pwol.enabled;const dc=dcByLevel.get(level)??14;return adjustDCByRarity(pwol?dc-Math.max(level,0):dc,rarity)}__name(calculateDC,"calculateDC"),__name2(calculateDC,"calculateDC");function calculateSimpleDC(rank,{pwol=!1}={}){return pwol?simpleDCsWithoutLevel.get(rank)??10:simpleDCs.get(rank)??10}__name(calculateSimpleDC,"calculateSimpleDC"),__name2(calculateSimpleDC,"calculateSimpleDC");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");function isRelevantEvent(event2){return!!event2&&"ctrlKey"in event2&&"metaKey"in event2&&"shiftKey"in event2}__name(isRelevantEvent,"isRelevantEvent"),__name2(isRelevantEvent,"isRelevantEvent");function eventToRollParams(event2,rollType){const key=rollType.type==="check"?"showCheckDialogs":"showDamageDialogs",skipDefault=!game.user.settings[key];if(!isRelevantEvent(event2))return{skipDialog:skipDefault};const params={skipDialog:event2.shiftKey?!skipDefault:skipDefault};return(event2.ctrlKey||event2.metaKey)&&(params.rollMode=game.user.isGM?"gmroll":"blindroll"),params}__name(eventToRollParams,"eventToRollParams"),__name2(eventToRollParams,"eventToRollParams");function eventToRollMode(event2){return!isRelevantEvent(event2)||!event2.ctrlKey||!event2.metaKey?"roll":game.user.isGM?"gmroll":"blindroll"}__name(eventToRollMode,"eventToRollMode"),__name2(eventToRollMode,"eventToRollMode");function getSelectedOrOwnActors(types=[]){return uniq(game.user.getActiveTokens().filter(t=>types.length===0||t.actor?.isOfType(...types)).flatMap(t=>t.actor??[]))}__name(getSelectedOrOwnActors,"getSelectedOrOwnActors"),__name2(getSelectedOrOwnActors,"getSelectedOrOwnActors");const inlineSelector=["action","check","effect-area"].map(keyword=>`[data-pf2-${keyword}]`).join(","),InlineRollLinks={injectRepostElement:(links,foundryDoc)=>{for(const link of links){(!foundryDoc||foundryDoc.isOwner)&&link.classList.add("with-repost");const repostButtons=htmlQueryAll(link,"i[data-pf2-repost]");if(repostButtons.length>0){if(foundryDoc&&!foundryDoc.isOwner){for(const button of repostButtons)button.remove();link.classList.remove("with-repost")}continue}if(foundryDoc&&!foundryDoc.isOwner)continue;const newButton=document.createElement("i"),icon=link.parentElement?.dataset?.pf2Checkgroup!==void 0?"fa-comment-alt-dots":"fa-comment-alt";newButton.classList.add("fa-solid",icon),newButton.dataset.pf2Repost="",newButton.title=game.i18n.localize("PF2E.Repost"),link.appendChild(newButton),newButton.addEventListener("click",event2=>{event2.stopPropagation();const target=event2.target;if(!(target instanceof HTMLElement))return;const parent=target?.parentElement;if(!parent)return;const document2=resolveDocument(target,foundryDoc);InlineRollLinks.repostAction(parent,document2)})}},listen:(html,foundryDoc=null)=>{foundryDoc??=resolveDocument(html,foundryDoc);const links=htmlQueryAll(html,inlineSelector).filter(l=>["A","SPAN"].includes(l.nodeName));InlineRollLinks.injectRepostElement(links,foundryDoc),InlineRollLinks.flavorDamageRolls(html,foundryDoc instanceof ActorPF2e?foundryDoc:null);for(const link of links.filter(l=>l.dataset.pf2Action)){const{pf2Action,pf2Glyph,pf2Variant,pf2Dc,pf2ShowDc,pf2Skill}=link.dataset;link.addEventListener("click",event2=>{const action2=game.pf2e.actions[pf2Action?sluggify(pf2Action,{camel:"dromedary"}):""],visibility=pf2ShowDc??"all";pf2Action&&action2?action2({event:event2,glyph:pf2Glyph,variant:pf2Variant,difficultyClass:pf2Dc?{scope:"check",value:Number(pf2Dc)||0,visibility}:void 0,skill:pf2Skill}):console.warn(`PF2e System | Skip executing unknown action '${pf2Action}'`)})}for(const link of links.filter(l=>l.dataset.pf2Check&&!l.dataset.invalid)){const{pf2Check,pf2Dc,pf2Traits,pf2Label,pf2Defense,pf2Adjustment,pf2Roller,pf2RollOptions}=link.dataset;if(!pf2Check)return;link.addEventListener("click",async event2=>{const parent=resolveActor(foundryDoc,link),actors=(()=>{switch(pf2Roller){case"self":return parent?.canUserModify(game.user,"update")?[parent]:[];case"party":return parent?.isOfType("party")?[parent]:compact([game.actors.party])}const actors2=getSelectedOrOwnActors(),isSave=tupleHasValue(SAVE_TYPES,pf2Check);return parent?.isOfType("party")||actors2.length===0&&parent&&!isSave?[parent]:actors2})();if(actors.length===0){ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0});return}const extraRollOptions=[...pf2Traits?.split(",").map(o=>o.trim())??[],...pf2RollOptions?.split(",").map(o=>o.trim())??[]],eventRollParams=eventToRollParams(event2,{type:"check"});switch(pf2Check){case"flat":{for(const actor of actors){const flatCheck=new Statistic(actor,{label:"",slug:"flat",modifiers:[],check:{type:"flat-check"}}),dc=Number.isInteger(Number(pf2Dc))?{label:pf2Label,value:Number(pf2Dc)}:null;flatCheck.roll({...eventRollParams,extraRollOptions,dc})}break}default:{const isSavingThrow=tupleHasValue(SAVE_TYPES,pf2Check),traits=isSavingThrow?[]:extraRollOptions.filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const actor of actors){const statistic=(()=>{if(pf2Check in CONFIG.PF2E.magicTraditions){const bestSpellcasting=actor.spellcasting.filter(c=>c.tradition===pf2Check).flatMap(s=>s.statistic??[]).sort((a,b)=>b.check.mod-a.check.mod).shift()??null;if(bestSpellcasting)return bestSpellcasting}return actor.getStatistic(pf2Check)})();if(!statistic){console.warn(ErrorPF2e(`Skip rolling unknown statistic ${pf2Check}`).message);continue}const targetActor=pf2Defense?game.user.targets.first()?.actor:null,dcValue=(()=>{const adjustment=Number(pf2Adjustment)||0;return pf2Dc==="@self.level"?calculateDC(actor.level)+adjustment:Number(pf2Dc??"NaN")+adjustment})(),dc=(()=>{if(Number.isInteger(dcValue))return{label:pf2Label,value:dcValue};if(pf2Defense){const defenseStat=targetActor?.getStatistic(pf2Defense);return defenseStat?{statistic:defenseStat.dc,scope:"check",value:defenseStat.dc.value}:null}return null})(),item=(()=>{const itemFromDoc=foundryDoc instanceof ItemPF2e?foundryDoc:foundryDoc instanceof ChatMessagePF2e?foundryDoc.item:null;return itemFromDoc?.isOfType("action","feat","campaignFeature")||isSavingThrow&&!itemFromDoc?.isOfType("weapon")?itemFromDoc:null})(),args={...eventRollParams,extraRollOptions,origin:isSavingThrow&&parent instanceof ActorPF2e?parent:null,dc,target:!isSavingThrow&&dc?.statistic?targetActor:null,item,traits};if(!!(item?.isOfType("action","feat")&&item.actionCost)&&pf2Defense){const subtitleLocKey=pf2Check in CONFIG.PF2E.magicTraditions?"PF2E.ActionsCheck.spell":statistic.check.type==="attack-roll"?"PF2E.ActionsCheck.x-attack-roll":"PF2E.ActionsCheck.x";args.label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:getActionGlyph(item.actionCost),subtitle:game.i18n.format(subtitleLocKey,{type:statistic.label}),title:item.name})}statistic.roll(args)}}}})}const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"};for(const link of links.filter(l=>l.hasAttribute("data-pf2-effect-area"))){const{pf2EffectArea,pf2Distance,pf2TemplateData,pf2Traits,pf2Width}=link.dataset;link.addEventListener("click",()=>{if(!canvas.ready)return;if(typeof pf2EffectArea!="string"){console.warn("PF2e System | Could not create template'");return}const templateData=JSON.parse(pf2TemplateData??"{}");switch(templateData.distance||=Number(pf2Distance),templateData.fillColor||=game.user.color,templateData.t=templateConversion[pf2EffectArea],templateData.t){case"ray":templateData.width=Number(pf2Width)||CONFIG.MeasuredTemplate.defaults.width*(canvas.dimensions?.distance??1);break;case"cone":templateData.angle=CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":{const distance=templateData.distance??0;templateData.distance=Math.hypot(distance,distance),templateData.width=distance,templateData.direction=45;break}}const flags={pf2e:{}};objectHasKey(CONFIG.PF2E.areaTypes,pf2EffectArea)&&objectHasKey(CONFIG.PF2E.areaSizes,templateData.distance)&&(flags.pf2e.areaType=pf2EffectArea);const messageId=foundryDoc instanceof ChatMessagePF2e?foundryDoc.id:htmlClosest(html,"[data-message-id]")?.dataset.messageId??null;messageId&&(flags.pf2e.messageId=messageId);const actor=resolveActor(foundryDoc,link);if(actor||pf2Traits){const origin={};actor&&(origin.actor=actor.uuid),pf2Traits&&(origin.traits=pf2Traits.split(",")),flags.pf2e.origin=origin}isEmpty(flags.pf2e)||(templateData.flags=flags),canvas.templates.createPreview(templateData)})}},makeRepostHtml:(target,defaultVisibility)=>{const flavor=target.attributes.getNamedItem("data-pf2-repost-flavor")?.value??"";return`<span data-visibility="${target.attributes.getNamedItem("data-pf2-show-dc")?.value??defaultVisibility}">${flavor}</span> ${target.outerHTML}`.trim()},repostAction:(target,foundryDoc=null)=>{if(!["pf2Action","pf2Check","pf2EffectArea"].some(d=>d in target.dataset))return;const actor=resolveActor(foundryDoc,target),defaultVisibility=(actor??foundryDoc)?.hasPlayerOwner?"all":"gm",content=(()=>target.parentElement?.dataset?.pf2Checkgroup!==void 0?`<div data-pf2-checkgroup>${htmlQueryAll(target.parentElement,inlineSelector).map(target2=>InlineRollLinks.makeRepostHtml(target2,defaultVisibility)).join("<br>")}</div>`:InlineRollLinks.makeRepostHtml(target,defaultVisibility))(),speaker=actor?ChatMessagePF2e.getSpeaker({actor,token:actor.getActiveTokens(!1,!0).shift()}):ChatMessagePF2e.getSpeaker(),message=game.messages.get(htmlClosest(target,"[data-message-id]")?.dataset.messageId??""),flags=foundryDoc instanceof JournalEntry?{pf2e:{journalEntry:foundryDoc.uuid}}:message?.flags.pf2e.origin?{pf2e:{origin:foundry.utils.deepClone(message.flags.pf2e.origin)}}:{};ChatMessagePF2e.create({speaker,content,flags})},flavorDamageRolls(html,actor=null){for(const rollLink of htmlQueryAll(html,"a.inline-roll[data-damage-roll]")){const itemId=htmlClosest(rollLink,"[data-item-id]")?.dataset.itemId,item=actor?.items.get(itemId??"");item&&(rollLink.dataset.flavor||=item.name)}}};function resolveDocument(html,foundryDoc){if(foundryDoc)return foundryDoc;const document2=(ui.windows[Number(html.closest(".app.sheet")?.dataset.appid)]??null)?.document;return document2 instanceof ActorPF2e||document2 instanceof JournalEntry?document2:null}__name(resolveDocument,"resolveDocument"),__name2(resolveDocument,"resolveDocument");function resolveActor(foundryDoc,anchor){if(foundryDoc instanceof ActorPF2e)return foundryDoc;if(foundryDoc instanceof ItemPF2e||foundryDoc instanceof ChatMessagePF2e)return foundryDoc.actor;const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?itemByUUID.actor:null}__name(resolveActor,"resolveActor"),__name2(resolveActor,"resolveActor");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(){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});try{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 token.object?._animation;for(const aura of tokens.flatMap(t=>Array.from(t.auras.values())))await aura.notifyActors();const sceneActors=new Set(tokens.flatMap(t=>t.actor?.primaryUpdater===game.user?t.actor:[]));for(const actor of sceneActors)actor.checkAreaEffects()}finally{lock.release()}},100);class ScenePF2e extends Scene{static{__name(this,"ScenePF2e")}static{__name2(this,"ScenePF2e")}get rulesBasedVision(){return this.tokenVision?this.flags.pf2e.rulesBasedVision??game.pf2e.settings.rbv:!1}get hearingRange(){return this.flags.pf2e.hearingRange}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=game.user.isGM&&game.users.filter(u=>u.active).length===1;return this.active&&!soleUserIsGM||this.isView&&soleUserIsGM}prepareData(){super.prepareData(),Promise.resolve().then(()=>{this.checkAuras()})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=foundry.utils.mergeObject({hearingRange:null,rulesBasedVision:null,syncDarkness:"default"},this.flags.pf2e??{}),this.rulesBasedVision&&(this.globalLight=!0,this.globalLightThreshold=1-(LightLevels.DARKNESS+.001))}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const flagChanges=changed.flags?.pf2e??{};if(this.isView&&["rulesBasedVision","hearingRange"].some(k=>flagChanges[k]!==void 0)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0}),changed.active!==!1&&canvas.scene===this)for(const token of canvas.tokens.placeables)token.auras.reset()}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId),documents.some(d=>d instanceof TokenDocumentPF2e&&!(d._source.light.dim||d._source.light.bright)&&d.actor?.synthetics.tokenOverrides.light)&&canvas.perception.update({initializeLighting:!0,initializeVision:!0})}}Object.defineProperty(ScenePF2e.prototype,"checkAuras",{configurable:!1,enumerable:!1,writable:!1,value:checkAuras});class AmbientLightDocumentPF2e extends AmbientLightDocument{static{__name(this,"AmbientLightDocumentPF2e")}static{__name2(this,"AmbientLightDocumentPF2e")}get isDarkness(){return this.object?.source.isDarkness??!1}}class MeasuredTemplateDocumentPF2e extends MeasuredTemplateDocument{static{__name(this,"MeasuredTemplateDocumentPF2e")}static{__name2(this,"MeasuredTemplateDocumentPF2e")}get actor(){const uuid=this.flags.pf2e?.origin?.actor;if(!uuid)return null;const document2=fromUuidSync(uuid);return document2 instanceof ActorPF2e?document2:this.item?.actor??null}get item(){const origin=this.flags.pf2e?.origin,uuid=origin?.uuid;if(!uuid)return null;const item=fromUuidSync(uuid);if(!(item instanceof ItemPF2e))return null;if(item?.isOfType("spell")){const overlayIds=origin?.variant?.overlays,castRank=origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel:castRank})??item}return item}get message(){return game.messages.get(this.flags.pf2e?.messageId??"")??null}get areaType(){return this.flags.pf2e.areaType}_initializeSource(data,options){const initialized=super._initializeSource(data,options),areaType=initialized.t==="cone"?"cone":initialized.t==="ray"?"line":null;return initialized.flags.pf2e=foundry.utils.mergeObject({areaType},initialized.flags.pf2e??{}),initialized}_onCreate(data,options,userId){super._onCreate(data,options,userId),toggleClearTemplatesButton(this.message)}_onDelete(options,userId){super._onDelete(options,userId),toggleClearTemplatesButton(this.message)}}class TileDocumentPF2e extends TileDocument{static{__name(this,"TileDocumentPF2e")}static{__name2(this,"TileDocumentPF2e")}}class TokenConfigPF2e extends TokenConfig{static{__name(this,"TokenConfigPF2e")}static{__name2(this,"TokenConfigPF2e")}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/scene/token/sheet.hbs",sheetConfig:!1}}get dimensionsFromActorSize(){const actorSize=this.actor?.size??"med";return{tiny:.5,sm:1,med:1,lg:2,huge:3,grg:4}[actorSize]}async getData(options){return{...await super.getData(options),sizeLinkable:!!this.actor&&SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToSizeTitle:this.token.flags.pf2e.linkToActorSize?"Unlink":"Link",autoscaleTitle:this.token.flags.pf2e.autoscale?"Unlink":"Link"}}_getFilePickerOptions(event2){return{...super._getFilePickerOptions(event2),redirectToRoot:this.actor?[ActorPF2e.getDefaultArtwork(this.actor.toObject()).texture.src]:[]}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.#disableVisionInputs(html),this.token.flags.pf2e.autoscale&&this.#disableScale(html),htmlQuery(html,"a[data-action=toggle-link-to-size]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.linkToActorSize":!this.token.flags.pf2e.linkToActorSize}),this.#reestablishPrototype(),await this.render()}),htmlQuery(html,"a[data-action=toggle-autoscale]")?.addEventListener("click",async()=>{await this.token.update({"flags.pf2e.autoscale":!this.token.flags.pf2e.autoscale}),this.#reestablishPrototype(),await this.render()})}#disableScale(html){if(!game.settings.get("pf2e","tokens.autoscale"))return;const scale=html.querySelector(".form-group.scale");if(!scale)throw ErrorPF2e("Scale form group missing");scale.classList.add("children-disabled");const constrainedScale=String(this.actor?.size==="sm"?.8:1),rangeInput=scale.querySelector("input[type=range]");if(rangeInput){rangeInput.disabled=!0,rangeInput.value=constrainedScale;const rangeDisplayValue=scale.querySelector(".range-value");rangeDisplayValue&&(rangeDisplayValue.innerHTML=constrainedScale)}}#reestablishPrototype(){if(this.isPrototype&&this.actor){const realPrototype=this.actor.prototypeToken;this.object=this.token=realPrototype}}#disableVisionInputs(html){if(!(["character","familiar"].includes(this.actor?.type??"")&&(this.token.rulesBasedVision||this.isPrototype&&game.pf2e.settings.rbv)))return;const sightInputNames=["angle","brightness","range","saturation","visionMode"].map(n=>`sight.${n}`),sightInputs=Array.from(html.querySelectorAll(sightInputNames.map(n=>`[name="${n}"]`).join(", "))),sightEnabledInput=html.querySelector('input[name="sight.enabled"]');if(!sightEnabledInput)throw ErrorPF2e("sight.enabled input not found");sightEnabledInput.addEventListener("change",()=>{for(const input of sightInputs)if(input.disabled=!sightEnabledInput.checked,input.type==="range")sightEnabledInput.checked?input.closest(".form-group")?.classList.remove("children-disabled"):input.closest(".form-group")?.classList.add("children-disabled");else if(input.name==="sight.color"){const colorInput=input.parentElement?.querySelector("input[type=color]");colorInput&&(colorInput.disabled=!sightEnabledInput.checked)}});for(const input of sightInputs)input.disabled=!0,input.type==="range"&&input.closest(".form-group")?.classList.add("children-disabled");html.querySelector("a.item[data-tab=detection]")?.classList.add("disabled");const managedBy=document.createElement("a");managedBy.className="managed-by-rbv",managedBy.append(fontAwesomeIcon("robot")),managedBy.title=game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy").replace(/<\/?rbv>/g,"");for(const sightInput of sightInputs){const anchor=managedBy.cloneNode(!0);anchor.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),sightInput.closest(".form-group")?.querySelector("label")?.append(anchor)}}_getSubmitData(updateData={}){const changes=updateData??{};return this.form.querySelector("input[name=scale]")?.disabled&&(changes.scale=Math.abs(this.token._source.texture.scaleX)),super._getSubmitData(changes)}async _updateObject(event2,formData){if(formData["flags.pf2e.linkToActorSize"]===!0)if(this.actor?.isOfType("vehicle")){const{dimensions}=this.actor,width=Math.max(Math.round(dimensions.width/5),1),length=Math.max(Math.round(dimensions.length/5),1);formData.width=width,formData.height=length}else formData.width=formData.height=this.dimensionsFromActorSize;return super._updateObject(event2,formData)}}class AmbientLightPF2e extends AmbientLight{static{__name(this,"AmbientLightPF2e")}static{__name2(this,"AmbientLightPF2e")}get isDarkness(){return this.source.isDarkness}}class EffectsCanvasGroupPF2e extends EffectsCanvasGroup{static{__name(this,"EffectsCanvasGroupPF2e")}static{__name2(this,"EffectsCanvasGroupPF2e")}get rulesBasedVision(){return game.pf2e.settings.rbv&&canvas.ready&&!!canvas.scene?.tokenVision}}class LightingLayerPF2e extends LightingLayer{static{__name(this,"LightingLayerPF2e")}static{__name2(this,"LightingLayerPF2e")}get lightingLevel(){return 1-canvas.darknessLevel}}class TemplateLayerPF2e extends TemplateLayer{static{__name(this,"TemplateLayerPF2e")}static{__name2(this,"TemplateLayerPF2e")}#previewListeners=null;#gridPrecision=2;get gridPrecision(){return this.#gridPrecision}snapFor(areaType){areaType&&canvas.grid.type===CONST.GRID_TYPES.SQUARE?this.#gridPrecision=areaType==="burst"?1:2:this.#gridPrecision=2}async createPreview(createData){const initialLayer=canvas.activeLayer,preview=await this._createPreview({...createData,...canvas.mousePosition},{renderSheet:!1});return this.#activatePreviewListeners(preview,initialLayer),preview}_onDragLeftMove(event2){if(!canvas.scene||!canvas.dimensions||canvas.grid.type===CONST.GRID_TYPES.GRIDLESS)return super._onDragLeftMove(event2);const{destination,layerDragState,preview:template,origin}=event2.interactionData,dragState=layerDragState??0;if(!template||template.destroyed||dragState===0)return;this.snapFor(template.areaType);const{dimensions}=canvas,{x,y}=canvas.grid.getSnappedPosition(destination.x,destination.y,this.gridPrecision);destination.x=x,destination.y=y;const ray=new Ray(origin,destination),ratio=dimensions.size/dimensions.distance,{document:document2}=template;if(["cone","circle"].includes(document2.t)){const snapAngle=Math.PI/(canvas.scene.hasHexGrid?6:4);document2.direction=Math.toDegrees(Math.floor((ray.angle+Math.PI*.125)/snapAngle)*snapAngle)}else document2.direction=Math.toDegrees(ray.angle);const increment=Math.max(ray.distance/ratio,dimensions.distance);document2.distance=Math.ceil(increment/dimensions.distance)*dimensions.distance,template.refresh(),event2.interactionData.layerDragState=2}_onMouseWheel(event2){const template=this.hover;if(!template||!canvas.scene||canvas.grid.type===CONST.GRID_TYPES.GRIDLESS)return super._onMouseWheel(event2);const shapeType=template.document.t,distance=template.document.distance??5,increment=event2.shiftKey||distance<=30?15:5,coneMultiplier=shapeType==="cone"?canvas.scene.hasHexGrid?2:3:1,snap=increment*coneMultiplier,delta=snap*Math.sign(event2.deltaY);return template.rotate(template.document.direction+delta,snap)}#activatePreviewListeners(preview,initialLayer){let lastMove=Date.now();const listeners=this.#previewListeners={mousemove:event2=>{event2.stopPropagation();const now=Date.now();if(now-lastMove<=25)return;canvas._onDragCanvasPan(event2);const destination=event2.getLocalPosition(this),dx=destination.x-preview.document.x,dy=destination.y-preview.document.y;preview.document.updateSource({x:preview.document.x+dx,y:preview.document.y+dy}),preview.renderFlags.set({refresh:!0}),lastMove=now},wheel:event2=>{if(!(event2 instanceof WheelEvent))return;event2.preventDefault(),event2.stopPropagation();const now=Date.now();if(now-lastMove<=25)return;const{direction}=preview.document,distance=preview.document.distance??5;if(event2.ctrlKey){const snap=event2.shiftKey||distance<=30?15:5;preview.document.updateSource({direction:direction+snap*Math.sign(event2.deltaY)}),preview.renderFlags.set({refresh:!0})}else if(event2.shiftKey){const snap=canvas.grid.type>=CONST.GRID_TYPES.HEXODDR&&canvas.grid.type<=CONST.GRID_TYPES.HEXEVENQ?60:45;preview.document.updateSource({direction:direction+snap*Math.sign(event2.deltaY)}),preview.renderFlags.set({refresh:!0})}lastMove=now},wheelAbortController:new AbortController,mousedown:event2=>{event2.stopPropagation(),preview.snapForShape();const{document:document2,position}=preview;this.#deactivatePreviewListeners(initialLayer,event2),document2.updateSource(canvas.grid.getSnappedPosition(position.x,position.y,this.gridPrecision)),canvas.scene?.createEmbeddedDocuments("MeasuredTemplate",[document2.toObject()])},rightdown:event2=>{event2.stopPropagation(),this.#deactivatePreviewListeners(initialLayer,event2)}};canvas.stage.on("mousemove",listeners.mousemove),canvas.app.view.addEventListener?.("wheel",listeners.wheel,{passive:!1,signal:listeners.wheelAbortController.signal}),canvas.stage.once("mousedown",listeners.mousedown),canvas.stage.once("rightdown",listeners.rightdown)}#deactivatePreviewListeners(initialLayer,event2){this._onDragLeftCancel(event2),this.#previewListeners&&(canvas.stage.off("mousemove",this.#previewListeners.mousemove),canvas.stage.off("mousedown",this.#previewListeners.mousedown),canvas.stage.off("rightdown",this.#previewListeners.rightdown),this.#previewListeners.wheelAbortController.abort(),this.#previewListeners=null),initialLayer!==this&&initialLayer?.activate()}}class TokenLayerPF2e extends TokenLayer{static{__name(this,"TokenLayerPF2e")}static{__name2(this,"TokenLayerPF2e")}cycleStack(){const hovered=this.hover;if(!hovered)return!1;const stack=this.placeables.filter(t=>hovered.distanceTo(t)===0&&hovered.document.elevation===t.document.elevation).sort((a,b)=>a.mesh.sort-b.mesh.sort);if(stack.length<2)return!1;const first=stack.shift();stack.push(first);for(let sort=stack.length-1;sort>=0;sort--){const token=stack[sort];token.document.sort=sort,token.mesh.initialize({sort}),sort===stack.length-1&&(token.emitHoverIn(new PointerEvent("pointerenter")),this.hover=token)}return!0}}function measureDistanceCuboid(r0,r1,{reach=null,token=null,target=null}={}){if(!canvas.dimensions)return NaN;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(r0,r1);const gridWidth=canvas.grid.grid.w,distance={dx:0,dy:0,dz:0};if([[r0,r1],[r1,r0]].some(([rA,rB])=>rB.right>rA.left&&rB.left<rA.right&&rB.bottom>rA.top&&rB.top<rA.bottom))distance.dx=0,distance.dy=0;else{const snapBounds=__name2((rectangle,{toward})=>{const roundLeft=rectangle.left<toward.left?Math.ceil:Math.floor,roundTop=rectangle.top<toward.top?Math.ceil:Math.floor,left=roundLeft(rectangle.left/gridWidth)*gridWidth,top=roundTop(rectangle.top/gridWidth)*gridWidth,width=Math.ceil(rectangle.width/gridWidth)*gridWidth,height=Math.ceil(rectangle.height/gridWidth)*gridWidth;return new PIXI.Rectangle(left,top,width,height)},"snapBounds"),r0Snapped=snapBounds(r0,{toward:r1}),r1Snapped=snapBounds(r1,{toward:r0});distance.dx=Math.max(r0Snapped.left-r1Snapped.right,r1Snapped.left-r0Snapped.right,0)+gridWidth,distance.dy=Math.max(r0Snapped.top-r1Snapped.bottom,r1Snapped.top-r0Snapped.bottom,0)+gridWidth}if(token&&target&&token?.document?.elevation!==target?.document.elevation&&token.actor&&target.actor){const selfElevation=token.document.elevation,targetElevation=target.document.elevation,[selfDimensions,targetDimensions]=[token.actor.dimensions,target.actor.dimensions],gridSize=canvas.dimensions.size,gridDistance=canvas.dimensions.distance,elevation0=Math.floor(selfElevation/gridDistance*gridSize),height0=Math.floor(selfDimensions.height/gridDistance*gridSize),elevation1=Math.floor(targetElevation/gridDistance*gridSize),height1=Math.floor(targetDimensions.height/gridDistance*gridSize),xzPlane={self:new PIXI.Rectangle(r0.x,elevation0,r0.width,height0),target:new PIXI.Rectangle(r1.x,elevation1,r1.width,height1)};if([[xzPlane.self,xzPlane.target],[xzPlane.target,xzPlane.self]].some(([rA,rB])=>rB.bottom>rA.top&&rB.top<rA.bottom))distance.dz=0;else{const snapBounds=__name2((rectangle,{toward})=>{const roundLeft=rectangle.left<toward.left?Math.ceil:Math.floor,roundTop=rectangle.top<toward.top?Math.ceil:Math.floor,left=roundLeft(rectangle.left/gridWidth)*gridWidth,top=roundTop(rectangle.top/gridWidth)*gridWidth,width=Math.ceil(rectangle.width/gridWidth)*gridWidth,height=Math.ceil(rectangle.height/gridWidth)*gridWidth;return new PIXI.Rectangle(left,top,width,height)},"snapBounds"),r0Snapped=snapBounds(xzPlane.self,{toward:xzPlane.target}),r1Snapped=snapBounds(xzPlane.target,{toward:xzPlane.self});distance.dz=Math.max(r0Snapped.top-r1Snapped.bottom,r1Snapped.top-r0Snapped.bottom,0)+gridWidth}}else distance.dz=0;return measureDistanceOnGrid(distance,{reach})}__name(measureDistanceCuboid,"measureDistanceCuboid"),__name2(measureDistanceCuboid,"measureDistanceCuboid");function measureDistance(p0,p1){return canvas.dimensions?canvas.grid.type!==CONST.GRID_TYPES.SQUARE?canvas.grid.measureDistance(p0,p1):measureDistanceOnGrid(new Ray(p0,p1)):NaN}__name(measureDistance,"measureDistance"),__name2(measureDistance,"measureDistance");function measureDistanceOnGrid(segment,{reach=null}={}){if(!canvas.dimensions)return NaN;const gridSize=canvas.dimensions.size,gridDistance=canvas.dimensions.distance,nx=Math.ceil(Math.abs(segment.dx/gridSize)),ny=Math.ceil(Math.abs(segment.dy/gridSize)),nz=Math.ceil(Math.abs((segment.dz||0)/gridSize)),sortedDistance=[nx,ny,nz].sort((a,b)=>a-b),squares={doubleDiagonal:sortedDistance[0],diagonal:sortedDistance[1]-sortedDistance[0],straight:sortedDistance[2]-sortedDistance[1]},reduction=squares.diagonal+squares.doubleDiagonal>1&&reach===10?1:0;return(Math.floor(squares.doubleDiagonal*1.75+squares.diagonal*1.5+squares.straight)-reduction)*gridDistance}__name(measureDistanceOnGrid,"measureDistanceOnGrid"),__name2(measureDistanceOnGrid,"measureDistanceOnGrid");function highlightGrid({areaType,object,colors,document:document2,collisionType="move",preview=!1}){if(!object.id&&!preview)return;const{grid,dimensions}=canvas;if(!(grid&&dimensions))return;const angle=document2.angle??0,direction=document2.direction??45,highlightLayer=grid.getHighlightLayer(object.highlightId)?.clear();if(!highlightLayer)return;const[cx,cy]=grid.getCenter(document2.x,document2.y),[col0,row0]=grid.grid.getGridPositionFromPixels(cx,cy),minAngle=(360+(direction-angle*.5)%360)%360,maxAngle=(360+(direction+angle*.5)%360)%360,snappedOrigin=canvas.grid.getSnappedPosition(document2.x,document2.y,object.layer.gridPrecision),withinAngle=__name2((min,max,value)=>(min=(360+min%360)%360,max=(360+max%360)%360,value=(360+value%360)%360,min<max?value>=min&&value<=max:value>=min||value<=max),"withinAngle"),coneOriginOffset=(()=>{if(areaType!=="cone")return{x:0,y:0};const dir=(direction>=0?360-direction:-direction)%360,xOffset=snappedOrigin.x%dimensions.size!==0?Math.sign(1*Math.round(Math.cos(Math.toRadians(dir))*100)/100)/2:0,yOffset=snappedOrigin.y%dimensions.size!==0?-Math.sign(1*Math.round(Math.sin(Math.toRadians(dir))*100)/100)/2:0;return{x:xOffset*dimensions.size,y:yOffset*dimensions.size}})(),padding=Math.clamped(document2.width??0,1.5,2),docDistance=document2.distance??0,padded=docDistance*padding/dimensions.distance,rowCount=Math.ceil(padded/(dimensions.size/grid.h)),columnCount=Math.ceil(padded/(dimensions.size/grid.w)),offsetEmanationOrigin=__name2(destination=>{if(!(areaType==="emanation"&&object instanceof TokenPF2e))return{x:0,y:0};if(object.w<=dimensions.size)return{x:0,y:0};const offset=(object.w-dimensions.size)/2,getCoordinate=__name2((centerCoord,destCoord)=>destCoord===centerCoord?0:destCoord>centerCoord?offset:-offset,"getCoordinate");return{x:getCoordinate(object.center.x,destination.x),y:getCoordinate(object.center.y,destination.y)}},"offsetEmanationOrigin");for(let a=-columnCount;a<columnCount;a++)for(let b=-rowCount;b<rowCount;b++){const[gx,gy]=canvas.grid.grid.getPixelsFromGridPosition(col0+a,row0+b),destination={x:gx+dimensions.size*.5,y:gy+dimensions.size*.5};if(destination.x<0||destination.y<0)continue;const emanationOriginOffset=offsetEmanationOrigin(destination),origin={x:snappedOrigin.x+coneOriginOffset.x+emanationOriginOffset.x,y:snappedOrigin.y+coneOriginOffset.y+emanationOriginOffset.y};if(areaType==="cone"){const ray=new Ray(origin,destination),rayAngle=(360+ray.angle/(Math.PI/180)%360)%360;if(ray.distance>0&&!withinAngle(minAngle,maxAngle,rayAngle))continue}if(measureDistance(destination,origin)>docDistance)continue;canvas.ready&&CONFIG.Canvas.polygonBackends[collisionType].testCollision(origin,destination,{type:collisionType,mode:"any"})?(grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:1,color:0}),highlightLayer.beginFill(0,.5).moveTo(gx,gy).lineTo(gx+dimensions.size,gy+dimensions.size).endFill()):grid.grid.highlightGridPosition(highlightLayer,{x:gx,y:gy,border:colors.border,color:colors.fill})}}__name(highlightGrid,"highlightGrid"),__name2(highlightGrid,"highlightGrid");class MeasuredTemplatePF2e extends MeasuredTemplate{static{__name(this,"MeasuredTemplatePF2e")}static{__name2(this,"MeasuredTemplatePF2e")}get actor(){return this.document.actor}get item(){return this.document.item}get message(){return this.document.message}get areaType(){return this.document.areaType}snapForShape(){this.layer.snapFor(this.areaType)}highlightGrid(){const isCircleOrCone=["circle","cone"].includes(this.document.t),hasSquareGrid=canvas.grid.type===CONST.GRID_TYPES.SQUARE;if(!isCircleOrCone||!hasSquareGrid)return super.highlightGrid();if(!this.isVisible){canvas.grid.getHighlightLayer(this.highlightId)?.clear();return}this.snapForShape(),highlightGrid({areaType:this.areaType,object:this,document:this.document,colors:{border:this.borderColor,fill:this.fillColor},preview:!0})}async _onDragLeftDrop(event2){return this.snapForShape(),super._onDragLeftDrop(event2)}}class HearingSource extends SoundSource{static{__name(this,"HearingSource")}static{__name2(this,"HearingSource")}_initialize(data){super._initialize(data),this.data.x=this.object.center.x,this.data.y=this.object.center.y,this.data.elevation=this.object.document.elevation,this.data.radius=canvas.dimensions?.maxR??1e3,this.data.walls=!0}}class EffectAreaSquare extends PIXI.Rectangle{static{__name(this,"EffectAreaSquare")}static{__name2(this,"EffectAreaSquare")}active;constructor(x,y,width,height,active=!0){super(x,y,width,height),this.active=active}get center(){return{x:this.x+this.width/2,y:this.y+this.height/2}}highlight(layer,{border,highlight}){this.x<0||this.y<0||(this.active?canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:border?.color,color:highlight.color,alpha:highlight.alpha}):(canvas.grid.grid.highlightGridPosition(layer,{x:this.x,y:this.y,border:0,color:0}),layer.beginFill(0,.5).moveTo(this.x,this.y).lineTo(this.x+this.width,this.y+this.height).endFill()))}}function getAreaSquares(data){if(!canvas.dimensions)return[];const squareWidth=canvas.dimensions.size,rowCount=Math.ceil(data.bounds.width/squareWidth),emptyVector=Array(rowCount-1).fill(null),genColumn=__name2(square=>emptyVector.reduce(colSquares=>{const squareAbove=colSquares.at(-1),squareBelow=new EffectAreaSquare(square.x,squareAbove.y+squareWidth,squareWidth,squareWidth);return colSquares.push(squareBelow),colSquares},[square]),"genColumn"),topLeftSquare=new EffectAreaSquare(data.bounds.x,data.bounds.y,squareWidth,squareWidth),collisionType=data.traits?.includes("visual")&&!data.traits.includes("auditory")?"sight":data.traits?.includes("auditory")&&!data.traits.includes("visual")?"sound":"move",tokenBounds=data.token.mechanicalBounds,tokenCenter=data.token.center,tokenCenters=[tokenCenter,...[{x:0,y:1},{x:1,y:0},{x:0,y:-1},{x:-1,y:0}].map(c=>({x:tokenCenter.x+c.x*Math.round(tokenBounds.width/8),y:tokenCenter.y+c.y*Math.round(tokenBounds.height/8)}))];return emptyVector.reduce(squares=>{const lastSquare=squares.at(-1)?.at(-1)??{x:NaN,y:NaN},column=genColumn(new EffectAreaSquare(lastSquare.x+squareWidth,topLeftSquare.y,squareWidth,squareWidth));return squares.push(column),squares},[genColumn(topLeftSquare)]).flat().filter(s=>measureDistanceCuboid(tokenBounds,s)<=data.radius).map(square=>(square.active=tokenCenters.some(c=>!CONFIG.Canvas.polygonBackends[collisionType].testCollision(c,square.center,{type:collisionType,mode:"any"})),square))}__name(getAreaSquares,"getAreaSquares"),__name2(getAreaSquares,"getAreaSquares");class AuraRenderer extends PIXI.Graphics{static{__name(this,"AuraRenderer")}static{__name2(this,"AuraRenderer")}slug;token;radius;radiusPixels;traits;appearance;static LINE_THICKNESS=3;border=new PIXI.Graphics;textureContainer=null;constructor(params){super(),this.slug=params.slug,this.token=params.token,this.appearance=params.appearance,this.radius=params.radius,this.radiusPixels=.5*this.token.mechanicalBounds.width+this.radius/(canvas.dimensions?.distance??0)*canvas.grid.size,this.traits=params.traits,this.addChild(this.border)}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get highlightLayer(){return canvas.grid?.getHighlightLayer(this.token.highlightId)??null}get squares(){return getAreaSquares(this)}async draw(showBorder){const{mechanicalBounds}=this.token;return this.x=mechanicalBounds.width/2,this.y=mechanicalBounds.height/2,this.token.document.width<1&&(this.x+=mechanicalBounds.x-this.token.x,this.y+=mechanicalBounds.y-this.token.y),this.#drawBorder(),this.border.visible=showBorder,this.#drawTexture()}repositionTexture(){if(this.textureContainer){const{bounds,radiusPixels}=this;this.textureContainer.position.set(bounds.x+radiusPixels,bounds.y+radiusPixels)}}#drawBorder(){const data=this.appearance.border;!data||this.border.geometry.graphicsData.length>0||this.border.lineStyle(AuraRenderer.LINE_THICKNESS,data.color,data.alpha).drawCircle(0,0,this.radiusPixels)}async#drawTexture(){const data=this.appearance.texture;if(!data||this.token.isPreview||this.textureContainer)return;this.textureContainer=new PIXI.Graphics;const texture=await(async()=>{const maybeTexture=await loadTexture(data.src,{fallback:"icons/svg/hazard.svg"});if(!(maybeTexture instanceof PIXI.Texture))return null;const globalVideo=isVideoFilePath(data.src)?game.video.getVideoSource(maybeTexture):null;if(globalVideo){maybeTexture.destroy();const videoTexture=await game.video.cloneTexture(globalVideo),video=game.video.getVideoSource(videoTexture)??globalVideo;video.playbackRate=data.playbackRate;const offset=data.loop?Math.random()*video.duration:0;return game.video.play(video,{volume:0,offset,loop:data.loop}),videoTexture}else return maybeTexture})();if(!texture)return;const{bounds,radiusPixels}=this,radius=data.scale*radiusPixels,diameter=radius*2,scale={x:diameter/texture.width,y:diameter/texture.height},matrix=new PIXI.Matrix(scale.x,void 0,void 0,scale.y,radius,radius);this.textureContainer.beginTextureFill({texture,alpha:data.alpha,matrix}).drawCircle(0,0,radius).endFill(),this.textureContainer.position.set(bounds.x+radiusPixels,bounds.y+radiusPixels),canvas.grid.grid.addChild(this.textureContainer)}highlight(){const{dimensions}=canvas;if(!dimensions)return;if(this.#drawLabel(),!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active)){const{highlightLayer}=this;if(!highlightLayer)return;for(const square of this.squares)square.highlight(highlightLayer,this.appearance)}}#drawLabel(){const style=CONFIG.canvasTextStyle.clone(),gridSize=canvas.dimensions?.size??100;style.fontSize=Math.max(Math.round(gridSize*.36*12)/12,36),style.align="center";const bounds=this.token.mechanicalBounds,gridUnits=canvas.scene?.grid.units.trim()||game.system.gridUnits,label=[this.radius,gridUnits].join(""),text=new PreciseText(label,style),center={x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2},textOffset=Math.sqrt(style.fontSize);text.position.set(center.x+textOffset,center.y-this.radiusPixels-style.fontSize-textOffset),this.highlightLayer?.beginFill(0,.5).lineStyle(AuraRenderer.LINE_THICKNESS,0).drawCircle(center.x,center.y-this.radiusPixels,6).endFill().addChild(text)}destroy(options){super.destroy(options),this.textureContainer&&(canvas.grid.grid.removeChild(this.textureContainer),this.textureContainer.destroyed||this.textureContainer.destroy())}}class AuraRenderers extends Map{static{__name(this,"AuraRenderers")}static{__name2(this,"AuraRenderers")}token;constructor(token){super(),this.token=token}get highlightId(){return this.token.highlightId}async reset(slugs){if(!slugs)this.clear();else for(const slug of slugs)this.delete(slug);if(!this.token.actor)return;const data=Array.from(this.token.document.auras.values()).filter(a=>slugs?.includes(a.slug)??!0);for(const datum of data){const renderer=new AuraRenderer({...datum,token:this.token});this.set(datum.slug,this.token.addChild(renderer))}return this.draw()}refreshPositions(){for(const aura of this.values())aura.repositionTexture()}get#showBordersHighlights(){const inEncounter=__name2(()=>!!(this.token.actor?.isOfType("familiar")?this.token.actor.master?.combatant?.encounter.active:this.token.combatant?.encounter.active),"inEncounter");return canvas.scene?.grid.type===CONST.GRID_TYPES.SQUARE&&canvas.scene.tokenVision&&canvas.scene.isInFocus&&(game.user.isGM||this.token.actor?.alliance==="party")&&(this.token.controlled||this.token.hover||this.token.layer.highlightObjects||inEncounter())}async draw(){if(this.size===0||(this.clearHighlights(),this.token.isAnimating))return;const showBordersHighlights=this.#showBordersHighlights;for(const aura of this.values())await aura.draw(showBordersHighlights);if(showBordersHighlights&&(this.token.hover||this.token.layer.highlightObjects)){const{highlightId}=this;(canvas.grid.highlightLayers[highlightId]??canvas.grid.addHighlightLayer(highlightId)).clear();for(const aura of this.values())aura.highlight()}}delete(key){const aura=this.get(key);return aura?(aura.destroyed||aura.destroy(!0),this.token.removeChild(aura),super.delete(key)):!1}clear(){this.clearHighlights();for(const aura of this.values())aura.destroyed||aura.destroy(!0),this.token.removeChild(aura);return super.clear()}destroy(){this.clear()}clearHighlights(){canvas.grid.destroyHighlightLayer(this.highlightId)}}class FlankingHighlightRenderer{static{__name(this,"FlankingHighlightRenderer")}static{__name2(this,"FlankingHighlightRenderer")}#layer=null;token;labelText;lineColor;constructor(token){this.token=token,this.labelText=game.i18n.localize("PF2E.Token.Flanking"),this.lineColor=CONFIG.Canvas.dispositionColors.CONTROLLED}get layer(){return this.#layer??this.#addLayer()}get shouldRender(){return canvas.ready&&!!canvas.scene?.isInFocus&&this.tokenIsSelectedOrOwn&&this.tokenIsReady}get tokenIsSelectedOrOwn(){return this.token.controlled&&this.token.isOwner||!!this.token.actor&&this.token.actor?.id===game.user.character?.id}get tokenIsReady(){return!this.token.isPreview&&!this.token.isAnimating}draw(){if(this.clear(),canvas.tokens.highlightObjects&&game.user.targets.size&&this.shouldRender)for(const target of game.user.targets)this.drawForTarget(target)}drawForTarget(target){const buddies=this.token.buddiesFlanking(target,{ignoreFlankable:!0});this.drawBuddyLines(buddies)}drawBuddyLines(buddies){for(const token of buddies)this.drawBuddyLine(token)}drawBuddyLine(buddy){const t=CONFIG.Canvas.objectBorderThickness,o=Math.round(t*1.5),c=Math.round(t*2);this.layer.lineStyle(o,0,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.lineStyle(t,this.lineColor,.5).moveTo(this.token.center.x,this.token.center.y).lineTo(buddy.center.x,buddy.center.y),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(this.token.center.x,this.token.center.y,c),this.layer.beginFill(this.lineColor).lineStyle(1,0).drawCircle(buddy.center.x,buddy.center.y,c),this.drawLabel(buddy)}drawLabel(buddy){const mid_x=Math.round((this.token.center.x+buddy.center.x)/2),mid_y=Math.round((this.token.center.y+buddy.center.y)/2),vect_x=buddy.center.x-this.token.center.x,vect_y=buddy.center.y-this.token.center.y,perp_vect_x=vect_x<=-vect_x?-vect_y:vect_y,perp_vect_y=vect_x<=-vect_x?vect_x:-vect_x,offsetScale=20/Math.sqrt(perp_vect_x**2+perp_vect_y**2),perp_x=mid_x+Math.round(perp_vect_x*offsetScale),perp_y=mid_y+Math.round(perp_vect_y*offsetScale),style=CONFIG.canvasTextStyle.clone();style.fontSize=24,canvas.dimensions?.size&&canvas.dimensions.size>=200?style.fontSize=28:canvas.dimensions?.size&&canvas.dimensions.size<50&&(style.fontSize=20),style.fill=this.lineColor,style.stroke=0;const text=new PreciseText(this.labelText,style);text.anchor.set(.5,.5);let rotation=Math.atan2(vect_y,vect_x);rotation>Math.PI/2?rotation=rotation-Math.PI:rotation<-Math.PI/2&&(rotation=rotation+Math.PI),text.rotation=rotation,text.position.set(perp_x,perp_y),this.layer.addChild(text)}clear(){this.#layer?.destroy({children:!0}),this.#layer=null}destroy(){this.clear()}#addLayer(){return this.#layer=new PIXI.Graphics,this.token.layer.addChild(this.#layer)}}class TokenPF2e extends Token{static{__name(this,"TokenPF2e")}static{__name2(this,"TokenPF2e")}auras;flankingHighlight;hearing;constructor(document2){super(document2),this.hearing=new HearingSource({object:this}),this.auras=new AuraRenderers(this),Object.defineProperty(this,"auras",{configurable:!1,writable:!1}),this.flankingHighlight=new FlankingHighlightRenderer(this),Object.defineProperty(this,"flankingHighlight",{configurable:!1,writable:!1})}get isVisible(){if(this.detectionFilter=null,this.document.hidden&&!game.user.isGM)return!1;if(!canvas.effects.visibility.tokenVision||this.controlled||canvas.effects.visionSources.get(this.sourceId)?.active)return!0;const tolerance=Math.floor(.35*Math.min(this.w,this.h));return canvas.effects.visibility.testVisibility(this.center,{tolerance,object:this})}get isAnimating(){return!!this._animation}get emitsDarkness(){return this.document.emitsDarkness}get hasLowLightVision(){return this.document.hasLowLightVision}get hasDarkvision(){return this.document.hasDarkvision}get linkToActorSize(){return this.document.linkToActorSize}get highlightId(){return`Token.${this.id}`}get mechanicalBounds(){const bounds=super.bounds;if(this.document.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get sightRange(){return canvas.dimensions?this.document.sight.range>=canvas.dimensions.maxR?canvas.dimensions.maxR:super.sightRange:0}isAdjacentTo(token){return this.distanceTo(token)===5}canFlank(flankee,context={}){if(this===flankee||!game.settings.get("pf2e","automation.flankingDetection"))return!1;const flankable=context.ignoreFlankable||flankee.actor?.attributes.flanking.flankable;if(!(this.actor?.attributes.flanking.canFlank&&flankable)||!this.actor.isOfType("character","npc")||!flankee.actor?.isOfType("creature")||this.actor.isAllyOf(flankee.actor))return!1;const reach=context.reach??this.actor.getReach({action:"attack"});return this.actor.canAttack&&reach>=this.distanceTo(flankee,{reach})}onOppositeSides(flankerA,flankerB,flankee){const[centerA,centerB]=[flankerA.center,flankerB.center],{bounds}=flankee,left=new Ray({x:bounds.left,y:bounds.top},{x:bounds.left,y:bounds.bottom}),right=new Ray({x:bounds.right,y:bounds.top},{x:bounds.right,y:bounds.bottom}),top=new Ray({x:bounds.left,y:bounds.top},{x:bounds.right,y:bounds.top}),bottom=new Ray({x:bounds.left,y:bounds.bottom},{x:bounds.right,y:bounds.bottom}),intersectsSide=__name2(side=>foundry.utils.lineSegmentIntersects(centerA,centerB,side.A,side.B),"intersectsSide");return intersectsSide(left)&&intersectsSide(right)||intersectsSide(top)&&intersectsSide(bottom)}isFlanking(flankee,context={}){if(!(this.actor&&this.canFlank(flankee,context)))return!1;const{flanking}=this.actor.attributes,flankingBuddies=canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick(context,["ignoreFlankable"])));return flankingBuddies.length===0?!1:flanking.canGangUp.some(g=>typeof g=="number"&&g<=flankingBuddies.length||g===!0&&flankingBuddies.length>=1)||flankingBuddies.some(b=>b.actor?.attributes.flanking.canGangUp.some(g=>g===!0))||this.isAdjacentTo(flankee)&&flanking.canGangUp.includes("animal-companion")&&flankingBuddies.some(b=>{if(!b.actor?.isOfType("character"))return!1;const traits=b.actor.traits;return traits.has("minion")&&!traits.has("construct")&&b.isAdjacentTo(flankee)})?!0:flankingBuddies.some(b=>this.onOppositeSides(this,b,flankee))}buddiesFlanking(flankee,context={}){return!this.actor||!this.canFlank(flankee,context)?[]:canvas.tokens.placeables.filter(t=>t!==this&&t.canFlank(flankee,pick(context,["ignoreFlankable"]))).filter(b=>this.onOppositeSides(this,b,flankee))}_applyRenderFlags(flags){super._applyRenderFlags(flags),flags.refreshPosition&&this.auras.refreshPositions()}_refreshVisibility(){super._refreshVisibility(),this.auras.draw(),this.flankingHighlight.draw()}_getBorderColor(options){const isHovered=options?.hover??(this.hover||this.layer.highlightObjects),isControlled=this.controlled||!game.user.isGM&&this.isOwner,isFriendly=this.document.disposition===CONST.TOKEN_DISPOSITIONS.FRIENDLY;if(!isHovered||isControlled||isFriendly||!this.actor?.hasPlayerOwner)return super._getBorderColor();const colors=CONFIG.Canvas.dispositionColors;switch(this.document.disposition){case CONST.TOKEN_DISPOSITIONS.NEUTRAL:return colors.NEUTRAL;case CONST.TOKEN_DISPOSITIONS.HOSTILE:return colors.HOSTILE;case CONST.TOKEN_DISPOSITIONS.SECRET:return this.isOwner?colors.SECRET:null;default:return super._getBorderColor(options)}}_drawBar(number,bar,data){if(!canvas.dimensions)return;const actor=this.document.actor;if(!(data.attribute==="attributes.hp"&&actor?.attributes.hp))return super._drawBar(number,bar,data);const{value,max,temp}=actor.attributes.hp??{},healthPercent=Math.clamped(value,0,max)/max,black=0,color=Number(number?Color.fromRGB([.5*healthPercent,.7*healthPercent,.5+healthPercent/2]):Color.fromRGB([1-healthPercent/2,healthPercent,0]));let h=Math.max(canvas.dimensions.size/12,8);const bs=Math.clamped(h/8,1,2);this.document.height>=2&&(h*=1.6);const numBars=temp>0?2:1,barHeight=h/numBars;if(bar.clear(),bar.lineStyle(0).beginFill(black,.5).drawRoundedRect(0,0,this.w,h,3),bar.lineStyle(bs/2,black,1),temp>0){const tempWidth=Math.clamped(temp,0,max)/max*this.w-2*(bs-1);bar.beginFill(6737151,1).drawRoundedRect(0,0,tempWidth,barHeight,2)}const healthBarY=(numBars-1)*barHeight;bar.beginFill(color,1).drawRoundedRect(0,healthBarY,healthPercent*this.w,barHeight,2),bar.beginFill(black,0).lineStyle(bs,black,1).drawRoundedRect(0,0,this.w,h,3),bar.position.set(0,number===0?this.h-h:0)}async drawEffects(){if(await super.drawEffects(),await this._animation,this.auras.size===0)return this.auras.reset();const changedAndDeletedAuraSlugs=Array.from(this.auras.entries()).filter(([slug,aura])=>{const properties=["radius","appearance"],sceneData=pick(this.document.auras.get(slug)??{radius:null,appearance:null},properties);if(sceneData.radius===null)return!0;const canvasData=pick(aura,properties);return!equals(sceneData,canvasData)}).map(([slug])=>slug),newAuraSlugs=Array.from(this.document.auras.keys()).filter(s=>!this.auras.has(s));return this.auras.reset([changedAndDeletedAuraSlugs,newAuraSlugs].flat())}emitHoverIn(nativeEvent){const event2=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event2.type="pointerover",event2.nativeEvent=nativeEvent,this._onHoverIn(event2,{hoverOutOthers:!0})}emitHoverOut(nativeEvent){const event2=new PIXI.FederatedPointerEvent(new PIXI.EventBoundary(this));event2.type="pointerout",event2.nativeEvent=nativeEvent,this._onHoverOut(event2)}_isVisionSource(){return!!this.actor?.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_partyVision")||super._isVisionSource()}clone(){const clone=super.clone();return clone.isPreview&&(clone.document.height=this.document.height,clone.document.width=this.document.width,clone.document.texture.scaleX=this.document.texture.scaleX,clone.document.texture.scaleY=this.document.texture.scaleY,clone.document.texture.src=this.document.texture.src),clone}async showFloatyText(params){if(!this.isVisible)return;if(!game.user.isGM&&typeof params!="number"){const[_,document2]=Object.entries(params)[0];if(document2 instanceof EffectPF2e&&document2.system.unidentified)return}const scrollingTextArgs=(()=>{if(typeof params=="number"){const quantity=params,maxHP=this.actor?.hitPoints?.max;if(!(quantity&&typeof maxHP=="number"))return null;const percent=Math.clamped(Math.abs(quantity)/maxHP,0,1),textColors={damage:16711680,healing:65280};return[this.center,params.signedString(),{anchor:CONST.TEXT_ANCHOR_POINTS.TOP,jitter:.25,fill:textColors[quantity<0?"damage":"healing"],fontSize:16+32*percent,stroke:0,strokeThickness:4}]}else{const[change,details]=Object.entries(params)[0],isAdded=change==="create",sign=isAdded?"+ ":"- ",appendedNumber=!/ \d+$/.test(details.name)&&details.value?` ${details.value}`:"",content=`${sign}${details.name}${appendedNumber}`,anchorDirection=isAdded?CONST.TEXT_ANCHOR_POINTS.TOP:CONST.TEXT_ANCHOR_POINTS.BOTTOM,textStyle=pick(this._getTextStyle(),["fill","fontSize","stroke","strokeThickness"]);return[this.center,content,{...textStyle,anchor:anchorDirection,direction:anchorDirection,jitter:.25}]}})();scrollingTextArgs&&(await this._animation,await canvas.interface?.createScrollingText(...scrollingTextArgs))}distanceTo(target,{reach=null}={}){if(!canvas.dimensions)return NaN;if(this===target)return 0;if(canvas.grid.type!==CONST.GRID_TYPES.SQUARE)return canvas.grid.measureDistance(this.position,target.position);const selfElevation=this.document.elevation,targetElevation=target.document.elevation;return selfElevation===targetElevation||!this.actor||!target.actor?measureDistanceCuboid(this.bounds,target.bounds,{reach}):measureDistanceCuboid(this.bounds,target.bounds,{reach,token:this,target})}async animate(updateData,options){if(options?.spin){let attributeAdded=!1;const currentRotation=this.document.rotation,rotationAngle=this.x<=this.document.x?360:-360;options.ontick=(_frame,data)=>{if(this.document.lockRotation=!1,!attributeAdded&&data.attributes.length>0){const duration=(data.duration??1e3)/1e3;data.attributes.push({attribute:"rotation",parent:data.attributes[0].parent,from:currentRotation,to:currentRotation+duration*rotationAngle,delta:data.attributes[0].delta}),attributeAdded=!0}}}await super.animate(updateData,options),this.document.lockRotation=this.document._source.lockRotation}updateVisionSource({defer=!1,deleted=!1}={}){super.updateVisionSource({defer,deleted}),this._isVisionSource()&&!deleted&&this.hearing.initialize()}render(renderer){if(super.render(renderer),!this.mesh)return;const configuredTint=this.document.texture.tint??"#FFFFFF";this.mesh.tint!==0&&this.detectionFilter instanceof OutlineOverlayFilter?this.mesh.tint=0:this.mesh.tint===0&&configuredTint!=="#000000"&&!this.detectionFilter&&(this.mesh.tint=Number(Color.fromString(configuredTint)))}_destroy(){super._destroy(),this.auras.destroy(),this.hearing.destroy(),this.flankingHighlight.destroy()}_canView(user,event2){return super._canView(user,event2)||!!(this.actor?.isOfType("npc")&&this.actor.isLootable)}_onControl(options={}){return game.ready&&game.pf2e.effectPanel.refresh(),super._onControl(options)}_onRelease(options){return game.pf2e.effectPanel.refresh(),super._onRelease(options)}_onApplyStatusEffect(statusId,active){super._onApplyStatusEffect(statusId,active),["undetected","unnoticed"].includes(statusId)&&(canvas.perception.update({refreshVision:!0,refreshLighting:!0},!0),this.mesh.refresh())}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.width&&(this._animation?this._animation.then(()=>{this.auras.reset()}):this.auras.reset())}}class TokenAura{static{__name(this,"TokenAura")}static{__name2(this,"TokenAura")}slug;token;level;radius;traits;effects;appearance;#squares;constructor(params){this.slug=params.slug,this.token=params.token,this.level=params.level,this.radius=params.radius,this.traits=params.traits,this.effects=params.effects,this.appearance=params.appearance}get radiusPixels(){const gridSize=this.scene.grid.distance,gridSizePixels=this.scene.grid.size;return .5*this.token.mechanicalBounds.width+this.radius/gridSize*gridSizePixels}get scene(){return this.token.scene}get bounds(){const{token,radiusPixels}=this,bounds=token.mechanicalBounds;return new PIXI.Rectangle(bounds.x-(radiusPixels-bounds.width/2),bounds.y-(radiusPixels-bounds.width/2),radiusPixels*2,radiusPixels*2)}get center(){return this.token.center}get squares(){return this.#squares??=getAreaSquares(this)}containsToken(token){return this.token.hidden||token.hidden||!this.token.object||!token.object?!1:token===this.token?!0:this.token.object.distanceTo(token.object)>this.radius?!1:this.squares.some(s=>s.active&&measureDistanceCuboid(s,token.mechanicalBounds)===0)}async notifyActors(){if(!this.scene.isInFocus)return;const auraActor=this.token.actor,auraData=auraActor?.auras.get(this.slug);if(!(auraActor&&auraData?.effects.length))return;const auradTokens=this.scene.tokens.filter(t=>t.actor?.primaryUpdater===game.user&&this.containsToken(t)),affectedActors=new Set(auradTokens.flatMap(t=>t.actor??[])),origin={actor:auraActor,token:this.token};for(const actor of affectedActors)await actor.applyAreaEffects(auraData,origin)}}class TokenDocumentPF2e extends TokenDocument{static{__name(this,"TokenDocumentPF2e")}static{__name2(this,"TokenDocumentPF2e")}constructed=!0;get inCombat(){return this.actor?.isOfType("party")?this.actor.members.every(a=>game.combat?.getCombatantByActor(a.id)):super.inCombat}hasStatusEffect(statusId){if(statusId==="dead")return this.overlayEffect===CONFIG.controlIcons.defeated;const{actor}=this;return!actor||!game.pf2e.settings.rbv?!1:objectHasKey(CONFIG.PF2E.conditionTypes,statusId)&&actor.hasCondition(statusId)||__name2(()=>actor.itemTypes.effect.some(e=>(e.slug??sluggify(e.name))===statusId),"hasEffect")()}static getTrackedAttributes(data={},_path=[]){if(_path.length===0&&Object.keys(data).length===0)for(const[type,model]of Object.entries(game.system.model.Actor))["character","npc"].includes(type)&&foundry.utils.mergeObject(data,model);if(_path.length>0)return super.getTrackedAttributes(data,_path);const patterns={positive:/^(?:attributes|resources)\./,negative:/\b(?:rank|_?modifiers|item|classdc|dexcap|familiar|\w+hp\b)|bonus/i},prunedData=foundry.utils.expandObject(Object.fromEntries(Object.entries(foundry.utils.flattenObject(data)).filter(([k,v])=>patterns.positive.test(k)&&!patterns.negative.test(k)&&!["boolean","string"].includes(typeof v))));return super.getTrackedAttributes(prunedData,_path)}static getTrackedAttributeChoices(attributes){return attributes??=this.getTrackedAttributes(),game.pf2e.settings.variants.stamina&&attributes.bar.push(["attributes","hp","sp"]),super.getTrackedAttributeChoices(attributes)}getBarAttribute(barName,options){const attribute=super.getBarAttribute(barName,options);return attribute&&["attributes.hp.sp","resources.resolve"].includes(attribute.attribute)&&(attribute.editable=!0),attribute}get scene(){return this.parent}get emitsDarkness(){return this.light.bright<0}get rulesBasedVision(){return!!(this.sight.enabled&&this.actor?.isOfType("character","familiar")&&this.scene?.rulesBasedVision)}get hasLowLightVision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasLowLightVision)}get hasDarkvision(){return!!(this.rulesBasedVision&&this.actor?.isOfType("creature")&&this.actor.hasDarkvision)}get linkToActorSize(){return this.flags.pf2e.linkToActorSize}get autoscale(){return this.flags.pf2e.autoscale}get playersCanSeeName(){const anyoneCanSee=[CONST.TOKEN_DISPLAY_MODES.ALWAYS,CONST.TOKEN_DISPLAY_MODES.HOVER],nameDisplayMode=this.displayName;return anyoneCanSee.includes(nameDisplayMode)||this.actor?.alliance==="party"}get bounds(){const gridSize=this.scene?.grid.size??100;return new PIXI.Rectangle(this._source.x,this._source.y,this.width*gridSize,this.height*gridSize)}get mechanicalBounds(){const bounds=this.bounds;if(this.width<1){const position=canvas.grid.getTopLeft(bounds.x+bounds.width/2,bounds.y+bounds.height/2);return new PIXI.Rectangle(position[0],position[1],Math.max(canvas.grid.size,bounds.width),Math.max(canvas.grid.size,bounds.height))}return bounds}get center(){const{bounds}=this;return{x:bounds.x+bounds.width/2,y:bounds.y+bounds.height/2}}_initialize(options){this.constructed??=!1,this.auras=new Map,super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){if(super.prepareBaseData(),this.flags=foundry.utils.mergeObject(this.flags,{pf2e:{}}),this.auras.clear(),!this.actor||!this.isEmbedded)return;TokenDocumentPF2e.assignDefaultImage(this);for(const[key,data]of this.actor.auras.entries())this.auras.set(key,new TokenAura({token:this,...foundry.utils.deepClone(data)}));if(!this.constructed)return;const linkDefault=SIZE_LINKABLE_ACTOR_TYPES.has(this.actor.type),linkToActorSize=this.flags.pf2e?.linkToActorSize??linkDefault,autoscaleDefault=game.pf2e.settings.tokens.autoscale,autoscale=linkToActorSize?this.flags.pf2e.autoscale??autoscaleDefault:!1;this.flags.pf2e=foundry.utils.mergeObject(this.flags.pf2e??{},{linkToActorSize,autoscale});const{alliance}=this.actor.system.details;this.disposition=this.disposition===CONST.TOKEN_DISPOSITIONS.SECRET?CONST.TOKEN_DISPOSITIONS.SECRET:alliance?{party:CONST.TOKEN_DISPOSITIONS.FRIENDLY,opposition:CONST.TOKEN_DISPOSITIONS.HOSTILE}[alliance]:CONST.TOKEN_DISPOSITIONS.NEUTRAL}_prepareDetectionModes(){if(!(this.constructed&&this.actor&&this.rulesBasedVision))return super._prepareDetectionModes();this.detectionModes=[{id:"basicSight",enabled:!0,range:0}],["character","familiar"].includes(this.actor.type)&&(this.sight.attenuation=.1,this.sight.brightness=0,this.sight.contrast=0,this.sight.range=0,this.sight.saturation=0,this.sight.visionMode="basic")}prepareDerivedData(){if(super.prepareDerivedData(),!(this.constructed&&this.actor&&this.scene))return;const{tokenOverrides}=this.actor.synthetics;this.name=tokenOverrides.name??this.name,tokenOverrides.texture&&(this.texture.src=tokenOverrides.texture.src,"scaleX"in tokenOverrides.texture&&(this.texture.scaleX=tokenOverrides.texture.scaleX,this.texture.scaleY=tokenOverrides.texture.scaleY,this.flags.pf2e.autoscale=!1),this.texture.tint=tokenOverrides.texture.tint??this.texture.tint),this.alpha=tokenOverrides.alpha??this.alpha,tokenOverrides.light&&(this.light=new foundry.data.LightData(tokenOverrides.light,{parent:this})),TokenDocumentPF2e.prepareSize(this),this.#prepareDerivedPerception()}#prepareDerivedPerception(){if(!(this.rulesBasedVision&&this.actor&&this.scene&&this.sight.enabled))return;const visionMode=this.hasDarkvision?"darkvision":"basic";this.sight.visionMode=visionMode;const{defaults}=CONFIG.Canvas.visionModes[visionMode].vision;if(this.sight.brightness=defaults.brightness??0,this.sight.saturation=defaults.saturation??0,visionMode==="darkvision"||this.scene.lightLevel>LightLevels.DARKNESS){const basicDetection=this.detectionModes.at(0);if(!basicDetection)return;this.sight.range=basicDetection.range=defaults.range??0,this.actor.isOfType("character")&&this.actor.flags.pf2e.colorDarkvision?this.sight.saturation=1:game.user.settings.monochromeDarkvision||(this.sight.saturation=0)}this.actor.isOfType("character","familiar")&&this.actor.system.traits.senses.some(s=>s.type==="seeInvisibility")&&this.detectionModes.push({id:"seeInvisibility",enabled:!0,range:1e3});const tremorsense=this.actor.isOfType("character")?this.actor.system.traits.senses.find(s=>s.type==="tremorsense"&&s.acuity!=="vague"):null;if(tremorsense&&this.detectionModes.push({id:"feelTremor",enabled:!0,range:tremorsense.range}),!this.actor.hasCondition("deafened")){const range2=this.scene.flags.pf2e.hearingRange??canvas.dimensions?.maxR??1/0;this.detectionModes.push({id:"hearing",enabled:!0,range:range2})}}static assignDefaultImage(token){const{actor}=token;if(!actor)return;const defaultIcons=[ActorPF2e.DEFAULT_ICON,`systems/pf2e/icons/default-icons/${actor.type}.svg`];game.pf2e.settings.tokens.nathMode&&defaultIcons.includes(token.texture.src)?token.texture.src=(()=>{switch(actor.alliance){case"party":return"systems/pf2e/icons/default-icons/alternatives/nath/ally.webp";case"opposition":return"systems/pf2e/icons/default-icons/alternatives/nath/enemy.webp";default:return token.texture.src}})():defaultIcons.some(path=>token.texture.src?.endsWith(path))&&(token.texture.src=actor._source.img)}static prepareSize(token){const{actor}=token;if(!(actor&&token.flags.pf2e.linkToActorSize))return;const size={tiny:.5,sm:1,med:1,lg:2,huge:3,grg:Math.max(token.width,4)}[actor.size];if(actor.isOfType("vehicle")){const{width,height}=actor.getTokenDimensions();token.width=width,token.height=height}else if(token.width=size,token.height=size,game.pf2e.settings.tokens.autoscale&&token.flags.pf2e.autoscale!==!1){const absoluteScale=actor.size==="sm"?.8:1,mirrorX=token.texture.scaleX<0?-1:1;token.texture.scaleX=mirrorX*absoluteScale;const mirrorY=token.texture.scaleY<0?-1:1;token.texture.scaleY=mirrorY*absoluteScale}}async setInitiative({initiative,sendMessage=!0}){if(!game.combat){ui.notifications.error("PF2E.Encounter.NoActiveEncounter");return}const currentId=game.combat.combatant?.id;this.combatant&&game.combat.combatants.has(this.combatant.id)?await game.combat.setInitiative(this.combatant.id,initiative):await game.combat.createEmbeddedDocuments("Combatant",[{tokenId:this.id,initiative}]),await this.update({turn:game.combat.turns.findIndex(c=>c.id===currentId)}),sendMessage&&await ChatMessagePF2e.createDocuments([{speaker:{scene:this.scene?.id,token:this.id},whisper:this.actor?.hasPlayerOwner?[]:game.users.contents.flatMap(user=>user.isGM?user.id:[]),content:game.i18n.format("PF2E.InitiativeIsNow",{name:this.name,value:initiative})}])}simulateUpdate(actorUpdates={}){if(!this.scene?.isInFocus&&!this.scene?.isView)return;const initializeVision=!!this.scene?.isView&&this.sight.enabled&&Object.keys(foundry.utils.flattenObject(actorUpdates)).some(k=>k.startsWith("system.traits.senses"));initializeVision&&canvas.perception.update({initializeVision},!0);const preUpdate=this.toObject(!1),preUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"]));this.reset();const postUpdate=this.toObject(!1),postUpdateAuras=Array.from(this.auras.values()).map(a=>omit(a,["appearance","token"])),tokenChanges=foundry.utils.diffObject(preUpdate,postUpdate);this.scene?.isView&&Object.keys(tokenChanges).length>0&&this.object?._onUpdate(tokenChanges,{},game.user.id);const aurasChanged=__name2(()=>!!this.scene?.isInFocus&&!equals(preUpdateAuras,postUpdateAuras),"aurasChanged");("disposition"in tokenChanges||"width"in tokenChanges||"height"in tokenChanges||aurasChanged())&&this.scene?.checkAuras?.()}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user.id===userId&&this.actor?.isOfType("loot")&&this.actor.toggleTokenHiding()}_onUpdate(changed,options,userId){const tokenSetsNameVisibility=game.pf2e.settings.tokens.nameVisibility;return"displayName"in changed&&tokenSetsNameVisibility&&this.combatant&&ui.combat.render(),changed.actorLink===!1&&this.rendered&&this.object?.controlled&&this.object.release(),super._onUpdate(changed,options,userId)}_onRelatedUpdate(update={},options={}){super._onRelatedUpdate(update,options),this.simulateUpdate(update)}_onDelete(options,userId){if(super._onDelete(options,userId),!!this.actor)if(this.isLinked)this.scene?.tokens.some(t=>t.actor===this.actor)||this.actor.checkAreaEffects();else for(const effect of this.actor.itemTypes.effect)game.pf2e.effectTracker.unregister(effect)}}class UserVisibilityPF2e{static{__name(this,"UserVisibilityPF2e")}static{__name2(this,"UserVisibilityPF2e")}static process(html,options={}){const visibilityElements=htmlQueryAll(html,"[data-visibility]");for(const element of visibilityElements.filter(e=>e.dataset.visibility==="none"))element.remove();const{message}=options,document2=options.document??message?.actor??message?.journalEntry??message??null;if(document2){const ownerElements=visibilityElements.filter(e=>e.dataset.visibility==="owner");for(const element of ownerElements){if(element.dataset.action){document2.isOwner||element.remove(),delete element.dataset.visibility;continue}const whoseData=element.dataset.whose??"self";if(whoseData==="self"){element.dataset.visibility=document2.hasPlayerOwner?"all":"gm";continue}message?.target&&whoseData==="target"&&(element.dataset.visibility=message.target.actor.hasPlayerOwner?"all":"gm")}}const hasOwnership=document2?.isOwner??game.user.isGM,dcSetting=game.settings.get("pf2e","metagame_showDC"),saveButtons=htmlQueryAll(html,"button[data-action=save]");if(!document2?.hasPlayerOwner&&!hasOwnership&&!dcSetting)for(const button of saveButtons){const saveType=button.dataset.save;if(objectHasKey(CONFIG.PF2E.saves,saveType)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]);button.innerText=game.i18n.format("PF2E.SavingThrowWithName",{saveName})}}else if(!document2?.hasPlayerOwner&&!dcSetting)for(const button of saveButtons)button.classList.add("hidden-to-others");for(const element of htmlQueryAll(html,"[data-owner-title]"))if(hasOwnership){const value=element.dataset.ownerTitle??"";element.title=value}else element.removeAttribute("data-owner-title");if(!game.user.isGM)for(const element of visibilityElements.filter(e=>e.dataset.visibility==="gm"))element.remove()}static processMessageSender(message,html){if(!game.pf2e.settings.tokens.nameVisibility)return;const token=message.token??(message.actor?new TokenDocumentPF2e(message.actor.prototypeToken.toObject()):null);if(token){const sender=html.querySelector("h4.message-sender"),nameToHide=token.name.trim(),shouldHideName=!token.playersCanSeeName&&sender?.innerText.trim()===nameToHide;sender&&shouldHideName&&(game.user.isGM?sender.dataset.visibility="gm":sender.innerText=message.user?.name??"Gamemaster")}}}const USER_VISIBILITIES=new Set(["all","owner","gm","none"]);class CheckRoll extends Roll{static{__name(this,"CheckRoll")}static{__name2(this,"CheckRoll")}static CHAT_TEMPLATE="systems/pf2e/templates/chat/check/roll.hbs";get roller(){return game.users.get(this.options.rollerId??"")??null}get type(){return this.options.type??"check"}get degreeOfSuccess(){return this.options.degreeOfSuccess??null}get isReroll(){return this.options.isReroll??!1}get isRerollable(){return!this.isReroll&&!this.dice.some(d=>d.modifiers.includes("kh")||d.modifiers.includes("kl"))}async render(options={}){this._evaluated||await this.evaluate({async:!0});const{isPrivate,flavor,template}=options,{type,identifier,action:action2,damaging}=this.options,canRollDamage=!!(damaging&&identifier&&(this.roller===game.user||game.user.isGM)),limitCueVisibility=!game.settings.get("pf2e","metagame_showResults"),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,type,identifier,action:action2,degree:this.degreeOfSuccess,canRollDamage,limitCueVisibility};return renderTemplate(template??CheckRoll.CHAT_TEMPLATE,chatData)}}class StrikeAttackRoll extends CheckRoll{static{__name(this,"StrikeAttackRoll")}static{__name2(this,"StrikeAttackRoll")}}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??traits),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");function getAdjustment(value,base,{better="higher"}={}){return value===base?null:(better==="higher"?value>base:value<base)?"adjusted-higher":"adjusted-lower"}__name(getAdjustment,"getAdjustment"),__name2(getAdjustment,"getAdjustment");function getAdjustedValue(value,reference,options){const adjustmentClass=getAdjustment(value,reference,options);return{value,adjustmentClass,adjustedHigher:adjustmentClass==="adjusted-higher",adjustedLower:adjustmentClass==="adjusted-lower"}}__name(getAdjustedValue,"getAdjustedValue"),__name2(getAdjustedValue,"getAdjustedValue");async function maintainFocusInRender(sheet,renderLogic){const element=sheet.element.get(0),{activeElement}=document,activeWasHere=element?.contains(activeElement);if(await renderLogic(),!(!activeElement||!activeWasHere)){if(activeElement instanceof HTMLInputElement&&activeElement.dataset.property)htmlQuery(element,`input[data-property="${activeElement.dataset.property}"]`)?.focus();else if(activeElement.classList.contains("tagify__input")){const name2=htmlClosest(activeElement,"tags")?.dataset.name;name2&&htmlQuery(element,`tags[data-name="${name2}"] span[contenteditable]`)?.focus()}}}__name(maintainFocusInRender,"maintainFocusInRender"),__name2(maintainFocusInRender,"maintainFocusInRender");class BaseTagSelector extends DocumentSheet{static{__name(this,"BaseTagSelector")}static{__name2(this,"BaseTagSelector")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"tag-selector",classes:["pf2e","tag-selector"],sheetConfig:!1,width:"auto"})}choices;flat;constructor(document2,options={}){super(document2,options),this.flat=options.flat??!1,this.choices=this.#getChoices()}get id(){return`${this.options.id}-${this.document.uuid}`}get title(){return game.i18n.localize(this.options.title||"PF2E.TraitsLabel")}async getData(options){return{...await super.getData(options),documentType:this.document.constructor.metadata.label}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input:not([type=checkbox])"))input.addEventListener("focusin",()=>{input.select()})}#getChoices(){const choices=this.configTypes.reduce((types,key)=>foundry.utils.mergeObject(types,CONFIG.PF2E[key]),{});return this.sortChoices(choices)}sortChoices(choices){return Object.entries(choices).map(([key,value])=>[key,game.i18n.localize(value)]).sort(([_keyA,valueA],[_keyB,valueB])=>valueA.localeCompare(valueB)).reduce((accumulated,[key,value])=>foundry.utils.mergeObject(accumulated,{[key]:value}),{})}}function isValuesList(value){return!!(value&&typeof value=="object"&&"value"in value)}__name(isValuesList,"isValuesList"),__name2(isValuesList,"isValuesList");class TagSelectorBasic extends BaseTagSelector{static{__name(this,"TagSelectorBasic")}static{__name2(this,"TagSelectorBasic")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/tag-selector/basic.hbs"})}allowCustom;#filterTimeout=null;objectProperty;constructor(document2,options){super(document2,options),this.objectProperty=options.objectProperty,this.allowCustom=options.allowCustom??!0,options.customChoices&&(foundry.utils.mergeObject(this.choices,options.customChoices),this.choices=this.sortChoices(this.choices))}get configTypes(){return this.options.configTypes??[]}async getData(options){const{chosen,custom,flat,disabled}=(()=>{const document2=this.document,sourceProperty=foundry.utils.getProperty(document2.toObject(),this.objectProperty),preparedProperty=foundry.utils.getProperty(document2,this.objectProperty);if(Array.isArray(preparedProperty)){const manuallyChosen=Array.isArray(sourceProperty)?sourceProperty.map(prop=>String(prop)):[],automaticallyChosen=preparedProperty.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:null,flat:!0,disabled:automaticallyChosen}}else if(isValuesList(preparedProperty)&&isValuesList(sourceProperty)){const manuallyChosen=sourceProperty.value.map(prop=>prop.toString()),custom2=this.allowCustom?sourceProperty.custom:null,automaticallyChosen=preparedProperty.value.filter(tag=>!manuallyChosen.includes(tag));return{chosen:Array.from(new Set([...manuallyChosen,...automaticallyChosen])),custom:custom2,flat:!1,disabled:automaticallyChosen}}else return{chosen:[],custom:null,flat:this.flat,disabled:[]}})(),choices=Object.keys(this.choices).reduce((accumulated,type)=>(accumulated[type]={label:this.choices[type],selected:chosen.includes(type),disabled:disabled.includes(type)},accumulated),{});return{...await super.getData(options),choices,allowCustom:this.allowCustom&&!flat,custom,flat}}activateListeners($html){super.activateListeners($html);const html=$html[0],searchInput=htmlQuery(html,"input[type=search]");searchInput?.addEventListener("input",()=>{this.#onFilterResults(searchInput)})}async _updateObject(event2,formData){const flat=event2.target instanceof HTMLElement?event2.target.dataset.flat:!1,value=this.#getUpdateData(formData);return this.allowCustom&&typeof formData.custom=="string"?super._updateObject(event2,{[this.objectProperty]:{value,custom:formData.custom}}):flat?super._updateObject(event2,{[this.objectProperty]:value}):super._updateObject(event2,{[`${this.objectProperty}.value`]:value})}#getUpdateData(formData){const optionsAreNumeric=Object.keys(formData).every(tag=>Number.isInteger(Number(tag))),selections=Object.entries(formData).flatMap(([tag,selected])=>selected?tag:[]).filter(tag=>tag!=="custom");return optionsAreNumeric?selections.map(tag=>Number(tag)):selections}#search(searchString){const query=new RegExp(RegExp.escape(searchString),"i"),html=this.element[0];for(const row of htmlQueryAll(html,"li.trait-item")){const name2=row.getElementsByClassName("trait-label")[0]?.textContent??"";row.style.display=query.test(name2)?"flex":"none"}}#onFilterResults(input){this.#filterTimeout&&(clearTimeout(this.#filterTimeout),this.#filterTimeout=null),this.#filterTimeout=window.setTimeout(()=>this.#search(input.value),100)}}class SenseSelector extends BaseTagSelector{static{__name(this,"SenseSelector")}static{__name2(this,"SenseSelector")}objectProperty="system.traits.senses";static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{height:"auto",template:"systems/pf2e/templates/system/tag-selector/senses.hbs",id:"sense-selector",title:"PF2E.Actor.Creature.Sense.Label"})}get configTypes(){return["senses"]}async getData(options){if(!this.document.isOfType("character"))throw ErrorPF2e("The Sense selector is usable only with PCs");const senses2=this.document.system.traits.senses,choices=Object.entries(this.choices).reduce((accum,[type,label])=>{const sense=senses2.find(sense2=>sense2.type===type),mandatoryAcuity=objectHasKey(SENSES_WITH_MANDATORY_ACUITIES,type),acuity=mandatoryAcuity?SENSES_WITH_MANDATORY_ACUITIES[type]:sense?.acuity??"precise";return{...accum,[type]:{acuity,mandatoryAcuity,disabled:!!sense?.source,label,selected:!!sense,value:sense?.value??""}}},{});return{...await super.getData(options),hasExceptions:!1,choices,senseAcuity:CONFIG.PF2E.senseAcuity}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&input.addEventListener("input",()=>{checkbox.checked=!!Number(input.value)})}}_onSubmit(event2,options){for(const input of htmlQueryAll(this.element[0],"input[type=number]")){const checkbox=htmlQuery(htmlClosest(input,"tr"),"input[type=checkbox]");checkbox&&!Number(input.value)&&(checkbox.checked=!1)}return super._onSubmit(event2,options)}async _updateObject(event2,formData){const update=Object.entries(formData).filter(e=>e[1]===!0||Array.isArray(e[1])&&e[1][0]).map(([type,values])=>{if(values===!0)return{type};if(Number(values[2])){const acuity=values[1],range2=Number(values[2]);return{type,acuity,value:range2}}else{const acuity=values[1];return{type,acuity}}});return super._updateObject(event2,{[this.objectProperty]:update})}}class SpeedSelector extends BaseTagSelector{static{__name(this,"SpeedSelector")}static{__name2(this,"SpeedSelector")}objectProperty="system.attributes.speed.otherSpeeds";static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"speed-selector",template:"systems/pf2e/templates/system/tag-selector/speeds.hbs",title:"PF2E.SpeedTypes"})}get configTypes(){return["speedTypes"]}async getData(options){if(!this.document.isOfType("creature"))throw ErrorPF2e("The Speed selector is usable only with creature-type actors");const speeds=this.document.system.attributes.speed.otherSpeeds,speedLabels=CONFIG.PF2E.speedTypes,choices=Object.keys(this.choices).reduce((accum,type)=>{const speed=speeds.find(s=>s.type===type);return{...accum,[type]:{selected:!!speed,disabled:!!speed?.source,label:game.i18n.localize(speedLabels[type]),value:Number(speed?.value)||""}}},{});return{...await super.getData(options),hasExceptions:this.document.isOfType("npc"),choices}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const input of htmlQueryAll(html,"input[type=number]"))input.addEventListener("input",()=>{const checkbox=input.closest("li")?.querySelector("input[type=checkbox]");checkbox&&(checkbox.checked=!!Number(input.value))})}async _updateObject(event2,formData){const update=Object.entries(formData).flatMap(([key,value])=>{if(!(Array.isArray(value)&&value.length===2))return[];const selected=!!value[0],distance=Math.trunc(Math.abs(value[1]));return selected&&distance?{type:key,value:Math.max(distance,5)}:[]});return super._updateObject(event2,{[this.objectProperty]:update})}}const TAG_SELECTOR_TYPES=["basic","senses","speed-types"],SELECTABLE_TAG_FIELDS=["abilities","actionTraits","attackEffects","creatureTraits","damageCategories","languages","levels","materialDamageEffects","otherArmorTags","otherConsumableTags","otherWeaponTags","senses","skills","speedTypes","vehicleTraits","weaponTraits"];class UUIDUtils{static{__name(this,"UUIDUtils")}static{__name2(this,"UUIDUtils")}static async fromUUIDs(uuids,options){const resolvedUUIDs=uniq(uuids).flatMap(u=>foundry.utils.parseUuid(u,options).uuid??[]),packEmbeddedLinks=resolvedUUIDs.filter(u=>{const parsed=foundry.utils.parseUuid(u,options);return parsed.collection instanceof CompendiumCollection&&parsed.embedded.length>0}),packEmbeddedDocs=compact(await Promise.all(packEmbeddedLinks.map(u=>fromUuid(u)))),documentsAndIndexData=compact(resolvedUUIDs.filter(u=>!packEmbeddedLinks.includes(u)).map(u=>fromUuidSync(u))),worldDocsAndCacheHits=documentsAndIndexData.filter(d=>d instanceof foundry.abstract.Document),indexEntries=documentsAndIndexData.filter(d=>!(d instanceof foundry.abstract.Document)),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);return pack.getDocuments({_id__in:ids})}))).flat();return sortBy([...packEmbeddedDocs,...worldDocsAndCacheHits,...packDocs],d=>uuids.indexOf(d.uuid))}static isItemUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).documentType==="Item"}static isCompendiumUUID(uuid){return typeof uuid=="string"&&foundry.utils.parseUuid(uuid).collection instanceof CompendiumCollection}static isTokenUUID(uuid){if(typeof uuid!="string")return!1;const parsed=foundry.utils.parseUuid(uuid);return parsed.documentType==="Scene"&&parsed.embedded[0]==="Token"}}class ActorSizePF2e{static{__name(this,"ActorSizePF2e")}static{__name2(this,"ActorSizePF2e")}value;length;width;static defaultSpaces={tiny:{length:2.5,width:2.5},sm:{length:5,width:5},med:{length:5,width:5},lg:{length:10,width:10},huge:{length:15,width:15},grg:{length:20,width:20}};static sizeRanks={grg:5,huge:4,lg:3,med:2,sm:1,tiny:0};constructor(params){(typeof params.value!="string"||params.smallIsMedium&¶ms.value==="sm")&&(params.value="med"),this.value=params.value;const spaces=ActorSizePF2e.defaultSpaces[params.value]??ActorSizePF2e.defaultSpaces.med;this.length=params.length??spaces.length,this.width=params.width??spaces.width}equals(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return thisSize===otherSize}isLargerThan(size,{smallIsMedium=!1}={}){const other=size instanceof ActorSizePF2e?size:new ActorSizePF2e({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return ActorSizePF2e.sizeRanks[thisSize]>ActorSizePF2e.sizeRanks[otherSize]}isSmallerThan(size,{smallIsMedium=!1}={}){const other=size instanceof ActorSizePF2e?size:new ActorSizePF2e({value:size}),thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(other.value,{smallIsMedium});return ActorSizePF2e.sizeRanks[thisSize]<ActorSizePF2e.sizeRanks[otherSize]}difference(size,{smallIsMedium=!1}={}){const thisSize=this.getEffectiveSize(this.value,{smallIsMedium}),otherSize=this.getEffectiveSize(size.value,{smallIsMedium});return ActorSizePF2e.sizeRanks[thisSize]-ActorSizePF2e.sizeRanks[otherSize]}getEffectiveSize(size,{smallIsMedium}){return smallIsMedium&&size==="sm"?"med":size}increment({skipSmall=!1}={}){this.value=this.value==="tiny"&&skipSmall?"med":this.value==="sm"&&skipSmall?"lg":this.value==="grg"?"grg":SIZES[SIZES.indexOf(this.value)+1];const newSpace=ActorSizePF2e.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}decrement({skipSmall=!1}={}){const toTiny=this.value==="med"&&skipSmall||this.value==="tiny";this.value=toTiny?"tiny":SIZES[SIZES.indexOf(this.value)-1];const newSpace=ActorSizePF2e.defaultSpaces[this.value];this.length=newSpace.length,this.width=newSpace.width}toString(){return game.i18n.localize(CONFIG.PF2E.actorSizes[this.value])}}function onClickCreateSpell(actor,data){if(!data.location)throw ErrorPF2e("Unexpected missing spellcasting-entry location");const rank=Number(data.level??1),newLabel=game.i18n.localize("PF2E.NewLabel"),[rankLabel,spellLabel]=rank>0?[game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),game.i18n.localize(data.location==="rituals"?"PF2E.Item.Spell.Ritual.Label":"TYPES.Item.spell")]:[null,game.i18n.localize("PF2E.TraitCantrip")],source={type:"spell",name:compact([newLabel,rankLabel,spellLabel]).join(" "),system:{level:{value:rank||1},location:{value:String(data.location)},traits:{value:rank===0?["cantrip"]:[]}}};data.location==="rituals"&&(source.system=foundry.utils.mergeObject(source.system,{category:{value:"ritual"}})),actor.createEmbeddedDocuments("Item",[source])}__name(onClickCreateSpell,"onClickCreateSpell"),__name2(onClickCreateSpell,"onClickCreateSpell");class ItemSummaryRenderer{static{__name(this,"ItemSummaryRenderer")}static{__name2(this,"ItemSummaryRenderer")}sheet;constructor(sheet){this.sheet=sheet}async toggleSummary(element,options={}){if(element.dataset.itemType==="spellSlot")return;const duration=.4,item=await this.getItemFromElement(element),summaryElem=await(async()=>{const container=htmlQuery(element,".item-summary");if(container?.hasChildNodes())return container;if(!container||!(item instanceof ItemPF2e))return null;const chatData=await item.getChatData({secrets:item.isOwner},element.dataset);return await this.renderItemSummary(container,item,chatData),InlineRollLinks.listen(container,item),container})();if(!summaryElem)return;const showSummary=options.visible??summaryElem.hidden;options.instant?summaryElem.hidden=!showSummary:showSummary?await gsap.fromTo(summaryElem,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration}):await gsap.to(summaryElem,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{summaryElem.hidden=!0}})}async getItemFromElement(element){const actor=this.sheet.actor,{itemId,itemType,actionIndex}=element.dataset;return!!element.dataset.isFormula?await fromUuid(itemId??""):itemType==="condition"?actor.conditions.get(itemId,{strict:!0}):actionIndex?actor.system.actions?.[Number(actionIndex)].item??null:actor.items.get(itemId??"")??null}async renderItemSummary(container,item,chatData){const description=isItemSystemData(chatData)?chatData.description.value:await TextEditor.enrichHTML(item.description,{rollData:item.getRollData(),async:!0}),rarity=item.system.traits?.rarity,isEffect=item instanceof AbstractEffectPF2e,selfEffect=item.isOfType("action","feat")&&item.system.selfEffect?await TextEditor.enrichHTML(`@UUID[${item.system.selfEffect.uuid}]{${item.system.selfEffect.name}}`,{async:!0}):null,summary=await renderTemplate("systems/pf2e/templates/actors/partials/item-summary.hbs",{item,description,identified:game.user.isGM||!(item.isOfType("physical")||isEffect)||item.isIdentified,rarityLabel:rarity&&item.isOfType("physical")?CONFIG.PF2E.rarityTraits[rarity]:null,isCreature:item.actor?.isOfType("creature"),chatData,selfEffect});if(container.innerHTML=summary,UserVisibilityPF2e.process(container,{document:item}),item.actor?.isOfType("creature"))for(const button of htmlQueryAll(container,"button"))button.addEventListener("click",event2=>{event2.preventDefault(),event2.stopPropagation();const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(button.dataset.action){case"spellAttack":spell?.rollAttack(event2);break;case"spellDamage":spell?.rollDamage(event2);break;case"spellTemplate":spell?.placeTemplate();break;case"consume":item.isOfType("consumable")&&item.consume();break}})}async saveAndRestoreState(callback){const html=this.sheet.element[0]??null,elements=htmlQueryAll(html,".item-summary:not([hidden])").flatMap(s=>htmlClosest(s,"[data-item-id], [data-action-index]")??htmlClosest(s,"li")??[]),$result=await callback.apply(null),result=$result[0];if(InlineRollLinks.listen(result,this.sheet.actor),elements.length>0){const selector=elements.map(s=>htmlSelectorFor(s)).join(","),promises=htmlQueryAll(result,selector).map(container=>this.toggleSummary(container,{instant:!0,visible:!0}));await Promise.all(promises)}return $result}}class MoveLootPopup extends FormApplication{static{__name(this,"MoveLootPopup")}static{__name2(this,"MoveLootPopup")}onSubmitCallback;constructor(object,options,callback){super(object,options),this.onSubmitCallback=callback}async getData(){const[prompt,buttonLabel]=this.options.isPurchase?["PF2E.loot.PurchaseLootMessage","PF2E.loot.PurchaseLoot"]:["PF2E.loot.MoveLootMessage","PF2E.loot.MoveLoot"];return{...await super.getData(),quantity:{default:this.options.quantity.default,max:this.options.quantity.max},newStack:this.options.newStack,lockStack:this.options.lockStack,prompt,buttonLabel}}static get defaultOptions(){return{...super.defaultOptions,id:"MoveLootPopup",classes:[],title:game.i18n.localize("PF2E.loot.MoveLootPopupTitle"),template:"systems/pf2e/templates/popups/loot/move-loot-popup.hbs",width:"auto",quantity:{default:1,max:1},newStack:!1,lockStack:!1,isPurchase:!1}}async _updateObject(_event,formData){this.onSubmitCallback(formData.quantity,formData.newStack)}}class AddCoinsPopup extends FormApplication{static{__name(this,"AddCoinsPopup")}static{__name2(this,"AddCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"add-coins",title:"PF2E.AddCoinsTitle",template:"systems/pf2e/templates/actors/add-coins.hbs"}}async _updateObject(_event,formData){const combineStacks=!!formData.combineStacks,coins={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};return this.object.inventory.addCoins(coins,{combineStacks})}}const itemTypeOptions=Object.fromEntries(new Map([["scroll","PF2E.CastingItemCreateDialog.scroll"],["wand","PF2E.CastingItemCreateDialog.wand"],["cantripDeck5","PF2E.CastingItemCreateDialog.cantripDeck5"]]));class CastingItemCreateDialog extends FormApplication{static{__name(this,"CastingItemCreateDialog")}static{__name2(this,"CastingItemCreateDialog")}onSubmitCallback;spell;formDataCache;constructor(object,options,callback,spell){super(object,options),this.spell=spell,this.formDataCache={itemType:this.spell.isCantrip?"cantripDeck5":"scroll",level:spell.baseRank},this.onSubmitCallback=callback}static get defaultOptions(){const options=super.defaultOptions;return options.classes=[],options.title=game.i18n.localize("PF2E.CastingItemCreateDialog.title"),options.template="systems/pf2e/templates/popups/casting-item-create-dialog.hbs",options.width="auto",options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){if(!this.spell)throw ErrorPF2e("CastingItemCreateDialog | Could not read spelldata");const{cantripDeck5,...nonCantripOptions}=itemTypeOptions,minimumRank=this.spell.baseRank,ranks=Array.from(Array(11-minimumRank).keys()).map(index=>minimumRank+index);return{...await super.getData(),validLevels:ranks,itemTypeOptions:this.spell.isCantrip?{cantripDeck5}:nonCantripOptions,itemType:this.formDataCache.itemType,level:this.formDataCache.level}}async _updateObject(event2,formData){if(Object.assign(this.formDataCache,formData),event2.type!=="submit"){await this.render();return}this.formDataCache.itemType==="wand"&&this.formDataCache.level===10?ui.notifications.warn(game.i18n.localize("PF2E.CastingItemCreateDialog.10thLevelWand")):this.onSubmitCallback&&this.spell&&this.onSubmitCallback(this.formDataCache.level,this.formDataCache.itemType,this.spell),this.close()}}function getMagicTraditions(item){const traits=item.system.traits.value;return new Set(traits.filter(t=>setHasElement(MAGIC_TRADITIONS,t)))}__name(getMagicTraditions,"getMagicTraditions"),__name2(getMagicTraditions,"getMagicTraditions");function getDcRarity(item){return item.traits.has("cursed")?"unique":item.rarity}__name(getDcRarity,"getDcRarity"),__name2(getDcRarity,"getDcRarity");function getIdentifyMagicDCs(item,baseDC,notMatchingTraditionModifier){const result={occult:baseDC,primal:baseDC,divine:baseDC,arcane:baseDC},traditions=getMagicTraditions(item);for(const key of MAGIC_TRADITIONS)traditions.size>0&&!traditions.has(key)&&(result[key]=baseDC+notMatchingTraditionModifier);return{arcana:result.arcane,nature:result.primal,religion:result.divine,occultism:result.occult}}__name(getIdentifyMagicDCs,"getIdentifyMagicDCs"),__name2(getIdentifyMagicDCs,"getIdentifyMagicDCs");function getItemIdentificationDCs(item,{pwol=!1,notMatchingTraditionModifier}){const baseDC=calculateDC(item.level,{pwol}),rarity=getDcRarity(item),dc=adjustDCByRarity(baseDC,rarity);return item.isMagical?getIdentifyMagicDCs(item,dc,notMatchingTraditionModifier):item.isAlchemical?{crafting:dc}:{dc}}__name(getItemIdentificationDCs,"getItemIdentificationDCs"),__name2(getItemIdentificationDCs,"getItemIdentificationDCs");function getUnidentifiedPlaceholderImage(item){return`systems/pf2e/icons/unidentified_item_icons/${(()=>{if(item.isOfType("weapon")){const{traits}=item;return traits.has("bomb")?"alchemical_bomb":traits.has("staff")?"staves":traits.has("artifact")?"artifact":"weapon"}else{if(item.isOfType("armor"))return"armor";if(item.isOfType("shield"))return"shields";if(item.isOfType("consumable"))switch(item.category){case"ammo":return"ammunition";case"oil":return"oils";case"scroll":return"infernal-contracts";case"talisman":return"talisman";case"elixir":case"mutagen":return"alchemical_elixir";case"poison":return"alchemical_poison";case"toolkit":return"alchemical_tool";case"wand":return"wands";case"potion":return"potions";case"snare":case"other":default:return item.traits.has("drug")?"drugs":"other-consumables"}else if(item.isOfType("equipment")&&item.traits.has("precious"))return"material-chunk"}return"adventuring_gear"})()}.webp`}__name(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage"),__name2(getUnidentifiedPlaceholderImage,"getUnidentifiedPlaceholderImage");class IdentifyItemPopup extends FormApplication{static{__name(this,"IdentifyItemPopup")}static{__name2(this,"IdentifyItemPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"identify-item",title:game.i18n.localize("PF2E.identification.Identify"),template:"systems/pf2e/templates/actors/identify-item.hbs",width:"auto",classes:["identify-popup"]}}get item(){return this.object}async getData(){const item=this.object,notMatchingTraditionModifier=game.settings.get("pf2e","identifyMagicNotMatchingTraditionModifier"),pwol=game.pf2e.settings.variants.pwol.enabled,dcs=getItemIdentificationDCs(item,{pwol,notMatchingTraditionModifier});return{...await super.getData(),isMagic:item.isMagical,isAlchemical:item.isAlchemical,dcs}}activateListeners($form){$form.find("button.update-identification").on("click",event2=>{const $button=$(event2.delegateTarget);this.submit({updateData:{status:$button.val()}})}),$form.find("button.post-skill-checks").on("click",async()=>{const item=this.item,itemImg=item.system.identification.unidentified.img,itemName=item.system.identification.unidentified.name,identifiedName=item.system.identification.identified.name,skills=$("div#identify-item").find("tr").toArray().flatMap(row=>{const slug=row.dataset.skill,dc=Number(row.dataset.dc);if(!(Number.isInteger(dc)&&objectHasKey(CONFIG.PF2E.skillList,slug)))return[];const name2=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return{slug,name:name2,dc}}),actionOption=item.isMagical?"action:identify-magic":item.isAlchemical?"action:identify-alchemy":null,content=await renderTemplate("systems/pf2e/templates/actors/identify-item-chat-skill-checks.hbs",{itemImg,itemName,identifiedName,rollOptions:compact(["concentrate","exploration","secret",actionOption]),skills});await ChatMessagePF2e.create({user:game.user.id,content})})}async _updateObject(_event,formData){const status=formData.status;status==="identified"&&await this.item.setIdentificationStatus(status)}}class IWREditor extends DocumentSheet{static{__name(this,"IWREditor")}static{__name2(this,"IWREditor")}category;types;constructor(actor,options){if(super(actor,options),this.actor.isOfType("familiar","loot"))throw ErrorPF2e(`Actor ${this.actor.name} (${this.actor.uuid}) may not have stored IWR data`);this.category=options.category,this.types={immunities:omit(CONFIG.PF2E.immunityTypes,["custom"]),weaknesses:omit(CONFIG.PF2E.weaknessTypes,["custom"]),resistances:omit(CONFIG.PF2E.resistanceTypes,["custom"])}[this.category]}static get defaultOptions(){return{...super.defaultOptions,closeOnSubmit:!1,classes:["iwr-editor"],template:"systems/pf2e/templates/actors/iwr-editor.hbs",sheetConfig:!1,width:500,height:"auto"}}get id(){return`${this.category}-editor-${this.actor.uuid}`}get title(){return game.i18n.format("PF2E.Actor.IWREditor.Title",{actor:this.actor.name,category:game.i18n.localize(this.categoryLabel)})}get actor(){return this.document}get categoryLabel(){return{immunities:"PF2E.ImmunitiesLabel",weaknesses:"PF2E.WeaknessesLabel",resistances:"PF2E.ResistancesLabel"}[this.category]}async getData(options={}){return this.options.id=this.id,{...await super.getData(options),category:this.category,header:this.categoryLabel,list:this.actor.attributes[this.category],sourceData:this.actor._source.system.attributes?.[this.category]??[],types:this.types}}getUpdatedData({includeNew=!1}={}){const entryElems=htmlQueryAll(this.element[0],".entry:not(.new,[data-synthetic])");return includeNew&&entryElems.push(...htmlQueryAll(this.element[0],".entry.new")),entryElems.flatMap(entryElem=>{const iwrType=htmlQuery(entryElem,"select")?.value;if(!iwrType)return[];const value=Math.trunc(Math.abs(Number(htmlQuery(entryElem,"input[data-property=value]")?.value??"NaN")))||5,exceptionsData=JSON.parse(htmlQuery(entryElem,"input[data-property=exceptions]")?.value||"[]");if(!(Array.isArray(exceptionsData)&&exceptionsData.every(o=>isObject(o))))throw ErrorPF2e("Unexpected data encountered while submitting form");const exceptions=exceptionsData.map(e=>e.id),doubleVsData=JSON.parse(htmlQuery(entryElem,"input[data-property=doubleVs]")?.value||"[]"),doubleVs=Array.isArray(doubleVsData)&&doubleVsData.every(o=>isObject(o)&&typeof o.id=="string"&&o.id in this.types)&&this.category==="resistances"?doubleVsData.map(d=>d.id):void 0;return exceptions.every(e=>typeof e=="string")?{type:iwrType,value:this.category==="immunities"?void 0:value||1,exceptions,doubleVs}:[]})}async#updateIWR({includeNew=!1}={}){const data=this.getUpdatedData({includeNew}),formInput=htmlQuery(this.element[0],"input[name]");if(!formInput)throw ErrorPF2e("Unexpected error getting for input element");formInput.value=JSON.stringify(data),await this.submit({preventRender:!1})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}activateListeners($html){const html=$html[0];for(const input of htmlQueryAll(html,"input[type=text]"))tagify(input,{whitelist:this.types,maxTags:4});htmlQuery(html,"a[data-action=add]")?.addEventListener("click",event2=>{const entryElem=htmlClosest(event2.target,".entry.new");htmlQuery(entryElem,"select[data-property=type]")?.value&&this.#updateIWR({includeNew:!0})});for(const inputOrSelect of htmlQueryAll(html,"select, input")){const entryElem=htmlClosest(inputOrSelect,".entry");entryElem&&!entryElem.classList.contains("new")&&inputOrSelect.addEventListener("change",()=>{this.#updateIWR()})}for(const removeButton of htmlQueryAll(html,"a[data-action=remove]"))removeButton.addEventListener("click",async event2=>{htmlClosest(event2.target,".entry")?.remove(),this.#updateIWR()})}}class RemoveCoinsPopup extends FormApplication{static{__name(this,"RemoveCoinsPopup")}static{__name2(this,"RemoveCoinsPopup")}static get defaultOptions(){return{...super.defaultOptions,id:"remove-coins",title:"PF2E.RemoveCoinsTitle",template:"systems/pf2e/templates/actors/remove-coins.hbs"}}async _updateObject(_event,formData){const actor=this.object,coinsToRemove={pp:Number(formData.pp)||0,gp:Number(formData.gp)||0,sp:Number(formData.sp)||0,cp:Number(formData.cp)||0};await actor.inventory.removeCoins(coinsToRemove,{byValue:!!formData.removeByValue})||ui.notifications.warn("PF2E.ErrorMessage.NotEnoughCoins",{localize:!0})}}class ActorSheetPF2e extends ActorSheet{static{__name(this,"ActorSheetPF2e")}static{__name2(this,"ActorSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop=[{dragSelector:"[data-foundry-list] .drag-handle"},{dragSelector:"ul[data-loot] li[data-item-id]"},{dragSelector:".item-list .item:not(.inventory-list *)"}],foundry.utils.mergeObject(options,{classes:["default","sheet","actor"],scrollY:[".sheet-sidebar",".tab.active",".inventory-list"]})}itemRenderer=new ItemSummaryRenderer(this);get isLootSheet(){return!1}async getData(options=this.options){options.id||=this.id,options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Actor.sheetClasses[this.actor.type]).filter(c=>c.canConfigure).length>1;for(const item of[...this.actor.itemTypes.action,...this.actor.itemTypes.feat])item.system.selfEffect&&(item.system.selfEffect.img??=fromUuidSync(item.system.selfEffect.uuid)?.img??null);const actorData=this.actor.toObject(!1),iwrKeys=["immunities","weaknesses","resistances"],attributes=actorData.system.attributes;for(const key of iwrKeys)attributes[key]=[...attributes[key]].sort((a,b)=>a.label.localeCompare(b.label));const coins=this.actor.inventory.coins,totalCoinage=ActorSheetPF2e.coinsToSheetData(coins),totalCoinageGold=(coins.copperValue/100).toFixed(2),totalWealth=this.actor.inventory.totalWealth,totalWealthGold=(totalWealth.copperValue/100).toFixed(2),traitsMap=(()=>{switch(this.actor.type){case"hazard":return CONFIG.PF2E.hazardTraits;case"vehicle":return CONFIG.PF2E.vehicleTraits;default:return CONFIG.PF2E.creatureTraits}})(),sheetData={actor:actorData,cssClass:this.actor.isOwner?"editable":"locked",data:actorData.system,document:this.actor,editable:this.isEditable,effects:[],enrichedContent:{},inventory:this.prepareInventory(),isLootSheet:this.isLootSheet,isTargetFlatFooted:!!this.actor.rollOptions.all["target:condition:off-guard"],items:actorData.items,limited:this.actor.limited,options,owner:this.actor.isOwner,title:this.title,toggles:this.actor.synthetics.toggles,totalCoinage,totalCoinageGold,totalWealth,totalWealthGold,traits:createSheetTags(traitsMap,{value:Array.from(this.actor.traits)}),user:{isGM:game.user.isGM}};return await this.prepareItems?.(sheetData),sheetData}prepareInventory(){const sections=[{label:game.i18n.localize("PF2E.Actor.Inventory.Section.WeaponsAndShields"),types:["weapon","shield"],items:[]},{label:game.i18n.localize("TYPES.Item.armor"),types:["armor"],items:[]},{label:game.i18n.localize("TYPES.Item.equipment"),types:["equipment"],items:[]},{label:game.i18n.localize("PF2E.Item.Consumable.Plural"),types:["consumable"],items:[]},{label:game.i18n.localize("TYPES.Item.treasure"),types:["treasure"],items:[]},{label:game.i18n.localize("PF2E.Item.Container.Plural"),types:["backpack"],items:[]}];for(const item of this.actor.inventory.contents.sort((a,b)=>(a.sort||0)-(b.sort||0)))item.isInContainer||sections.find(s=>s.types.includes(item.type))?.items.push(this.prepareInventoryItem(item));return{sections,bulk:this.actor.inventory.bulk,showValueAlways:this.actor.isOfType("npc","loot","party"),showIndividualPricing:this.actor.isOfType("loot"),hasStowingContainers:this.actor.itemTypes.backpack.some(c=>c.system.stowing&&!c.isInContainer),invested:this.actor.inventory.invested}}prepareInventoryItem(item){const editable=game.user.isGM||item.isIdentified,heldItems=item.isOfType("backpack")?item.contents.map(i=>this.prepareInventoryItem(i)):void 0;heldItems?.sort((a,b)=>(a.item.sort||0)-(b.item.sort||0));const actorSize=new ActorSizePF2e({value:this.actor.size}),itemSize=new ActorSizePF2e({value:item.size}),sizeDifference=itemSize.difference(actorSize,{smallIsMedium:!0}),canBeEquipped=!item.isInContainer;return{item,itemSize:sizeDifference!==0?itemSize:null,editable,isContainer:item.isOfType("backpack"),canBeEquipped,isInvestable:!1,isSellable:editable&&item.isOfType("treasure")&&!item.isCoinage,hasCharges:item.isOfType("consumable")&&item.uses.max>0,heldItems}}static coinsToSheetData(coins){return DENOMINATIONS.reduce((accumulated,d)=>({...accumulated,[d]:{value:coins[d],label:CONFIG.PF2E.currencies[d]}}),{})}getStrikeFromDOM(button,readyOnly=!1){const actionIndex=Number(htmlClosest(button,"[data-action-index]")?.dataset.actionIndex??"NaN"),rootAction=this.actor.system.actions?.at(actionIndex)??null,altUsage=tupleHasValue(["thrown","melee"],button?.dataset.altUsage)?button?.dataset.altUsage:null,strike=altUsage?rootAction?.altUsages?.find(s=>altUsage==="thrown"?s.item.isThrown:s.item.isMelee)??null:rootAction;return strike?.ready||!readyOnly?strike:null}activateListeners($html){super.activateListeners($html);const html=$html[0];this.activateClickListener(html);const inventoryPanel=(()=>{const selector=this.actor.isOfType("loot")?".sheet-body":".tab[data-tab=inventory]";return htmlQuery(html,selector)})();this.activateInventoryListeners(inventoryPanel);const toMessageSelectors=[".item[data-item-id] .item-image",".item[data-item-id] .item-chat","li [data-action=to-message]"];for(const element of htmlQueryAll(html,toMessageSelectors.join(",")))element.addEventListener("click",async event2=>{const itemId=htmlClosest(element,"[data-item-id]")?.dataset.itemId??"",[item,fromFormula]=(()=>{if(UUIDUtils.isItemUUID(itemId)){if("knownFormulas"in this&&isObject(this.knownFormulas)){const formula=this.knownFormulas[itemId];if(formula)return[new ItemProxyPF2e(formula.item.toObject(),{parent:this.actor}),!0]}throw ErrorPF2e(`Invalid UUID [${itemId}]!`)}return[this.actor.items.get(itemId,{strict:!0}),!1]})();(!item.isOfType("physical")||item.isIdentified)&&await item.toMessage(event2,{create:!0,data:{fromFormula}})});if(!this.options.editable)return;const manualPropertyInputs=htmlQueryAll(html,"select[data-property],input[data-property]");for(const input of manualPropertyInputs)input.addEventListener("focus",()=>{const propertyPath=input.dataset.property??"";if(input.name=propertyPath,input instanceof HTMLInputElement){const baseValue=Math.trunc(Number(foundry.utils.getProperty(this.actor._source,propertyPath))||0);input.value=baseValue.toString(),input.type==="text"&&input.dataset.dtype==="Number"&&(input.type="number")}}),input.addEventListener("blur",()=>{input.removeAttribute("name");const propertyPath=input.dataset.property??"",preparedValue=Number(foundry.utils.getProperty(this.actor,propertyPath))||0,baseValue=Math.trunc(Number(foundry.utils.getProperty(this.actor._source,propertyPath))||0),newValue=Math.trunc(Number(input.value));input instanceof HTMLInputElement&&(input.type==="number"&&input.dataset.dtype==="Number"&&(input.type="text"),baseValue===newValue&&(input.value=input.classList.contains("modifier")?signedInteger(preparedValue):String(preparedValue)))});for(const link of htmlQueryAll(html,".item-delete"))link.addEventListener("click",event2=>{const itemId=htmlClosest(event2.currentTarget,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});this.deleteItem(item,event2)});for(const link of htmlQueryAll(html,".inventory-browse"))link.addEventListener("click",()=>this.#onClickBrowseEquipment(link));for(const link of htmlQueryAll(html,".save-name"))link.addEventListener("click",event2=>{const saveType=htmlClosest(link,"[data-save]")?.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);this.actor.saves?.[saveType]?.check.roll(eventToRollParams(event2,{type:"check"}))});const rollInitElem=htmlQuery(html,"a[data-action=roll-initiative]");rollInitElem?.addEventListener("click",event2=>{!rollInitElem.classList.contains("disabled")&&this.actor.initiative&&this.actor.initiative.roll(eventToRollParams(event2,{type:"check"}))}),htmlQuery(html,".actions-options")?.addEventListener("change",event2=>{const toggleRow=htmlClosest(event2.target,"[data-item-id][data-domain][data-option]"),checkbox=htmlQuery(toggleRow,"input[data-action=toggle-roll-option]"),suboptionsSelect=htmlQuery(toggleRow,"select[data-action=set-suboption"),{domain,option,itemId}=toggleRow?.dataset??{},suboption=suboptionsSelect?.value??null;checkbox&&domain&&option&&this.actor.toggleRollOption(domain,option,itemId??null,checkbox.checked,suboption)});for(const listName of["immunities","weaknesses","resistances"])htmlQuery(html,`a[data-action=edit-${listName}]`)?.addEventListener("click",()=>{new IWREditor(this.actor,{category:listName}).render(!0)});for(const strikeElem of htmlQueryAll(html,"ol.strikes-list > li[data-strike]")){const attackSelectors=".item-image[data-action=strike-attack], button[data-action=strike-attack]";for(const button of htmlQueryAll(strikeElem,attackSelectors))button.addEventListener("click",async event2=>{if(!Array.isArray(this.actor.system.actions))throw ErrorPF2e("Strikes are not supported on this actor");const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null,strike=this.getStrikeFromDOM(button,!0),variantIndex=Number(button.dataset.variantIndex);await strike?.variants[variantIndex]?.roll({event:event2,altUsage})});const damageSelectors="button[data-action=strike-damage], button[data-action=strike-critical]";for(const button of htmlQueryAll(strikeElem,damageSelectors)){const strike=this.getStrikeFromDOM(button),method=button.dataset.action==="strike-damage"?"damage":"critical";button.addEventListener("click",async event2=>{await strike?.[method]?.({event:event2})});const altUsage=tupleHasValue(["thrown","melee"],button.dataset.altUsage)?button.dataset.altUsage:null;strike?.[method]?.({getFormula:!0,altUsage}).then(formula=>{formula&&(button.dataset.tooltip=formula.toString())})}}for(const anchor of htmlQueryAll(html,".item-unprepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"";this.actor.spellcasting.collections.get(entryId)?.unprepareSpell(slotLevel,slotId)});for(const anchor of htmlQueryAll(html,".item-toggle-prepare"))anchor.addEventListener("click",()=>{const row=htmlClosest(anchor,".item"),slotLevel=Number(row?.dataset.slotLevel)||0,slotId=Number(row?.dataset.slotId)||0,entryId=row?.dataset.entryId??"",expendedState=row?.dataset.expendedState!=="true";this.actor.spellcasting.collections.get(entryId)?.setSlotExpendedState(slotLevel,slotId,expendedState)});for(const link of htmlQueryAll(html,".tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link));for(const link of htmlQueryAll(html,".item-create, .item-control.spell-create"))link.addEventListener("click",()=>this.#onClickCreateItem(link));for(const anchor of htmlQueryAll(html,".item-edit"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId??"")?.sheet.render(!0,{focus:!0})});for(const effectDecrement of htmlQueryAll(html,".effects-list .decrement"))effectDecrement.addEventListener("click",event2=>{const parent=htmlClosest(event2.currentTarget,".item"),effect=this.actor.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.decrease()});for(const effectIncrement of htmlQueryAll(html,".effects-list .increment"))effectIncrement.addEventListener("click",event2=>{const parent=htmlClosest(event2.currentTarget,".item"),effect=this.actor?.items.get(parent?.dataset.itemId??"");effect instanceof AbstractEffectPF2e&&effect.increase()});for(const element of htmlQueryAll(html,".effects-list [data-action=effect-toggle-unidentified]")??[])element.addEventListener("click",async event2=>{const effectId=htmlClosest(event2.currentTarget,"[data-item-id]")?.dataset.itemId,effect=this.actor.items.get(effectId,{strict:!0});if(effect.isOfType("effect")){const isUnidentified=effect.system.unidentified;await effect.update({"system.unidentified":!isUnidentified})}});for(const inputElem of htmlQueryAll(html,"input[type=text], input[type=number]"))inputElem.addEventListener("focus",()=>{inputElem.select()});for(const deltaInput of htmlQueryAll(html,"input[data-allow-delta]"))deltaInput.addEventListener("input",()=>{const match=/[+-]?\d*/.exec(deltaInput.value)?.at(0);deltaInput.value=match??deltaInput.value})}activateClickListener(html){const handlers={"use-action":event2=>{const itemId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});item.isOfType("action","feat")&&createSelfEffectMessage(item,eventToRollMode(event2))},"roll-check":(event2,anchor)=>{const statistic=this.actor.getStatistic(anchor.dataset.statistic??""),args=eventToRollParams(event2,{type:"check"});anchor.dataset.secret!==void 0&&(args.rollMode=game.user.isGM?"gmroll":"blindroll"),statistic?.roll(args)},"show-image":()=>{const actor=this.actor,title=actor.token?.name??actor.prototypeToken?.name??actor.name;new ImagePopout(actor.img,{title,uuid:actor.uuid}).render(!0)},"toggle-summary":(_event,anchor)=>{const element=htmlClosest(anchor,"[data-item-id], [data-action-index]")??htmlClosest(anchor,"li");element&&this.itemRenderer.toggleSummary(element)}};return html.addEventListener("click",event2=>{const actionTarget=htmlClosest(event2.target,"a[data-action], button[data-action]"),handler=handlers[actionTarget?.dataset.action??""];handler&&actionTarget&&(event2.stopImmediatePropagation(),handler(event2,actionTarget))}),handlers}activateInventoryListeners(panel){if(this.isEditable){this._canDragDrop(".item-list")&&this.#activateInventoryDragDrop(panel),panel?.addEventListener("click",event2=>{const link=htmlClosest(event2.target,"a[data-action], button[data-action]");if(!link)return;const getItem=__name2(()=>{const itemId=htmlClosest(link,"[data-item-id]")?.dataset.itemId??"",item=this.actor.items.get(itemId);if(!item?.isOfType("physical"))throw ErrorPF2e("Item not found or isn't physical");return item},"getItem");switch(link.dataset.action){case"add-coins":{new AddCoinsPopup(this.actor).render(!0);return}case"remove-coins":{new RemoveCoinsPopup(this.actor).render(!0);return}case"increase-quantity":{const item=getItem(),addend=event2.ctrlKey?10:event2.shiftKey?5:1;item.update({"system.quantity":item.quantity+addend});return}case"decrease-quantity":{const item=getItem();if(item.quantity>0){const subtrahend=Math.min(item.quantity,event2.ctrlKey?10:event2.shiftKey?5:1);item.update({"system.quantity":item.quantity-subtrahend})}return}case"repair":{const item=getItem();game.pf2e.actions.repair({event:event2,item});return}case"toggle-identified":{const item=getItem();item.isIdentified?item.setIdentificationStatus("unidentified"):new IdentifyItemPopup(item).render(!0);return}case"toggle-container":{const item=getItem();if(!item.isOfType("backpack"))return;const isCollapsed=item.system.collapsed??!1;item.update({"system.collapsed":!isCollapsed});return}case"sell-treasure":{const item=getItem(),sellItem=__name2(async()=>{item?.isOfType("treasure")&&!item.isCoinage&&(await item.delete(),await this.actor.inventory.addCoins(item.assetValue))},"sellItem");if(event2.ctrlKey){sellItem();return}const content=document.createElement("p");content.innerText=game.i18n.format("PF2E.SellItemQuestion",{item:item.name}),new Dialog({title:game.i18n.localize("PF2E.SellItemConfirmHeader"),content:content.outerHTML,buttons:{Yes:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("Yes"),callback:sellItem},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"Yes"}).render(!0);return}case"sell-all-treasure":this.#onClickSellAllTreasure()}});for(const anchor of htmlQueryAll(panel,".carry-type-hover"))$(anchor).tooltipster({animation:"fade",delay:200,animationDuration:10,trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["bottom"],theme:"crb-hover",minWidth:120})}}#activateInventoryDragDrop(panel){const section=htmlQuery(panel,"section[data-inventory]");if(!(!section||!this.isEditable))for(const list of htmlQueryAll(section,"ul[data-item-list]")){const options={...SORTABLE_BASE_OPTIONS,scroll:section,setData:(dataTransfer,dragEl)=>{const item=this.actor.inventory.get(dragEl.dataset.itemId,{strict:!0});dataTransfer.setData("text/plain",JSON.stringify({...item.toDragData(),fromInventory:!0}))},onMove:event2=>this.#onMoveInventoryItem(event2),onEnd:event2=>this.#onDropInventoryItem(event2)};new Sortable(list,options)}}#onMoveInventoryItem(event2){const isSeparateSheet=htmlClosest(event2.target,"form")!==htmlClosest(event2.related,"form");if(!this.isEditable||isSeparateSheet)return!1;const sourceItem=this.actor.inventory.get(event2.dragged?.dataset.itemId,{strict:!0}),containerRowData=htmlQueryAll(this.form,"li[data-is-container] > .data");for(const row of containerRowData)row.classList.remove("drop-highlight");const targetSection=htmlClosest(event2.related,"ul[data-item-types]")?.dataset.itemTypes?.split(",")??[];if(targetSection.length===0)return!1;if(targetSection.includes(sourceItem.type))return!0;if(targetSection.includes("backpack")){const openContainerId=htmlClosest(event2.related,"ul[data-container-id]")?.dataset.containerId??"",openContainer=this.actor.inventory.get(openContainerId),targetItemRow=htmlClosest(event2.related,"li[data-item-id]"),targetItem=this.actor.inventory.get(targetItemRow?.dataset.itemId??"");return targetItemRow&&targetItem?.isOfType("backpack")&&!openContainer?(htmlQuery(targetItemRow,":scope > .data")?.classList.add("drop-highlight"),!1):!!targetItem}return!1}async#onDropInventoryItem(event2){const isSeparateSheet=htmlClosest(event2.target,"form")!==htmlClosest(event2.originalEvent?.target,"form");if(!this.isEditable||isSeparateSheet)return;const containerRowData=htmlQueryAll(this.form,"li[data-is-container] > .data");for(const row of containerRowData)row.classList.remove("drop-highlight");const inventory=this.actor.inventory,sourceItem=inventory.get(event2.item.dataset.itemId,{strict:!0}),itemsInList=htmlQueryAll(htmlClosest(event2.item,"ul"),":scope > li").map(li=>li.dataset.itemId===sourceItem.id?sourceItem:inventory.get(li.dataset.itemId,{strict:!0})),targetItemId=htmlClosest(event2.originalEvent?.target,"li[data-item-id]")?.dataset.itemId??"",targetItem=this.actor.inventory.get(targetItemId),stackTarget=(()=>targetItem?.isStackableWith(sourceItem)?targetItem:null)();if(stackTarget)return sourceItem.move({toStack:stackTarget});const containerId=htmlClosest(event2.item,"ul[data-container-id]")?.dataset.containerId??"",container=targetItem?.isOfType("backpack")?targetItem:inventory.get(containerId);if(container&&!container.isOfType("backpack"))throw ErrorPF2e("Unexpected non-container retrieved while sorting items");const sourceIndex=itemsInList.indexOf(sourceItem),targetBefore=itemsInList[sourceIndex-1],targetAfter=itemsInList[sourceIndex+1],siblings=[...itemsInList];siblings.splice(siblings.indexOf(sourceItem),1);const sortingUpdates=SortingHelpers.performIntegerSort(sourceItem,{siblings,target:targetBefore??targetAfter,sortBefore:!targetBefore}).map(u=>({_id:u.target.id,"system.containerId":container?.id??null,sort:u.update.sort}));sortingUpdates.some(u=>u._id===sourceItem.id)||sortingUpdates.push({_id:sourceItem.id,"system.containerId":container?.id??null}),await this.actor.updateEmbeddedDocuments("Item",sortingUpdates)}async deleteItem(item,event2){(event2?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`<p>${game.i18n.format("PF2E.DeleteQuestion",{name:`"${item.name}"`})}</p>`}))&&await item.delete()}async#onClickBrowseEquipment(element){const checkboxesFilterCodes=(element.dataset.filter??"").split(",").map(s=>s.trim()).filter(s=>!!s),tab=game.pf2e.compendiumBrowser.tabs.equipment,filter2=await tab.getFilterData(),{checkboxes}=filter2;for(const itemType of checkboxesFilterCodes){const checkbox=checkboxes.itemTypes;objectHasKey(checkbox.options,itemType)&&(checkbox.options[itemType].selected=!0,checkbox.selected.push(itemType),checkbox.isExpanded=!0)}tab.open(filter2)}_canDragStart(selector){return this.isLootSheet||super._canDragStart(selector)}_canDragDrop(selector){return this.isLootSheet||super._canDragDrop(selector)}_onDragStart(event2){if(!(event2.target instanceof HTMLElement)||!event2.dataTransfer)return;const isContentLink=event2.target.classList.contains("content-link"),isPersistent="persistent"in event2.target.dataset;if(event2.target!==event2.currentTarget&&(isContentLink||isPersistent))return;const targetElement=event2.currentTarget,previewElement=htmlClosest(targetElement,"[data-item-id], [data-strike]");if(previewElement&&targetElement&&targetElement!==previewElement){const{x,y}=previewElement.getBoundingClientRect();event2.dataTransfer.setDragImage(previewElement,event2.pageX-x,event2.pageY-y)}const itemId=previewElement?.dataset.itemId,item=this.actor.items.get(itemId??""),baseDragData={actorId:this.actor.id,actorUUID:this.actor.uuid,sceneId:canvas.scene?.id??null,tokenId:this.actor.token?.id??null,...item?.toDragData()};previewElement?.dataset.isFormula&&(baseDragData.isFormula=!0,baseDragData.entrySelector=previewElement.dataset.entrySelector);const supplementalData=(()=>{const actionIndex=previewElement?.dataset.actionIndex;if(actionIndex)return"itemType"in baseDragData&&baseDragData.itemType==="melee"?{index:Number(actionIndex)}:{type:"Action",index:Number(actionIndex)};const elementTrait=previewElement?.dataset.element;if(elementTrait)return{type:"Action",elementTrait};const label=previewElement?.innerText.trim(),rollOptionData=previewElement?.dataset??{};return item&&label&&rollOptionData.domain&&rollOptionData.option?{type:"RollOption",label,...rollOptionData}:baseDragData.isFormula?{pf2e:{type:"CraftingFormula",itemUuid:itemId}}:null})();event2.dataTransfer.setData("text/plain",JSON.stringify({...baseDragData,...supplementalData}))}async emulateItemDrop(data){const event2=new DragEvent("drop",{altKey:game.keyboard.isModifierActive("Alt")});return this._onDropItem(event2,data)}async _onDropItem(event2,data){event2.preventDefault();const item=await ItemPF2e.fromDropData(data);return item?item.actor?.uuid===this.actor.uuid?data.fromInventory?[]:this._onSortItem(event2,item.toObject()):item.actor&&item.isOfType("physical")?(await this.moveItemBetweenActors(event2,item.actor.id,item.actor?.token?.id??null,this.actor.id,this.actor.token?.id??null,item.id),[item]):this._handleDroppedItem(event2,item,data):[]}async _handleDroppedItem(event2,item,data){const{actor}=this,itemSource=item.toObject(),mystified=game.user.isGM&&event2.altKey;mystified&&itemSource.type==="effect"&&(itemSource.system.unidentified=!0),mystified&&item.isOfType("physical")&&isPhysicalData(itemSource)&&(itemSource.system.identification.unidentified=item.getMystifiedData("unidentified"),itemSource.system.identification.status="unidentified");const containerAttribute=htmlClosest(event2.target,".item-container")?.dataset.containerType,dropContainerType=this._tabs[0]?.active==="inventory"&&!containerAttribute?"actorInventory":containerAttribute,craftingTab=this._tabs[0]?.active==="crafting";if(item.isOfType("spell")&&itemSource.type==="spell")return item.isRitual?this._onDropItemCreate(item.clone().toObject()):dropContainerType==="actorInventory"&&itemSource.system.level.value>0?(new CastingItemCreateDialog(actor,{},async(heightenedLevel,itemType,spell)=>{const createdItem=await createConsumableFromSpell(spell,{type:itemType,heightenedLevel,mystified});await this._onDropItemCreate(createdItem)},item).render(!0),[item]):[];if(itemSource.type==="spellcastingEntry")return[];if(itemSource.type==="condition"){const value=data.value;return typeof value=="number"&&itemSource.system.value.isValued&&(itemSource.system.value.value=value),actor.canUserModify(game.user,"update")?[await actor.increaseCondition(itemSource.system.slug,{value})??[]].flat():(ui.notifications.error("PF2E.ErrorMessage.NoUpdatePermission",{localize:!0}),[])}else if(itemIsOfType(itemSource,"affliction","effect")){const{level,value,context}=data;typeof level=="number"&&level>=0&&(itemSource.system.level.value=Math.floor(level)),itemSource.type==="effect"&&itemSource.system.badge?.type==="counter"&&typeof value=="number"&&(itemSource.system.badge.value=value),itemSource.system.context=context??null;const originItem=fromUuidSync(context?.origin.item??"");itemSource.system.traits?.value.length===0&&originItem instanceof SpellPF2e&&itemSource.system.traits.value.push(...originItem.traits)}else if(item.isOfType("physical")&&actor.isOfType("character")&&craftingTab){const actorFormulas=foundry.utils.deepClone(actor.system.crafting.formulas);return actorFormulas.some(f=>f.uuid===item.uuid)||(actorFormulas.push({uuid:item.uuid}),await actor.update({"system.crafting.formulas":actorFormulas})),[item]}if(isPhysicalData(itemSource)){const containerId=htmlClosest(event2.target,"li[data-is-container]")?.dataset.itemId?.trim()||null;this.actor.itemTypes.backpack.find(container2=>container2.id===containerId)?(itemSource.system.containerId=containerId,itemSource.system.equipped.carryType="stowed"):itemSource.system.equipped.carryType="worn",data?.uuid?.startsWith("Compendium")&&itemSource.type!=="treasure"&&!["med","sm"].includes(actor.size)&&actor.isOfType("creature")&&(itemSource.system.size=actor.size)}return this._onDropItemCreate(new ItemProxyPF2e(itemSource).clone().toObject())}async _onDropFolder(_event,data){if(!(this.actor.isOwner&&data.documentName==="Item"))return[];const folder=await Folder.fromDropData(data);if(!folder)return[];const itemSources=[folder,...folder.getSubfolders()].flatMap(f=>f.contents).map(i=>i.toObject());return this._onDropItemCreate(itemSources)}async moveItemBetweenActors(event2,sourceActorId,sourceTokenId,targetActorId,targetTokenId,itemId){const sourceActor=canvas.scene?.tokens.get(sourceTokenId??"")?.actor??game.actors.get(sourceActorId),targetActor=canvas.scene?.tokens.get(targetTokenId??"")?.actor??game.actors.get(targetActorId),item=sourceActor?.items.get(itemId);if(!sourceActor||!targetActor)throw ErrorPF2e("Unexpected missing actor(s)");if(!item?.isOfType("physical"))throw ErrorPF2e("Missing or invalid item");const containerId=htmlClosest(event2.target,"[data-is-container]")?.dataset.containerId?.trim(),sourceItemQuantity=item.quantity,stackable=!!targetActor.inventory.findStackableItem(item._source),isPurchase=sourceActor.isOfType("loot")&&sourceActor.isMerchant&&!sourceActor.isOwner,isAmmunition=item.isOfType("consumable")&&item.isAmmo;if(sourceItemQuantity>1){const defaultQuantity=isPurchase?isAmmunition?Math.min(10,sourceItemQuantity):1:sourceItemQuantity;new MoveLootPopup(sourceActor,{quantity:{max:sourceItemQuantity,default:defaultQuantity},lockStack:!stackable,isPurchase},(quantity,newStack)=>{sourceActor.transferItemToActor(targetActor,item,quantity,containerId,newStack)}).render(!0)}else sourceActor.transferItemToActor(targetActor,item,1,containerId)}#onClickCreateItem(anchor){const dataset={...anchor.dataset},itemType=compact([dataset.type??dataset.types?.split(",")].flat()).find(t=>t!=="shield");if(!objectHasKey(CONFIG.PF2E.Item.documentClasses,itemType))throw ErrorPF2e("Unrecognized item type: types");if(itemType==="spell")return onClickCreateSpell(this.actor,dataset);const itemSource=(()=>{switch(itemType){case"action":{const{actionType}=dataset;if(!objectHasKey(CONFIG.PF2E.actionTypes,actionType))throw ErrorPF2e(`Action type not recognized: ${actionType}`);const name2=game.i18n.localize(`PF2E.ActionType${actionType.capitalize()}`);return{type:itemType,name:name2,system:{actionType:{value:actionType}}}}case"melee":{const name2=game.i18n.localize(`PF2E.NewPlaceholders.${itemType.capitalize()}`),meleeOrRanged=dataset.actionType==="melee"?"melee":"ranged";return{type:itemType,name:name2,system:{weaponType:{value:meleeOrRanged}}}}case"lore":{const name2=this.actor.type==="npc"?game.i18n.localize("PF2E.SkillLabel"):game.i18n.localize("PF2E.NewPlaceholders.Lore");return{type:itemType,name:name2}}default:{if(!setHasElement(PHYSICAL_ITEM_TYPES,itemType))throw ErrorPF2e(`Unsupported item type: ${itemType}`);return{name:game.i18n.localize(`PF2E.NewPlaceholders.${itemType.capitalize()}`),type:itemType}}}})();if(itemSource){if(dataset.traits){const traits=dataset.traits?.split(",")??[];itemSource.system=foundry.utils.mergeObject(itemSource.system??{},{traits:{value:traits}})}this.actor.createEmbeddedDocuments("Item",[itemSource])}}async#onClickSellAllTreasure(){const content=await renderTemplate("systems/pf2e/templates/actors/sell-all-treasure-dialog.hbs");new Dialog({title:game.i18n.localize("PF2E.SellAllTreasureTitle"),content,buttons:{yes:{icon:fontAwesomeIcon("check").outerHTML,label:"Yes",callback:async()=>this.actor.inventory.sellAllTreasure()},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"}},default:"cancel"}).render(!0)}openTagSelector(anchor,options={}){const selectorType=anchor.dataset.tagSelector;if(!tupleHasValue(TAG_SELECTOR_TYPES,selectorType))throw ErrorPF2e(`Unrecognized tag selector type "${selectorType}"`);if(selectorType==="basic"){const objectProperty=anchor.dataset.property??"",title=anchor.dataset.title??"",configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag));this.tagSelector("basic",{...options,objectProperty,configTypes,title})}else this.tagSelector(selectorType,options)}tagSelector(selectorType,options){if(selectorType==="basic"&&options&&"objectProperty"in options)new TagSelectorBasic(this.object,options).render(!0);else{if(selectorType==="basic")throw ErrorPF2e("Insufficient options provided to render basic tag selector");{const TagSelector={senses:SenseSelector,"speed-types":SpeedSelector}[selectorType];new TagSelector(this.object,options).render(!0)}}}openTab(name2){this._tabs[0].activate(name2)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}async _render(force,options){await maintainFocusInRender(this,()=>super._render(force,options)),options?.tab&&this.openTab(options.tab)}async _onSubmit(event2,{updateData=null,preventClose=!1,preventRender=!1}={}){for(const input of htmlQueryAll(this.form,"tags ~ input"))input.value===""&&(input.value="[]");return super._onSubmit(event2,{updateData,preventClose,preventRender})}_getSubmitData(updateData){const data=super._getSubmitData(updateData);processTagifyInSubmitData(this.form,data);for(const el of this.form.elements)if(el instanceof HTMLInputElement&&el.dataset.allowDelta!==void 0){const strValue=el.value.trim(),value=Number(strValue);(strValue.startsWith("+")||strValue.startsWith("-"))&&!Number.isNaN(value)&&(data[el.name]=Number(foundry.utils.getProperty(this.actor,el.name))+value)}return data}}function normalizeActionChangeData(document2,changed){if(changed.system&&("actionType"in changed.system||"actions"in changed.system)){const actionType=changed.system?.actionType?.value??document2.system.actionType.value,actionCount=Number(changed.system?.actions?.value??document2.system.actions.value);changed.system=foundry.utils.mergeObject(changed.system,{actionType:{value:actionType},actions:{value:actionType!=="action"?null:Math.clamped(actionCount,1,3)}})}}__name(normalizeActionChangeData,"normalizeActionChangeData"),__name2(normalizeActionChangeData,"normalizeActionChangeData");function activateActionSheetListeners(item,html){htmlQuery(html,"a[data-action=frequency-add]")?.addEventListener("click",()=>{const frequency={max:1,per:"day"};item.update({system:{frequency}})}),htmlQuery(html,"a[data-action=frequency-delete]")?.addEventListener("click",()=>{item.update({"system.-=frequency":null})}),item.isOfType("action","feat")&&htmlQuery(html,"a[data-action=delete-effect]")?.addEventListener("click",()=>{item._source.system.selfEffect&&item.update({"system.-=selfEffect":null})})}__name(activateActionSheetListeners,"activateActionSheetListeners"),__name2(activateActionSheetListeners,"activateActionSheetListeners");function createSelfEffectSheetData(data){if(!data)return null;const indexEntry=fromUuidSync(data.uuid);indexEntry?.name&&isImageFilePath(indexEntry.img)&&(data.name=indexEntry.name,data.img=indexEntry.img);const parsedUUID=foundry.utils.parseUuid(data.uuid),linkData={id:parsedUUID.documentId??null,type:parsedUUID.documentType??null,pack:parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null};return{...data,...linkData}}__name(createSelfEffectSheetData,"createSelfEffectSheetData"),__name2(createSelfEffectSheetData,"createSelfEffectSheetData");async function handleSelfEffectDrop(sheet,event2){if(!sheet.isEditable||sheet.item.system.actionType.value==="passive")return;const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!item?.isOfType("effect"))throw ErrorPF2e("Invalid item drop");await sheet.item.update({"system.selfEffect":{uuid:item.uuid,name:item.name}})}__name(handleSelfEffectDrop,"handleSelfEffectDrop"),__name2(handleSelfEffectDrop,"handleSelfEffectDrop");function createActionRangeLabel(range2){if(!range2?.max)return null;const[key,value]=range2.increment?["PF2E.Action.Range.IncrementN",range2.increment]:["PF2E.Action.Range.MaxN",range2.max];return game.i18n.format(key,{n:value})}__name(createActionRangeLabel,"createActionRangeLabel"),__name2(createActionRangeLabel,"createActionRangeLabel");function processSanctification(item){const itemTraits=item.system.traits;if(!itemTraits.value.includes("sanctified"))return;const actorTraits=item.actor.system.traits?.value??[],isHoly=actorTraits.includes("holy"),isUnholy=actorTraits.includes("unholy");(isHoly||isUnholy)&&!(isHoly&&isUnholy)&&(itemTraits.value=uniq([...itemTraits.value,isHoly?"holy":"unholy"]).sort())}__name(processSanctification,"processSanctification"),__name2(processSanctification,"processSanctification");class RollNotePF2e{static{__name(this,"RollNotePF2e")}static{__name2(this,"RollNotePF2e")}selector;title;text;predicate;outcome;visibility;rule;constructor(params){this.selector=params.selector,this.title=params.title??null,this.text=params.text,this.predicate=new PredicatePF2e(params.predicate??[]),this.outcome=[...params.outcome??[]],this.visibility=params.visibility??null,this.rule=params.rule??null}static notesToHTML(notes){return createHTMLElement("ul",{classes:["notes"],children:notes.flatMap(n=>[`
|
|
`,n.toHTML()]).slice(1)})}toHTML(){const element=createHTMLElement("li",{classes:["roll-note"],dataset:{itemId:this.rule?.item.id,visibility:this.visibility},innerHTML:game.i18n.localize(this.text)});if(element.childNodes.length===1&&element.firstChild instanceof HTMLElement&&(element.innerHTML=element.firstChild.innerHTML),this.title){const strong=createHTMLElement("strong",{innerHTML:game.i18n.localize(this.title)});element.prepend(strong," ")}return element}clone(){return new RollNotePF2e({...this.toObject(),rule:this.rule})}toObject(){return{selector:this.selector,title:this.title,text:this.text,predicate:this.predicate.toObject(),outcome:this.outcome,visibility:this.visibility}}}class DamagePF2e{static{__name(this,"DamagePF2e")}static{__name2(this,"DamagePF2e")}static async roll(data,context,callback){const outcome=context.outcome??null;context.rollMode??=(context.secret?"blindroll":void 0)??game.settings.get("core","rollMode"),context.createMessage??=!0,context.options.has("secret")&&(context.secret=!0);const subtitle=outcome?context.sourceType==="attack"?game.i18n.localize(`PF2E.Check.Result.Degree.Attack.${outcome}`):game.i18n.localize(`PF2E.Check.Result.Degree.Check.${outcome}`):null;let flavor=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:data.name,subtitle});if(context.traits){const toTags=__name2((slugs,{labels={},descriptions={},cssClass,dataAttr})=>slugs.map(s=>({value:s,label:game.i18n.localize(labels[s]??"")})).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(tag=>{const description=descriptions[tag.value]??"",span=document.createElement("span");return span.className="tag",cssClass&&span.classList.add(cssClass),span.dataset[dataAttr]=tag.value,description&&(span.dataset.tooltip=description),span.innerText=tag.label,span.outerHTML}).join(""),"toTags"),traits=toTags(context.traits,{labels:CONFIG.PF2E.actionTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:null,dataAttr:"trait"}),item2=context.self?.item,itemTraits=item2?.isOfType("weapon","melee")?toTags(Array.from(item2.traits).filter(t=>!(t in CONFIG.PF2E.materialDamageEffects)),{labels:item2.isOfType("spell")?CONFIG.PF2E.spellTraits:CONFIG.PF2E.npcAttackTraits,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_alt",dataAttr:"trait"}):"",runeTags=(()=>{const hasGhostTouch=context.options.has("item:rune:property:ghost-touch"),hasAstral=context.options.has("item:rune:property:astral")||context.options.has("item:rune:property:greater-astral");return(hasGhostTouch||hasAstral)&&context.options.has("target:trait:incorporeal")?toTags(["ghost-touch"],{labels:{"ghost-touch":"PF2E.WeaponPropertyRune.ghostTouch.Name"},descriptions:{"ghost-touch":"PF2E.WeaponPropertyRune.ghostTouch.Note"},cssClass:"ghost-touch",dataAttr:"slug"}):""})(),properties=(()=>{const range2=item2?.isOfType("action","melee","weapon")?item2.range:null,label=createActionRangeLabel(range2);if(label&&(range2?.increment||range2?.max)){const slug=range2.increment?`range-increment-${range2.increment}`:`range-${range2.max}`;return toTags([slug],{labels:{[slug]:label},descriptions:{[slug]:"PF2E.Item.Weapon.RangeIncrementN.Hint"},cssClass:"tag_secondary",dataAttr:"slug"})}else return""})(),materialEffects=toTags(data.materials,{labels:CONFIG.PF2E.preciousMaterials,descriptions:CONFIG.PF2E.traitsDescriptions,cssClass:"tag_material",dataAttr:"material"}),otherTags=[itemTraits,properties,materialEffects,runeTags].join(""),tagsElem=createHTMLElement("div",{classes:["tags"],dataset:{tooltipClass:"pf2e"}});tagsElem.innerHTML=otherTags.length>0?`${traits}<hr class="vr" />${otherTags}`:traits,flavor+=tagsElem.outerHTML,flavor+=`
|
|
<hr />`}const breakdownTags=(Array.isArray(data.damage.breakdown)?data.damage.breakdown:data.damage.breakdown[outcome??"success"]).map(b=>`<span class="tag tag_transparent">${b}</span>`);flavor+=`<div class="tags">${breakdownTags.join("")}</div>`;const roll=await(()=>{const damage=data.damage;if("roll"in damage)return damage.roll.evaluate({async:!0});const formula=foundry.utils.deepClone(damage.formula[outcome??"success"]);if(!formula)return ui.notifications.error(game.i18n.format("PF2E.UI.noDamageInfoForOutcome",{outcome})),null;const rollerId=game.userId,degreeOfSuccess=outcome?DEGREE_OF_SUCCESS_STRINGS.indexOf(outcome):null,critRule=degreeOfSuccess!==DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?null:game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",options={rollerId,damage:data,degreeOfSuccess,critRule,ignoredResistances:damage.ignoredResistances};return new DamageRoll(formula,{},options).evaluate({async:!0})})();if(roll===null)return null;const syntheticNotes=context.self?.actor?extractNotes(context.self?.actor.synthetics.rollNotes,context.domains??[]):[],contextNotes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n))??[],notes=[...syntheticNotes,...contextNotes].filter(n=>(n.outcome.length===0||outcome&&n.outcome.includes(outcome))&&n.predicate.test(context.options)),notesList=RollNotePF2e.notesToHTML(notes);flavor+=notesList.outerHTML;const{self,target}=context,item=self?.item??null,targetFlag=target?{actor:target.actor.uuid,token:target.token.uuid}:null,strike=(()=>{if(item?.isOfType("melee","weapon")&&item&&self?.actor?.isOfType("character","npc")){const strikes=self.actor.system.actions,strike2=strikes.find(a=>a.item?.id===item.id&&a.item.slug===item.slug);if(strike2)return{actor:self.actor.uuid,index:strikes.indexOf(strike2),damaging:!0,name:strike2.item.name,altUsage:item.isOfType("weapon")?item.altUsageType:null}}return null})(),rollMode=context.rollMode??"roll",contextFlag={type:context.type,sourceType:context.sourceType,actor:context.self?.actor.id??null,token:context.self?.token?.id??null,target:targetFlag,domains:context.domains??[],options:Array.from(context.options).sort(),mapIncreases:context.mapIncreases,notes:notes.map(n=>n.toObject()),secret:context.secret??!1,rollMode,traits:context.traits??[],skipDialog:context.skipDialog??!game.user.settings.showDamageDialogs,outcome,unadjustedOutcome:context.unadjustedOutcome??null},messageData=await roll.toMessage({speaker:ChatMessagePF2e.getSpeaker({actor:self?.actor,token:self?.token}),flavor,flags:{pf2e:{context:contextFlag,target:targetFlag,modifiers:data.modifiers?.flatMap(m=>"kind"in m?m.toObject():[])??[],dice:data.modifiers?.flatMap(m=>"diceNumber"in m?m.toObject():[])??[],origin:item?.getOriginData(),strike,preformatted:"both"}}},{create:!1}),splashRolls=await(async()=>{const splashInstances=roll.instances.map(i=>({damageType:i.type,total:i.componentTotal("splash")})).filter(s=>s.total>0),rolls=[];for(const splash of splashInstances){const formula=`(${splash.total}[splash])[${splash.damageType}]`,roll2=await new DamageRoll(formula).evaluate({async:!0});roll2.options.splashOnly=!0,rolls.push(roll2.toJSON())}return rolls})();return context.createMessage&&(messageData.rolls.push(...splashRolls),await ChatMessagePF2e.create(messageData,{rollMode})),Hooks.callAll("pf2e.damageRoll",roll),callback&&callback(roll),roll}}class DamageModifierDialog extends Application{static{__name(this,"DamageModifierDialog")}static{__name2(this,"DamageModifierDialog")}formulaData;context;baseDamageType;degree;#resolve;isRolled=!1;#originallyEnabled;constructor(params){super(),this.formulaData=params.formulaData,this.context=params.context,this.baseDamageType=params.formulaData.base.at(0)?.damageType??"untyped",this.degree=DEGREE_OF_SUCCESS_STRINGS.indexOf(this.context.outcome??"success"),this.#originallyEnabled=new Set(this.formulaData.modifiers.filter(m=>m.enabled))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/damage/damage-modifier-dialog.hbs",classes:["roll-modifiers-dialog","damage-dialog","dialog"],popOut:!0,width:440,height:"auto"}}get title(){return this.isCritical?game.i18n.localize("PF2E.Roll.Dialog.Damage.TitleCritical"):game.i18n.localize("PF2E.Roll.Dialog.Damage.Title")}get isCritical(){return this.degree===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS}#getModifierIcon(object){const damageTypeIconClass=object.damageType?DAMAGE_TYPE_ICONS[object.damageType]:null,damageTypeIcon=damageTypeIconClass?fontAwesomeIcon(damageTypeIconClass):null;return(()=>{switch(object.category){case"splash":return compact([fontAwesomeIcon("fa-burst"),damageTypeIcon]);case"persistent":return object.damageType!=="bleed"?[damageTypeIcon,fontAwesomeIcon("fa-hourglass",{style:"duotone"})]:[damageTypeIcon];case"precision":return[damageTypeIcon,fontAwesomeIcon("fa-crosshairs")];default:return[damageTypeIcon]}})().map(i=>i?.outerHTML??"").join("")}#getTypeLabel(damageType,category){if(category==="precision")return game.i18n.localize("PF2E.Damage.Precision");if(!damageType)return null;const typeLabel=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType]);switch(category){case"persistent":return game.i18n.format("PF2E.Damage.PersistentTooltip",{damageType:typeLabel});case"splash":return game.i18n.format("PF2E.Roll.Dialog.Damage.Splash",{damageType:typeLabel});default:return typeLabel}}async getData(){const visibleModifiers=[...this.formulaData.modifiers.entries()].filter(([_,m])=>this.isCritical||!m.critical),visibleDiceAll=[...this.formulaData.dice.entries()].filter(([_,d])=>this.isCritical||!d.critical),visibleDice=visibleDiceAll.filter(([_,d])=>!d.override||d.dieSize||d.diceNumber),baseResult=createDamageFormula({base:this.formulaData.base,modifiers:[],dice:[],ignoredResistances:[]}),baseRoll=new DamageRoll(baseResult.formula),baseFormulaTemplate=(await Promise.all(baseRoll.instances.map(i=>i.render()))).join(" + "),result=createDamageFormula(this.formulaData,this.degree),roll=new DamageRoll(result?.formula??"0"),formulaTemplate=(await Promise.all(roll.instances.map(i=>i.render({tooltips:!1})))).join(" + ");return{appId:this.id,baseFormula:baseFormulaTemplate,modifiers:visibleModifiers.map(([idx,m])=>({idx,label:m.label,category:m.category,type:m.type,modifier:m.modifier,hideIfDisabled:!this.#originallyEnabled.has(m)&&m.hideIfDisabled,damageType:m.damageType,typeLabel:this.#getTypeLabel(m.damageType,m.damageCategory),enabled:m.enabled,ignored:m.ignored,critical:m.critical,icon:this.#getModifierIcon(m)})),dice:visibleDice.map(([idx,d])=>({idx,label:d.label,category:d.category,damageType:d.damageType,typeLabel:this.#getTypeLabel(d.damageType,d.category),diceLabel:d.diceNumber&&d.dieSize?`${d.diceNumber}${d.dieSize}`:d.diceNumber?game.i18n.format("PF2E.Roll.Dialog.Damage.Dice",{dice:signedInteger(d.diceNumber)}):"",enabled:d.enabled,ignored:d.ignored,critical:d.critical,icon:this.#getModifierIcon(d)})),overrides:pipe(visibleDiceAll,filter(args=>!!args[1].override),sortBy(([_,d])=>d.override.diceNumber&&!d.override.dieSize?1:d.override.upgrade?2:3),map(([idx,d])=>({idx,label:d.label,category:d.category,damageType:d.override.damageType??d.damageType,typeLabel:this.#getTypeLabel(d.override.damageType??d.damageType,d.category),diceLabel:compact([d.override.upgrade?game.i18n.localize("PF2E.Roll.Dialog.Damage.DieSizeUpgrade"):null,d.override.diceNumber||d.override.dieSize?game.i18n.format("PF2E.Roll.Dialog.Damage.Override",{value:d.override.diceNumber&&d.override.dieSize?`${d.override.diceNumber}${d.override.dieSize}`:d.override.diceNumber?game.i18n.format("PF2E.Roll.Dialog.Damage.Dice",{dice:d.override.diceNumber}):d.override.dieSize??""}):null]).join(" + "),enabled:d.enabled,ignored:d.ignored,critical:d.critical,icon:this.#getModifierIcon(d)}))),isCritical:this.isCritical,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),damageSubtypes:sortStringRecord(pick(CONFIG.PF2E.damageCategories,Array.from(DAMAGE_CATEGORIES_UNIQUE))),rollModes:CONFIG.Dice.rollModes,rollMode:this.context?.rollMode,showDamageDialogs:game.user.settings.showDamageDialogs,formula:formulaTemplate}}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.isRolled=!0,this.close()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const{dice,modifiers}=this.formulaData,modIndex=Number(checkbox.dataset.modifierIndex),dieIndex=Number(checkbox.dataset.diceIndex);Number.isNaN(modIndex)?Number.isNaN(dieIndex)||(dice[dieIndex].ignored=!checkbox.checked,dice[dieIndex].enabled=checkbox.checked):(modifiers[modIndex].ignored=!checkbox.checked,this.#applyStackingRules()),this.render()});const categorySelect=htmlQuery(html,"select.add-dice-category"),damageTypeSelect=htmlQuery(html,"select.add-dice-type");categorySelect?.addEventListener("change",()=>{damageTypeSelect&&(categorySelect.value==="precision"?(damageTypeSelect.value="",damageTypeSelect.disabled=!0):(damageTypeSelect.disabled=!1,damageTypeSelect.value=damageTypeSelect.firstElementChild?.value??"acid"))});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value),damageType=parent.querySelector(".add-modifier-damage-type")?.value??null,category=parent.querySelector(".add-modifier-category")?.value||null,errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");const label=String(parent.querySelector(".add-modifier-name")?.value).trim()||game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`);errors.length>0?ui.notifications.error(errors.join(" ")):(this.formulaData.modifiers.push(new ModifierPF2e({label,modifier:value,type,damageType,damageCategory:category})),this.#applyStackingRules(),this.render())});const addDiceButton=htmlQuery(html,"button.add-dice");addDiceButton?.addEventListener("click",()=>{const parent=addDiceButton.parentElement,count=Number(parent.querySelector(".add-dice-count")?.value||1),faces=parent.querySelector(".add-dice-faces")?.value??"d4",category=parent.querySelector(".add-dice-category")?.value||null,type=parent.querySelector(".add-dice-type")?.value||null;if(Number.isNaN(count)){ui.notifications.error("Damage dice count must be a number.");return}else if(count<1){ui.notifications.error("Damage dice count must be greater than zero.");return}if(!tupleHasValue(["persistent","precision","splash",null],category)){ui.notifications.error(`Unkown damage category: ${category}.`);return}const faceLabel=game.i18n.localize(`PF2E.DamageDie${faces.toUpperCase()}`),label=game.i18n.format("PF2E.Roll.Dialog.Damage.ExtraDice",{dice:`+${count}${faceLabel}`}),slug=sluggify(`${label}-${type}`);this.formulaData.dice.push(new DamageDicePF2e({label,category,diceNumber:count,dieSize:faces,damageType:type,slug,selector:"damage"})),this.render()});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const toggle=htmlQuery(html,"input[data-action=change-show-default]");toggle?.addEventListener("click",async()=>{await game.user.update({"flags.pf2e.settings.showDamageDialogs":toggle.checked})})}#applyStackingRules(){applyStackingRules(this.formulaData.modifiers.filter(m=>m.category!=="persistent")),applyStackingRules(this.formulaData.modifiers.filter(m=>m.category==="persistent"))}async resolve(){return this.render(!0),new Promise(resolve=>{this.#resolve=resolve})}async close(options){this.#resolve?.(this.isRolled),super.close(options)}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}}const superEnrichHTML=TextEditor.enrichHTML,superEnrichContentLinks=TextEditor._enrichContentLinks,superCreateInlineRoll=TextEditor._createInlineRoll,superOnClickInlineRoll=TextEditor._onClickInlineRoll;class TextEditorPF2e extends TextEditor{static{__name(this,"TextEditorPF2e")}static{__name2(this,"TextEditorPF2e")}static enrichHTML(content,options={}){options.secrets??=game.user.isGM,content=content?.replace(/^\s*<p>@Localize\[([\w.]+)\]<\/p>\s*$/,"@Localize[$1]")??null;const enriched=superEnrichHTML.apply(this,[content,options]);return typeof enriched=="string"&&(options.processVisibility??!0)?TextEditorPF2e.processUserVisibility(enriched,options):Promise.resolve().then(async()=>TextEditorPF2e.processUserVisibility(await enriched,options))}static _enrichContentLinks(text,options){if(options?.async){const documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],pattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g"),uuids=text.map(t=>Array.from((t.textContent??"").matchAll(pattern))).flat(2).filter(m=>UUIDUtils.isCompendiumUUID(m));return UUIDUtils.fromUUIDs(uuids).then(()=>superEnrichContentLinks.apply(this,[text,options]))}return superEnrichContentLinks.apply(this,[text,options])}static async _createInlineRoll(match,rollData,options={}){const anchor=await superCreateInlineRoll.apply(this,[match,rollData,options]),formula=anchor?.dataset.formula;if(formula){const roll=(()=>{try{return new DamageRoll(formula)}catch{return null}})();if(!roll||!looksLikeDamageRoll(roll))return anchor;const icon=damageDiceIcon(roll),label=match[4]&&match[4].length>0?match[4]:roll.formula;anchor.innerHTML=`${icon.outerHTML}${label}`,anchor.dataset.tooltip=roll.formula,anchor.dataset.damageRoll="",roll.instances.length>0&&roll.instances.every(i=>i.persistent)&&(anchor.draggable=!0,anchor.dataset.persistent="")}return anchor}static async _onClickInlineRoll(event2){const anchor=event2.currentTarget??null;if(!(anchor instanceof HTMLAnchorElement&&anchor.dataset.formula&&"damageRoll"in anchor.dataset))return superOnClickInlineRoll.apply(this,[event2]);const sheetElem=htmlClosest(anchor,".sheet"),messageElem=htmlClosest(anchor,"li.chat-message"),app=ui.windows[Number(sheetElem?.dataset.appid)],message=game.messages.get(messageElem?.dataset.messageId??""),[actor,rollData]=(()=>{if(message?.actor)return[message.actor,message.getRollData()];if(app instanceof ActorSheetPF2e){const itemId=anchor.dataset.pf2ItemId;return[app.actor,app.actor.items.get(itemId)?.getRollData()??app.actor.getRollData()]}if(app instanceof ItemSheetPF2e)return[app.actor,app.item.getRollData()];const itemUuid=anchor.dataset.itemUuid,itemByUUID=itemUuid&&!itemUuid.startsWith("Compendium.")?fromUuidSync(itemUuid):null;return itemByUUID instanceof ItemPF2e?[itemByUUID.actor,itemByUUID.getRollData()]:[null,{}]})(),options=anchor.dataset.flavor?{flavor:anchor.dataset.flavor}:{},speaker=ChatMessagePF2e.getSpeaker({actor}),rollMode=objectHasKey(CONFIG.Dice.rollModes,anchor.dataset.mode)?anchor.dataset.mode:"roll",baseFormula=anchor.dataset.pf2BaseFormula;if(baseFormula){const item=rollData.item instanceof ItemPF2e?rollData.item:null,traits=anchor.dataset.pf2Traits?.split(",")??[],domains=anchor.dataset.pf2Domains?.split(","),extraRollOptions=anchor.dataset.pf2RollOptions?.split(",")??[],result=await augmentInlineDamageRoll(baseFormula,{...eventToRollParams(event2,{type:"damage"}),actor,item,domains,traits,extraRollOptions});result&&await DamagePF2e.roll(result.template,result.context);return}const roll=new DamageRoll(anchor.dataset.formula,rollData,options);return roll.toMessage({speaker,flavor:roll.options.flavor},{rollMode})}static processUserVisibility(content,options){const html=createHTMLElement("div",{innerHTML:content}),document2=options.rollData?.actor??null;return UserVisibilityPF2e.process(html,{document:document2}),html.innerHTML}static async enrichString(data,options={}){if(data.length<4)return null;const item=options.rollData?.item??null,[_match,inlineType,paramString,inlineLabel]=data;switch(inlineType){case"Check":{const actor=options.rollData?.actor??item?.actor??null;return this.#createCheck({paramString,inlineLabel,item,actor})}case"Damage":return this.#createDamageRoll({paramString,rollData:options.rollData,inlineLabel});case"Localize":return this.#localize(paramString,options);case"Template":return this.#createTemplate(paramString,inlineLabel,item?.system);default:return null}}static convertXMLNode(html,name2,{visible,visibility,whose,tooltip,classes}){const node=html.querySelector(name2);if(!node)return null;const span=document.createElement("span"),{dataset,classList}=span;if(typeof visible=="boolean"&&(visibility=visible?"all":"gm"),visibility&&(dataset.visibility=visibility),whose&&(dataset.whose=whose),tooltip&&(dataset.tooltip=tooltip.trim()),classes)for(const cssClass of classes)classList.add(cssClass);return span.append(...Array.from(node.childNodes)),node.replaceWith(span),span}static async#localize(paramString,options){const content=game.i18n.localize(paramString);if(content===paramString)return ui.notifications.error(`Failed to localize ${paramString}!`),null;const result=document.createElement("span");return result.innerHTML=await TextEditor.enrichHTML(content,{...options,async:!0}),result}static#createTemplate(paramString,label,itemData){const params=this.#parseInlineParams(paramString,{first:"type"});if(!params)return null;if(!params.type)ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.TypeMissing"));else if(params.distance)if(objectHasKey(CONFIG.PF2E.areaTypes,params.type)){if(isNaN(+params.distance))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.DistanceNoNumber",{distance:params.distance})),null;if(params.width&&isNaN(+params.width))return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.WidthNoNumber",{width:params.width})),null;{params.traits||=itemData?.traits?.value?.toString()??"",label||(label=game.i18n.format("PF2E.TemplateLabel",{size:params.distance,unit:game.i18n.localize("PF2E.Foot"),shape:game.i18n.localize(CONFIG.PF2E.areaTypes[params.type])}));const html=document.createElement("span");return html.innerHTML=label,html.setAttribute("data-pf2-effect-area",params.type),html.setAttribute("data-pf2-distance",params.distance),params.traits!==""&&html.setAttribute("data-pf2-traits",params.traits),params.type==="line"&&html.setAttribute("data-pf2-width",params.width??"5"),html}}else return ui.notifications.error(game.i18n.format("PF2E.InlineTemplateErrors.TypeUnsupported",{type:params.type})),null;else return ui.notifications.error(game.i18n.localize("PF2E.InlineTemplateErrors.DistanceMissing")),null;return null}static#parseInlineParams(paramString,options={}){return paramString.split("|").reduce((result2,part,idx)=>{if(idx===0&&options.first&&!part.includes(":"))return result2[options.first]=part.trim(),result2;const colonIdx=part.indexOf(":"),portions=colonIdx>=0?[part.slice(0,colonIdx),part.slice(colonIdx+1)]:[part,""];return result2[portions[0]]=portions[1],result2},{})}static#createCheck({paramString,inlineLabel,item=null,actor=item?.actor??null}){const rawParams=this.#parseInlineParams(paramString,{first:"type"});if(!rawParams)return null;if(!rawParams.type)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const showDC=setHasElement(USER_VISIBILITIES,rawParams.showDC)?rawParams.showDC:actor?.hasPlayerOwner||actor?.isOfType("party")||game.settings.get("pf2e","metagame_showDC")?"all":"gm",params={...rawParams,type:rawParams.type,basic:rawParams.basic!==void 0&&["true",""].includes(rawParams.basic),showDC,traits:(()=>{const traits=[],itemTraits=item?.system.traits?.value??[];return rawParams.overrideTraits!=="true"&&traits.push(...itemTraits),rawParams.traits&&traits.push(...rawParams.traits.split(",").map(trait=>trait.trim())),Array.from(new Set(traits))})(),extraRollOptions:compact([...this.#createActionOptions(item),...rawParams.basic==="true"?["damaging-effect"]:[],...rawParams.options?.split(",").map(t=>t.trim())??[]]).sort()};rawParams.dc&&(params.dc=rawParams.dc),rawParams.defense&&(params.defense=rawParams.defense);const types=params.type.split(",");let adjustments=params.adjustment?.split(",")??["0"];if(types.length!==adjustments.length&&adjustments.length>1)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.AdjustmentLengthMismatch")),null;if(types.length>adjustments.length&&(adjustments=new Array(types.length).fill(adjustments[0])),adjustments.some(adj=>adj!==""&&isNaN(parseInt(adj))))return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.NonIntegerAdjustment")),null;const buttons=types.map((type,i)=>this.#createSingleCheck({actor,item,inlineLabel,params:{...params,type,adjustment:adjustments[i]}}));if(buttons.length===1)return buttons[0];{const checkGroup=document.createElement("div");checkGroup.setAttribute("data-pf2-checkgroup","");for(const button of buttons){if(button===null)return null;checkGroup.hasChildNodes()&&checkGroup.appendChild(document.createElement("br")),checkGroup.appendChild(button)}return checkGroup}}static#createSingleCheck({params,item,actor,inlineLabel}){const icon=(()=>{switch(params.type){case"fortitude":return fontAwesomeIcon("heart-pulse");case"reflex":return fontAwesomeIcon("person-running");case"will":return fontAwesomeIcon("brain");case"perception":return fontAwesomeIcon("eye");default:return fontAwesomeIcon("dice-d20")}})();icon.classList.add("icon");const name2=params.name??item?.name??params.type,localize=localizer("PF2E.InlineCheck"),label=(()=>{if(inlineLabel)return inlineLabel;if(tupleHasValue(SAVE_TYPES,params.type)){const saveName=game.i18n.localize(CONFIG.PF2E.saves[params.type]);return params.basic?localize("BasicWithSave",{save:saveName}):saveName}switch(params.type){case"flat":return game.i18n.localize("PF2E.FlatCheck");case"perception":return game.i18n.localize("PF2E.PerceptionLabel");default:{const shortForm=(()=>{if(objectHasKey(SKILL_EXPANDED,params.type))return SKILL_EXPANDED[params.type].shortForm;if(objectHasKey(SKILL_DICTIONARY,params.type))return params.type})();return shortForm?game.i18n.localize(CONFIG.PF2E.skills[shortForm]):params.type.split("-").map(word=>word.slice(0,1).toUpperCase()+word.slice(1)).join(" ")}}})(),createLabel=__name2(content=>createHTMLElement("span",{classes:["label"],innerHTML:content}),"createLabel"),anchor=createHTMLElement("a",{classes:["inline-check"],children:[icon,createLabel(label)],dataset:{pf2Traits:params.traits.toString()||null,pf2RollOptions:params.extraRollOptions.toString()||null,pf2RepostFlavor:name2,pf2ShowDc:params.showDC==="all"?null:params.showDC,pf2Label:localize("DCWithName",{name:name2}),pf2Adjustment:Number(params.adjustment)||null,pf2Roller:params.roller||null,pf2Check:sluggify(params.type)}});if(params.defense&¶ms.dc&&(anchor.dataset.tooltip=localize("Invalid",{message:localize("Errors.DCAndDefense")}),anchor.dataset.invalid="true"),!["flat","fortitude","reflex","will"].includes(params.type)&¶ms.defense&&(anchor.dataset.pf2Defense=params.defense),params.type&¶ms.dc){const checkDC=params.dc==="@self.level"?params.dc:getCheckDC({name:name2,params,item,actor});if(anchor.dataset.pf2Dc=checkDC,checkDC!=="@self.level"){const dc=params.dc===""?NaN:Number(checkDC),displayedDC=isNaN(dc)?checkDC:`${dc+Number(params.adjustment)}`,text=anchor.innerText;anchor.querySelector("span.label")?.replaceWith(createLabel(game.i18n.format("PF2E.DCWithValueAndVisibility",{role:params.showDC,dc:displayedDC,text})))}}return params.roller==="self"&&actor&&!actor.canUserModify(game.user,"update")?createHTMLElement("span",{children:[anchor.innerText]}):anchor}static async#createDamageRoll(args){const params=this.#parseInlineParams(args.paramString,{first:"formula"});if(!params||!params.formula)return ui.notifications.warn(game.i18n.localize("PF2E.InlineCheck.Errors.TypeMissing")),null;const item=args.rollData?.item instanceof ItemPF2e?args.rollData?.item:null,actor=(args.rollData?.actor instanceof ActorPF2e?args.rollData?.actor:null)??item?.actor??null,domains=params.domains?.split(",");if(domains?.some(d=>!/^[a-z][-a-z0-9]+-damage$/.test(d)))return ui.notifications.warn(game.i18n.format("PF2E.InlineCheck.Errors.InvalidDomains",{type:"@Damage"})),null;const traits=(()=>{const fromParams=params.traits?.split(",").flatMap(t=>t.trim()||[])??[],fromItem=item?.system.traits?.value??[];return params.overrideTraits==="true"?fromParams:uniq([...fromParams,...fromItem])})().sort(),extraRollOptions=compact([...params.options?.split(",").map(t=>t.trim())??[],...this.#createActionOptions(item)]).sort(),result=await augmentInlineDamageRoll(params.formula,{skipDialog:!0,actor,item,domains,traits,extraRollOptions}),baseFormula=(()=>actor?new DamageRoll(params.formula,{...item?.getRollData()??{},actor:{level:(item&&"level"in item?item.level:null)??1}}).formula:null)(),roll=result?.template.damage.roll??new DamageRoll(params.formula,args.rollData),formula=roll.formula,element=createHTMLElement("a",{classes:compact(["inline-roll","roll",baseFormula&&baseFormula!==formula?"altered":null]),children:[damageDiceIcon(roll),args.inlineLabel??formula],dataset:{formula:roll._formula,tooltip:args.inlineLabel?formula:baseFormula&&baseFormula!==formula?game.i18n.format("PF2E.InlineDamage.Base",{formula:baseFormula}):null,damageRoll:params.formula,pf2Domains:domains?.join(",")||null,pf2BaseFormula:result?params.formula:null,pf2Traits:traits.toString()||null,pf2RollOptions:extraRollOptions.toString()||null,pf2ItemId:item?.id}});return roll.instances.length>0&&roll.instances.every(i=>i.persistent)&&(element.draggable=!0,element.dataset.persistent="true"),element}static#createActionOptions(item){return!item?.isOfType("action","feat")||!item.actionCost?[]:compact([`action:${item.slug??sluggify(item.name)}`,item.actionCost.value?`action:cost:${item.actionCost.value}`:null])}}function getCheckDC({name:name2,params,item=null,actor=item?.actor??null}){const{type}=params,dc=params.dc,base=(()=>{if(dc?.startsWith("resolve")&&(item||actor)){params.immutable||="true";const resolve=dc.match(/resolve\((.+?)\)$/),value=resolve&&resolve?.length>0?resolve[1]:"";return Number(__name2(resolveString=>{try{const rollData=item?.getRollData()??actor?.getRollData()??{};return Roll.safeEval(Roll.replaceFormulaData(resolveString,rollData))}catch{return 0}},"saferEval")(value))}return Number(dc)||void 0})();if(base){const getStatisticValue=__name2(selectors=>{if(item?.actor&¶ms.immutable!=="true"){const{actor:actor2}=item,{synthetics}=actor2,modifier=new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base-10,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,selectors,"base")}),stat=new Statistic(actor2,{slug:type,label:name2,domains:selectors,modifiers:[modifier]});return String(stat.dc.value)}return base.toString()},"getStatisticValue"),slugName=sluggify(name2);if(type==="flat")return params.immutable==="false"?getStatisticValue(["inline-dc",`${slugName}-inline-dc`]):base.toString();{const selectors=["all","inline-dc",`${slugName}-inline-dc`];return getStatisticValue(selectors)}}return"0"}__name(getCheckDC,"getCheckDC"),__name2(getCheckDC,"getCheckDC");async function augmentInlineDamageRoll(baseFormula,args){const{name:name2,actor,item,traits,extraRollOptions}=args;try{const rollData=item?.getRollData()??actor?.getRollData()??{};rollData.actor??={level:(item&&"level"in item?item.level:null)??1};const base=extractBaseDamage(new DamageRoll(baseFormula,rollData)),domains=compact(["damage","inline-damage",item?`${item.id}-inline-damage`:null,item?`${sluggify(item.slug??item.name)}-inline-damage`:null,args.domains].flat()),options=new Set([...actor?.getRollOptions(domains)??[],...item?.getRollOptions("item")??[],...traits??[],...extraRollOptions??[]]),firstBase=base.at(0);if(!firstBase)return null;if(actor?.isOfType("npc")&&(actor.isElite||actor.isWeak)){const value=options.has("item:frequency:limited")?4:2;firstBase.terms?.push({dice:null,modifier:actor.isElite?value:-value})}item?.isOfType("physical")&&(firstBase.materials=uniq(compact([item.material.effects,firstBase.materials].flat()).sort()));const{modifiers,dice}=(()=>{if(!(actor instanceof ActorPF2e))return{modifiers:[],dice:[]};const extractOptions={resolvables:rollData??{},test:options};return processDamageCategoryStacking(base,{modifiers:extractModifiers(actor.synthetics,domains,extractOptions),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options})})(),formulaData={base,modifiers,dice,ignoredResistances:[]},isAttack=!!traits?.includes("attack"),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options,self:(()=>actor?{actor,token:actor.token,item:item||null,statistic:null,modifiers}:null)(),traits:traits?.filter(t=>t in CONFIG.PF2E.actionTraits)??[]};if(!args.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const{formula,breakdown}=createDamageFormula(formulaData);if(!formula||formula==="{}")return null;const roll=new DamageRoll(formula);return{template:{name:name2??item?.name??actor?.name??"",damage:{roll,breakdown},modifiers:[...modifiers,...dice],materials:item?.isOfType("physical")?item.system.material.effects:[]},context}}catch(ex){return console.error(`Failed to parse inline @Damage ${baseFormula}:`,ex),null}}__name(augmentInlineDamageRoll,"augmentInlineDamageRoll"),__name2(augmentInlineDamageRoll,"augmentInlineDamageRoll");class CriticalHitAndFumbleCards{static{__name(this,"CriticalHitAndFumbleCards")}static{__name2(this,"CriticalHitAndFumbleCards")}static rollTypes=["attack-roll","spell-attack-roll"];static diceSoNice;static appendButtonsOption;static handleDraw(message){if(message.isAuthor&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"",firstDie=message.rolls.at(0)?.dice[0];firstDie&&firstDie.faces===20&&this.rollTypes.includes(type)&&(firstDie.total===20?this.automaticDraw("critTable"):firstDie.total===1&&this.automaticDraw("fumbleTable"))}}static automaticDraw(table){this.diceSoNice??=!!game.modules.get("dice-so-nice")?.active,this.diceSoNice?Hooks.once("diceSoNiceRollComplete",()=>{this.drawFromTable(table,!0)}):this.drawFromTable(table,!0)}static drawFromTable(table,automatic=!1){const tableId=table==="critTable"?"FTEpsIWWVrDj0jNG":"WzMGWMIrrPvSp75D";game.packs.get("pf2e.rollable-tables",{strict:!0}).getDocument(tableId).then(rollTable=>{rollTable?.draw({displayChat:!1}).then(draw=>{const data={roll:draw.roll,messageData:{}};automatic&&!this.diceSoNice&&(data.messageData.sound=void 0),rollTable?.toMessage(draw.results,data)})})}static appendButtons(message,$html){if(this.appendButtonsOption??=game.settings.get("pf2e","critFumbleButtons"),this.appendButtonsOption&&(message.isAuthor||game.user.isGM)&&message.isContentVisible){const type=message.flags.pf2e.context?.type??"";if(this.rollTypes.includes(type)){const critButton=$(`<button class="dice-total-fullDamage-btn" style="width: 22px; height:22px; font-size:10px;line-height:1px"><i class="fa-solid fa-thumbs-up" title="${game.i18n.localize("PF2E.CriticalHitCardButtonTitle")}"></i></button>`),fumbleButton=$(`<button class="dice-total-fullDamage-btn" style="width: 22px; height:22px; font-size:10px;line-height:1px"><i class="fa-solid fa-thumbs-down" title="${game.i18n.localize("PF2E.CriticalFumbleCardButtonTitle")}"></i></button>`),btnContainer1=$('<span class="dmgBtn-container" style="position:absolute; right:0; bottom:1px;"></span>');btnContainer1.append(critButton),btnContainer1.append(fumbleButton),critButton.on("click",event2=>{event2.stopPropagation(),this.drawFromTable("critTable"),event2.currentTarget.blur()}),fumbleButton.on("click",event2=>{event2.stopPropagation(),this.drawFromTable("fumbleTable"),event2.currentTarget.blur()}),$html.find(".dice-total").wrapInner('<span id="value"></span>').append(btnContainer1)}}}}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.baseRank<=spellLevel&&!s.isCantrip&&!s.isFocusSpell&&!s.isRitual).reduce((result,spell)=>(result[spell.baseRank]=[...result[spell.baseRank]||[],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:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")},craft:{icon:fontAwesomeIcon("hammer").outerHTML,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 data=await createConsumableFromSpell(spell,{type:consumableType,heightenedLevel:spellLevel});return craftItem(new ItemProxyPF2e(data),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 ElementalBlast{static{__name(this,"ElementalBlast")}static{__name2(this,"ElementalBlast")}actor;statistic;item;configs;infusion;constructor(actor){if(!actor.isOfType("character"))throw ErrorPF2e("Must construct with a PC");this.actor=actor,this.statistic=this.actor.getStatistic("impulse"),this.item=this.actor.itemTypes.action.find(a=>a.slug==="elemental-blast")??null,this.infusion=this.#prepareBlastInfusion(),this.configs=this.#prepareBlastConfigs()}static#blastConfigSchema=(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({element:new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.elementTraits,initial:void 0}),label:new fields2.StringField({required:!0,blank:!1,initial:void 0}),img:new fields2.FilePathField({required:!0,categories:["IMAGE"],nullable:!1,initial:"systems/pf2e/icons/default-icons/spell.svg"}),damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),dieFaces:new fields2.NumberField({required:!0,nullable:!1,integer:!0,choices:[6,8],initial:void 0}),range:new fields2.NumberField({required:!0,nullable:!1,integer:!0,positive:!0,initial:void 0})})})();static#blastInfusionSchema=(()=>{const{fields:fields2}=foundry.data;return new fields2.SchemaField({damageTypes:new fields2.ArrayField(new fields2.StringField({required:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:void 0})),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1}),max:new fields2.NumberField({required:!0,integer:!0,positive:!0,nullable:!1})},{required:!1,nullable:!0,initial:null}),traits:new fields2.SchemaField({melee:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0})),ranged:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,choices:()=>CONFIG.PF2E.weaponTraits,initial:void 0}))})})})();get actionCost(){const cost=this.item?.flags.pf2e.rulesSelections.actionCost??1;if(cost!==1&&cost!==2)throw ErrorPF2e("Action cost must be 1 or 2");return cost}#prepareBlastConfigs(){const{item,statistic,actionCost,infusion}=this;if(!item||!statistic)return[];const{kineticist}=this.actor.flags.pf2e;if(!isObject(kineticist)||!("elementalBlast"in kineticist)||!isObject(kineticist.elementalBlast))return[];const schema=ElementalBlast.#blastConfigSchema,damageTypeSelections=(()=>{const flag=item.flags.pf2e.damageSelections;return isObject(flag)?flag:{}})(),blasts=Object.values(kineticist.elementalBlast).filter(b=>isObject(b)&&"element"in b).map(b=>schema.clean(b)),validationFailures=blasts.flatMap(b=>schema.validate(b)??[]);for(const failure of validationFailures)throw failure.asError();item.flags.pf2e.attackItemBonus=statistic.check.modifiers.find(m=>m.enabled&&["item","potency"].includes(m.type))?.value??0;const maps=(()=>{const domains=[...statistic.check.domains,"elemental-blast-attack-roll"],options=this.actor.getRollOptions(domains),modifier=statistic.check.mod,mapsFor=__name2(melee=>{const penalties=calculateMAPs(this.#createModifiedItem({melee})??item,{domains,options});return{map1:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map1),penalty:penalties.map1}),map2:game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(modifier+penalties.map2),penalty:penalties.map2})}},"mapsFor");return{melee:mapsFor(!0),ranged:mapsFor(!1)}})();return blasts.map(blast=>{const damageTypes2=uniq(compact([blast.damageTypes,this.infusion?.damageTypes].flat())).map(dt=>({value:dt,label:game.i18n.localize(CONFIG.PF2E.damageTypes[dt]),icon:DAMAGE_TYPE_ICONS[dt]??"",selected:damageTypeSelections[blast.element]===dt})).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),firstDamageType=damageTypes2.at(0);firstDamageType&&!damageTypes2.some(dt=>dt.selected)&&(firstDamageType.selected=!0);const maxRange=infusion?.range?.max??blast.range,range2=infusion?.range?.increment?{increment:infusion.range.increment,max:infusion.range.increment*6,label:game.i18n.format("PF2E.Action.Range.IncrementN",{n:infusion.range.increment})}:{increment:null,max:maxRange,label:game.i18n.format("PF2E.Action.Range.MaxN",{n:maxRange})};return{...blast,statistic,maps,item,actionCost,damageTypes:damageTypes2,range:range2}})}#prepareBlastInfusion(){const schema=ElementalBlast.#blastInfusionSchema,flag=this.actor.flags.pf2e.kineticist,infusionData=isObject(flag)&&isObject(flag.elementalBlast)?flag.elementalBlast.infusion:null;return isObject(infusionData)?schema.clean(infusionData):null}#getBlastConfig(element,damageType){const config=this.configs.find(c=>c.element===element&&c.damageTypes.some(t=>t.value===damageType));if(!config)throw ErrorPF2e(`Elemental blast configuration of element ${element} and damage type ${damageType} not found.`);return config}#createModifiedItem({melee,config,damageType}){const{item}=this;if(!item)return null;const traits=(()=>{const baseTraits=this.item?.system.traits.value??[],infusionTraits=melee?this.infusion?.traits.melee:this.infusion?.traits.ranged;return uniq(compact([baseTraits,infusionTraits,config?.element,damageType].flat()).filter(t=>t in CONFIG.PF2E.actionTraits)).sort()})(),clone=item.clone({system:{traits:{value:traits}}},{keepId:!0});return clone.range=melee?null:config?.range??null,clone}async attack(params){const{statistic,actionCost}=this;if(!(statistic&&this.item))throw ErrorPF2e("Unable to blast");if(!this.actor.rollOptions.all["self:effect:kinetic-aura"])throw ErrorPF2e("No kinetic gate");const{element,damageType}=params;if(!element)throw ErrorPF2e("No element provided");if(!objectHasKey(elementTraits,element))throw ErrorPF2e(`Unrecognized element: ${element}`);if(!damageType)throw ErrorPF2e("No damage type provided");if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))throw ErrorPF2e(`Unrecognized damage type: ${damageType}`);const blastConfig=this.#getBlastConfig(element,damageType),melee=!!(params.melee??=!0),item=this.#createModifiedItem({config:blastConfig,damageType,melee});if(!item)return null;const thisToken=this.actor.getActiveTokens(!0,!1).shift()??null,targetToken=game.user.targets.first()??null;if(!params.melee&&thisToken&&targetToken&&thisToken.distanceTo(targetToken)>blastConfig.range.max)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null;const actionSlug="elemental-blast",blastStatistic=statistic.extend({check:{domains:[`${actionSlug}-attack-roll`],modifiers:AttackTraitHelpers.createAttackModifiers({item})}}),label=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{title:item.name,glyph:actionCost.toString(),subtitle:game.i18n.format("PF2E.ActionsCheck.x-attack-roll",{type:statistic.label})}),meleeOrRanged=params.melee?"melee":"ranged",mapIncreases=Math.clamped(params.mapIncreases??0,0,2)||0;return blastStatistic.roll({identifier:`${blastConfig.element}.${params.damageType}.${meleeOrRanged}.${actionCost}`,action:actionSlug,attackNumber:mapIncreases+1,target:targetToken?.actor??null,token:thisToken?.document??null,item,label,traits:item.system.traits.value,melee,damaging:!0,dc:{slug:"ac"},extraRollOptions:[`action:${actionSlug}`,`action:cost:${actionCost}`,meleeOrRanged,`item:${meleeOrRanged}`],...eventToRollParams(params.event,{type:"check"})})}async damage(params){if(!this.statistic)return null;const melee=!!(params.melee??=!0),blastConfig=this.#getBlastConfig(params.element,params.damageType);if(!blastConfig)return null;const item=this.#createModifiedItem({config:blastConfig,damageType:params.damageType,melee});if(!item)return null;const outcome=params.outcome??"success",meleeOrRanged=melee?"melee":"ranged",actionCost=Math.clamped(Number(params.actionCost??this.actionCost),1,2)||1,actionSlug="elemental-blast",domains=["damage","attack-damage","impulse-damage",`${actionSlug}-damage`],targetToken=game.user.targets.first()??null;item.flags.pf2e.attackItemBonus=blastConfig.statistic.check.modifiers.find(m=>m.enabled&&["item","potency"].includes(m.type))?.value??0;const context=await this.actor.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:this.statistic.check,item,target:{token:targetToken},domains,outcome,melee,checkContext:params.checkContext,options:new Set([`action:${actionSlug}`,`action:cost:${actionCost}`,meleeOrRanged,`item:${meleeOrRanged}`,`item:damage:type:${params.damageType}`,...item.traits])}),baseDamage={category:null,damageType:params.damageType,terms:[{dice:{number:1,faces:blastConfig.dieFaces},modifier:0}]},damageSynthetics=processDamageCategoryStacking([baseDamage],{modifiers:extractModifiers(context.self.actor.synthetics,domains,{test:context.options,resolvables:{blast:item}}),dice:extractDamageDice(context.self.actor.synthetics.damageDice,domains,{test:context.options,resolvables:{blast:item,target:context.target?.actor??null}}),test:context.options}),extraModifiers=compact([...damageSynthetics.modifiers,this.#strengthModToDamage(item,domains)]),modifiers=new StatisticModifier("",extraModifiers).modifiers,formulaData={dice:damageSynthetics.dice,modifiers,base:[baseDamage],ignoredResistances:[]},damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,traits:item.system.traits.value,...eventToRollParams(params.event,{type:"damage"})};if(!params.getFormula&&!damageContext.skipDialog&&!await new DamageModifierDialog({formulaData,context:damageContext}).resolve())return null;const damageData=createDamageFormula(formulaData,outcome==="success"?DEGREE_OF_SUCCESS.SUCCESS:DEGREE_OF_SUCCESS.CRITICAL_SUCCESS),roll=new DamageRoll(damageData.formula);if(params.getFormula)return roll.formula;const damageTemplate={name:`${game.i18n.localize("PF2E.DamageRoll")}: ${item.name}`,materials:[],modifiers,damage:{roll,breakdown:damageData.breakdown}};return DamagePF2e.roll(damageTemplate,damageContext)}#strengthModToDamage(item,domains){if(!item.range)return null;const strengthModValue=this.actor.abilities.str.mod,{traits}=item,modifierValue=traits.has("thrown")?strengthModValue:traits.has("propulsive")?strengthModValue<0?strengthModValue:Math.floor(strengthModValue/2):null;return typeof modifierValue=="number"?new ModifierPF2e({slug:"str",label:CONFIG.PF2E.abilities.str,ability:"str",modifier:modifierValue,type:"ability",adjustments:extractModifierAdjustments(this.actor.synthetics.modifierAdjustments,domains,"str")}):null}async setDamageType({element,damageType}){if(!this.configs.some(c=>c.element===element&&c.damageTypes.some(dt=>dt.value===damageType)))throw ErrorPF2e(`Damage type "${damageType}" not available for ${element}`);await this.item?.update({[`flags.pf2e.damageSelections.${element}`]:damageType})}}class CheckModifiersDialog extends Application{static{__name(this,"CheckModifiersDialog")}static{__name2(this,"CheckModifiersDialog")}check;context;resolve;isResolved=!1;#originallyEnabled;constructor(check,resolve,context={options:new Set}){const title=(()=>{const maybeWithHTML=context.title?.trim()||check.slug;if(!maybeWithHTML.includes("<"))return maybeWithHTML.trim();const div=document.createElement("div");return div.innerHTML=maybeWithHTML,div.querySelector(".action-glyph, .pf2-icon")?.remove(),div.innerText.trim()})();super({title}),this.check=check,this.resolve=resolve,this.context=context,this.#originallyEnabled=new Set(check.modifiers.filter(m=>m.enabled))}static get defaultOptions(){return{...super.defaultOptions,template:"systems/pf2e/templates/chat/check-modifiers-dialog.hbs",classes:["roll-modifiers-dialog","dice-checks","dialog"],popOut:!0,width:380,height:"auto"}}async getData(){const fortune=this.context.rollTwice==="keep-higher",misfortune=this.context.rollTwice==="keep-lower",none=fortune===misfortune,rollMode=this.context.rollMode==="roll"?game.settings.get("core","rollMode"):this.context.rollMode;return{appId:this.id,modifiers:this.check.modifiers.map(m=>({...m,hideIfDisabled:!this.#originallyEnabled.has(m)&&m.hideIfDisabled})),totalModifier:this.check.totalModifier,rollModes:CONFIG.Dice.rollModes,rollMode,showCheckDialogs:game.user.settings.showCheckDialogs,substitutions:this.#resolveSubstitutions(),fortune,none,misfortune}}#resolveSubstitutions(){this.context.substitutions??=[];const hasRequired={fortune:this.context.substitutions.some(s=>s.required&&s.effectType==="fortune"),misfortune:this.context.substitutions.some(s=>s.required&&s.effectType==="misfortune")};return this.context.substitutions.map(substitution=>{const toggleable=!hasRequired[substitution.effectType],selected=substitution.required?!0:substitution.selected&&toggleable;return{...substitution,selected,toggleable}})}activateListeners($html){const html=$html[0];htmlQuery(html,"button.roll")?.addEventListener("click",()=>{this.resolve(!0),this.isResolved=!0,this.close()});for(const checkbox of htmlQueryAll(html,".substitutions input[type=checkbox]"))checkbox.addEventListener("click",()=>{const substitutions=this.context.substitutions??[],index=Number(checkbox.dataset.subIndex),toggledSub=substitutions.at(index);if(!toggledSub)return;toggledSub.selected=toggledSub.required||checkbox.checked;const options=this.context.options??=new Set;for(const substitution of substitutions){const option=`substitute:${substitution.slug}`;substitution.selected?options.add(option):options.delete(option)}this.context.substitutions=this.#resolveSubstitutions().map(s=>omit(s,["toggleable"])),this.check.calculateTotal(this.context.options),this.render()});for(const checkbox of htmlQueryAll(html,".modifier-container input[type=checkbox]"))checkbox.addEventListener("click",()=>{const index=Number(checkbox.dataset.modifierIndex);this.check.modifiers[index].ignored=!checkbox.checked,this.check.calculateTotal(),this.render()});const addModifierButton=htmlQuery(html,"button.add-modifier");addModifierButton?.addEventListener("click",()=>{const parent=addModifierButton.parentElement,value=Number(parent.querySelector(".add-modifier-value")?.value||1),type=String(parent.querySelector(".add-modifier-type")?.value);let name2=String(parent.querySelector(".add-modifier-name")?.value);const errors=[];if(Number.isNaN(value)?errors.push("Modifier value must be a number."):value===0&&errors.push("Modifier value must not be zero."),!setHasElement(MODIFIER_TYPES,type))throw ErrorPF2e("Unexpected invalid modifier type");(!name2||!name2.trim())&&(name2=game.i18n.localize(value<0?`PF2E.PenaltyLabel.${type}`:`PF2E.BonusLabel.${type}`)),errors.length>0?ui.notifications.error(errors.join(" ")):(this.check.push(new ModifierPF2e(name2,value,type)),this.render())});for(const rollTwice of htmlQueryAll(html,".fate input[type=radio]"))rollTwice.addEventListener("click",()=>{this.context.rollTwice=rollTwice.value||!1});const rollModeInput=htmlQuery(html,"select[name=rollmode]");rollModeInput?.addEventListener("change",()=>{const rollMode=rollModeInput.value;if(!tupleHasValue(Object.values(CONST.DICE_ROLL_MODES),rollMode))throw ErrorPF2e("Unexpected roll mode");this.context.rollMode=rollMode});const toggle=htmlQuery(html,"input[data-action=change-show-default]");toggle?.addEventListener("click",async()=>{await game.user.update({"flags.pf2e.settings.showCheckDialogs":toggle.checked})})}async close(options){this.isResolved||this.resolve(!1),super.close(options)}_injectHTML($html){super._injectHTML($html),$html[0]?.querySelector("button.roll")?.focus()}}class CheckPF2e{static{__name(this,"CheckPF2e")}static{__name2(this,"CheckPF2e")}static async roll(check,context={},event2=null,callback){event2&&foundry.utils.mergeObject(context,eventToRollParams(event2,{type:"check"})),context.skipDialog??=!game.user.settings.showCheckDialogs,context.createMessage??=!0,Array.isArray(context.options)&&(context.options=new Set(context.options));const rollOptions=context.options??new Set;typeof context.mapIncreases=="number"&&rollOptions.add(`map:increases:${context.mapIncreases}`),rollOptions.has("secret")&&(context.rollMode??=game.user.isGM?"gmroll":"blindroll"),context.rollMode??="roll",rollOptions.size>0&&!context.isReroll&&check.calculateTotal(rollOptions);const substitutions=context.substitutions??=[],requiredSubstitution=context.substitutions.find(s=>s.required&&s.selected);if(requiredSubstitution)for(const substitution of context.substitutions)substitution.required=substitution===requiredSubstitution,substitution.selected=substitution===requiredSubstitution;if(!context.skipDialog&&context.type!=="flat-check"&&!await new Promise(resolve=>{new CheckModifiersDialog(check,resolve,context).render(!0)}))return null;const extraTags=[],isReroll=context.isReroll??!1;isReroll&&(context.rollTwice=!1);const[dice,tagsFromDice]=(()=>{const substitution=substitutions.find(s=>s.selected),rollTwice=context.rollTwice??!1,fortuneMisfortune=new Set(compact([substitution?.effectType,rollTwice==="keep-higher"?"fortune":rollTwice==="keep-lower"?"misfortune":null]));for(const trait of fortuneMisfortune)rollOptions.add(trait);if(rollOptions.has("fortune")&&rollOptions.has("misfortune")){for(const sub of substitutions)rollOptions.delete(`substitute:${sub.slug}`),check.calculateTotal(rollOptions);return["1d20",["PF2E.TraitFortune","PF2E.TraitMisfortune"]]}else if(substitution){const effectType={fortune:"PF2E.TraitFortune",misfortune:"PF2E.TraitMisfortune"}[substitution.effectType],extraTag=game.i18n.format("PF2E.SpecificRule.SubstituteRoll.EffectType",{type:game.i18n.localize(effectType),substitution:reduceItemName(game.i18n.localize(substitution.label))});return[substitution.value.toString(),[extraTag]]}else return context.rollTwice==="keep-lower"?["2d20kl",["PF2E.TraitMisfortune"]]:context.rollTwice==="keep-higher"?["2d20kh",["PF2E.TraitFortune"]]:["1d20",[]]})();extraTags.push(...tagsFromDice);const options={type:context.type,identifier:context.identifier,action:context.action&&sluggify(context.action)||null,rollerId:game.userId,isReroll,totalModifier:check.totalModifier,damaging:!!context.damaging,domains:context.domains},totalModifierPart=signedInteger(check.totalModifier,{emptyStringZero:!0}),roll=await new CheckRoll(`${dice}${totalModifierPart}`,{},options).evaluate({async:!0}),dosAdjustments=(()=>{if(isNil(context.dc))return{};const naturalTotal=compact(roll.dice.map(d=>d.results.find(r=>r.active&&!r.discarded)?.result??null)).shift(),temporaryRollOptions=new Set([...rollOptions,`check:total:${roll.total}`,`check:total:natural:${naturalTotal}`]);return context.dosAdjustments?.filter(a=>a.predicate?.test(temporaryRollOptions)??!0).reduce((record,data)=>{for(const outcome of["all",...DEGREE_OF_SUCCESS_STRINGS])data.adjustments[outcome]&&(record[outcome]=foundry.utils.deepClone(data.adjustments[outcome]));return record},{})??{}})(),degree=context.dc?new DegreeOfSuccess(roll,context.dc,dosAdjustments):null;degree&&(context.outcome=DEGREE_OF_SUCCESS_STRINGS[degree.value],context.unadjustedOutcome=DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted],roll.options.degreeOfSuccess=degree.value);const notes=context.notes?.map(n=>n instanceof RollNotePF2e?n:new RollNotePF2e(n)).filter(note=>{if(!note.predicate.test([...rollOptions,...note.rule?.item.getRollOptions("parent")??[]]))return!1;if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))})??[],notesList=RollNotePF2e.notesToHTML(notes),item=context.item??null,flavor=await(async()=>{const result=await this.#createResultFlavor({degree,target:context.target??null}),tags=this.#createTagFlavor({check,context,extraTags}),title=(context.title??check.slug).trim();return[title.startsWith("<h4")?title:(()=>{const strong=document.createElement("strong");return strong.innerHTML=title,createHTMLElement("h4",{classes:["action"],children:[strong]})})(),result??[],tags,notesList].flat().map(e=>typeof e=="string"?e:e.outerHTML).join("")})(),contextFlag={...context,type:context.type??"check",identifier:context.identifier??null,item:void 0,dosAdjustments,actor:context.actor?.id??null,token:context.token?.id??null,domains:context.domains??[],target:context.target?{actor:context.target.actor.uuid,token:context.target.token.uuid}:null,options:Array.from(rollOptions).sort(),notes:notes.map(n=>n.toObject()),rollMode:context.rollMode,rollTwice:context.rollTwice??!1,title:context.title??"PF2E.Check.Label",traits:context.traits??[],substitutions,dc:context.dc?omit(context.dc,["statistic"]):null,skipDialog:context.skipDialog,isReroll:context.isReroll??!1,outcome:context.outcome??null,unadjustedOutcome:context.unadjustedOutcome??null};delete contextFlag.item;const message=await(()=>{const flags={core:context.type==="initiative"?{initiativeRoll:!0}:{},pf2e:{context:contextFlag,modifierName:check.slug,modifiers:check.modifiers.map(m=>m.toObject()),origin:item?.getOriginData()}},speaker=ChatMessagePF2e.getSpeaker({actor:context.actor,token:context.token}),{rollMode}=contextFlag,create=context.createMessage;return roll.toMessage({speaker,flavor,flags},{rollMode,create})})();if(callback){const msg=message instanceof ChatMessagePF2e?message:new ChatMessagePF2e(message),evt=event2&&event2 instanceof Event?event2:event2?.originalEvent??null;await callback(roll,context.outcome,msg,evt)}return item?.isOfType("weapon")&&item.traits.has("consumable")&&item.actor.items.has(item.id)&&item.quantity>0&&await item.update({system:{quantity:item.quantity-1}}),roll}static#createTagFlavor({check,context,extraTags}){const toTagElement=__name2((tag,cssClass=null)=>{const span=document.createElement("span");return span.classList.add("tag"),cssClass&&span.classList.add(`tag_${cssClass}`),span.innerText=tag.label,tag.name&&(span.dataset.slug=tag.name),tag.description&&(span.dataset.tooltip=tag.description),span},"toTagElement"),traits=uniqBy(context.traits?.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)).map(trait=>(trait.label=game.i18n.localize(trait.label),trait))??[],t=>t.name).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t))??[],{item}=context,itemTraits=item?.isOfType("weapon","melee")&&context.type!=="saving-throw"?Array.from(item.traits).map(t=>{const dictionary=item.isOfType("spell")?CONFIG.PF2E.spellTraits:CONFIG.PF2E.npcAttackTraits,obj=traitSlugToObject(t,dictionary);return obj.label=game.i18n.localize(obj.label),obj}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)).map(t=>toTagElement(t,"alt")):[],properties=(()=>{const range2=item?.isOfType("action","weapon")?item.range:null,label=createActionRangeLabel(range2);if(label&&(range2?.increment||range2?.max)){const slug=range2.increment?`range-increment-${range2.increment}`:`range-${range2.max}`;return[toTagElement({name:slug,label,description:"PF2E.Item.Weapon.RangeIncrementN.Hint"},"secondary")]}else return[]})(),traitsAndProperties=createHTMLElement("div",{classes:["tags","traits"],dataset:{tooltipClass:"pf2e"}});if(itemTraits.length===0&&properties.length===0)traitsAndProperties.append(...traits);else{const verticalBar=document.createElement("hr");verticalBar.className="vr",traitsAndProperties.append(...[traits,verticalBar,itemTraits,properties].flat())}const modifiers=check.modifiers.filter(m=>m.enabled).map(modifier=>{const sign=modifier.modifier<0?"":"+",label=`${modifier.label} ${sign}${modifier.modifier}`;return toTagElement({name:modifier.slug,label},"transparent")}),tagsFromOptions=extraTags.map(t=>toTagElement({label:game.i18n.localize(t)},"transparent")),modifiersAndExtras=createHTMLElement("div",{classes:["tags","modifiers"],children:[...modifiers,...tagsFromOptions]});return compact([traitsAndProperties.childElementCount>0?traitsAndProperties:null,document.createElement("hr"),modifiersAndExtras])}static async rerollFromMessage(message,{heroPoint=!1,keep="new"}={}){if(!(message.isAuthor||game.user.isGM)){ui.notifications.error(game.i18n.localize("PF2E.RerollMenu.ErrorCantDelete"));return}const actor=game.actors.get(message.speaker.actor??"");let rerollFlavor=game.i18n.localize(`PF2E.RerollMenu.MessageKeep.${keep}`);if(heroPoint)if(actor?.isOfType("character")){const heroPointCount=actor.heroPoints.value;if(heroPointCount)await actor.update({"system.resources.heroPoints.value":Math.clamped(heroPointCount-1,0,actor.heroPoints.max)}),rerollFlavor=game.i18n.format("PF2E.RerollMenu.MessageHeroPoint",{name:actor.name});else{ui.notifications.warn(game.i18n.format("PF2E.RerollMenu.WarnNoHeroPoint",{name:actor.name}));return}}else{ui.notifications.error("PF2E.RerollMenu.ErrorNoActor",{localize:!0});return}const systemFlags=foundry.utils.deepClone(message.flags.pf2e),context=systemFlags.context;if(!isCheckContextFlag(context))return;context.skipDialog=!0,context.isReroll=!0;const oldRoll=message.rolls.at(0);if(!(oldRoll instanceof CheckRoll))throw ErrorPF2e("Unexpected error retrieving prior roll");const unevaluatedNewRoll=oldRoll.clone();unevaluatedNewRoll.options.isReroll=!0,Hooks.callAll("pf2e.preReroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),unevaluatedNewRoll,heroPoint,keep);const newRoll=await unevaluatedNewRoll.evaluate({async:!0});Hooks.callAll("pf2e.reroll",Roll.fromJSON(JSON.stringify(oldRoll.toJSON())),newRoll,heroPoint,keep);let keptRoll=newRoll,[oldRollClass,newRollClass]=["pf2e-reroll-discard",""];(keep==="higher"&&oldRoll.total>newRoll.total||keep==="lower"&&oldRoll.total<newRoll.total)&&([oldRollClass,newRollClass]=[newRollClass,oldRollClass],keptRoll=oldRoll);const degree=(()=>{const{dc}=context;if(!dc)return null;if(dc.slug==="armor"){const targetActor=(()=>{const{target}=context;if(!target?.actor)return null;const maybeActor=fromUuidSync(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})();dc.statistic=targetActor?.armorClass}return new DegreeOfSuccess(newRoll,dc,context.dosAdjustments)})(),useNewRoll=keptRoll===newRoll&&!!degree;useNewRoll&°ree&&(newRoll.options.degreeOfSuccess=degree.value);const renders={old:await CheckPF2e.renderReroll(oldRoll,{isOld:!0}),new:await CheckPF2e.renderReroll(newRoll,{isOld:!1})},rerollIcon=fontAwesomeIcon(heroPoint?"hospital-symbol":"dice");rerollIcon.classList.add("pf2e-reroll-indicator"),rerollIcon.setAttribute("title",rerollFlavor);const oldFlavor=message.flavor??"";context.outcome=useNewRoll?DEGREE_OF_SUCCESS_STRINGS[degree.value]:context.outcome;const newFlavor=useNewRoll?await(async()=>{const parsedFlavor=document.createElement("div");parsedFlavor.innerHTML=oldFlavor;const target=context.target??null,targetFlavor=await this.#createResultFlavor({degree,target});targetFlavor&&htmlQuery(parsedFlavor,".target-dc-result")?.replaceWith(targetFlavor);for(const element of htmlQueryAll(parsedFlavor,".roll-note"))element.remove();const notesText=(context.notes?.map(n=>new RollNotePF2e(n))??[]).filter(note=>{if(!context.dc||note.outcome.length===0)return!0;const outcome=context.outcome??context.unadjustedOutcome;return!!(outcome&¬e.outcome.includes(outcome))}).map(n=>n.text).join(`
|
|
`)??"";return parsedFlavor.innerHTML+notesText})():oldFlavor,{initiativeRoll}=message.flags.core;if(initiativeRoll){const combatant=message.token?.combatant;await combatant?.parent.setInitiative(combatant.id,newRoll.total)}await message.delete({render:!1}),await keptRoll.toMessage({content:`<div class="${oldRollClass}">${renders.old}</div><div class="pf2e-reroll-second ${newRollClass}">${renders.new}</div>`,flavor:`${rerollIcon.outerHTML}${newFlavor}`,speaker:message.speaker,flags:{core:{initiativeRoll},pf2e:systemFlags}},{rollMode:context.rollMode})}static async renderReroll(roll,{isOld}){const die=roll.dice.find(d=>d instanceof Die&&d.faces===20);if(typeof die?.total!="number")throw ErrorPF2e("Unexpected error inspecting d20 term");const html=await roll.render(),element=parseHTML(`<div>${html}</div>`);return isOld&&element.querySelector(".message-buttons")?.remove(),[1,20].includes(die.total)&&element.querySelector(".dice-total")?.classList.add(die.total===20?"success":"failure"),element.innerHTML}static async#createResultFlavor({degree,target}){if(!degree)return null;const{dc}=degree,customLabel=!!dc.label&&Number.isInteger(dc.value)&&!dc.label.includes("{dc}")&&dc.label?`<dc>${game.i18n.localize(dc.label)}: {dc}</dc>`:dc.label??null,targetActor=await(async()=>{if(!target?.actor)return null;if(target.actor instanceof ActorPF2e)return target.actor;const maybeActor=await fromUuid(target.actor);return maybeActor instanceof ActorPF2e?maybeActor:maybeActor instanceof TokenDocumentPF2e?maybeActor.actor:null})(),targetData=await(async()=>{if(!target)return null;const token=await(async()=>target.token?target.token instanceof TokenDocumentPF2e?target.token:targetActor?.token?targetActor.token:fromUuid(target.token):null)(),canSeeName=(token??new TokenDocumentPF2e(targetActor?.prototypeToken.toObject()??{})).playersCanSeeName||!game.pf2e.settings.tokens.nameVisibility;return{name:token?.name??targetActor?.name??"",visible:!!canSeeName}})(),{checkDCs}=CONFIG.PF2E,dcData=(()=>{const dcSlug=dc.slug??(dc.statistic instanceof StatisticDifficultyClass?dc.statistic.parent.slug:null),dcType=game.i18n.localize(dc.label?.trim()||game.i18n.localize(objectHasKey(checkDCs.Specific,dcSlug)?checkDCs.Specific[dcSlug]:checkDCs.Unspecific)),circumstances=dc.statistic instanceof StatisticDifficultyClass?dc.statistic.modifiers.filter(m=>m.enabled&&m.type==="circumstance"):[],preadjustedDC=circumstances.length>0&&dc.statistic?dc.value-circumstances.reduce((total,c)=>total+c.modifier,0):dc.value??null,visible=targetActor?.hasPlayerOwner||dc.visible||game.settings.get("pf2e","metagame_showDC");if(typeof preadjustedDC!="number"||circumstances.length===0){const labelKey=game.i18n.localize(targetData?checkDCs.Label.WithTarget:customLabel??checkDCs.Label.NoTarget);return{markup:game.i18n.format(labelKey,{dcType,dc:dc.value,target:targetData?.name??null}),visible}}const adjustment={preadjusted:preadjustedDC,direction:preadjustedDC<dc.value?"increased":preadjustedDC>dc.value?"decreased":"no-change",circumstances:circumstances.map(c=>({label:c.label,value:c.modifier}))},translation=adjustment.direction==="no-change"?checkDCs.Label.NoChangeTarget:checkDCs.Label.AdjustedTarget;return{markup:game.i18n.format(translation,{target:targetData?.name??game.user.name,dcType,preadjusted:preadjustedDC,adjusted:dc.value}),visible,adjustment}})(),resultData=(()=>{const offset={value:new Intl.NumberFormat(game.i18n.lang,{maximumFractionDigits:0,signDisplay:"always",useGrouping:!1}).format(degree.rollTotal-dc.value),visible:dc.visible},checkOrAttack=sluggify(dc.scope??"Check",{camel:"bactrian"}),locPath=__name2((checkOrAttack2,dosKey)=>`PF2E.Check.Result.Degree.${checkOrAttack2}.${dosKey}`,"locPath"),unadjusted=game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.unadjusted])),[adjusted,locKey]=degree.adjustment?[game.i18n.localize(locPath(checkOrAttack,DEGREE_OF_SUCCESS_STRINGS[degree.value])),"AdjustedLabel"]:[unadjusted,"Label"],markup=game.i18n.format(`PF2E.Check.Result.${locKey}`,{adjusted,unadjusted,offset:offset.value}),visible=game.settings.get("pf2e","metagame_showResults");return{markup,visible}})(),rendered=await renderTemplate("systems/pf2e/templates/chat/check/target-dc-result.hbs",{dc:dcData,result:resultData}),html=parseHTML(rendered),{convertXMLNode}=TextEditorPF2e;if(targetData&&convertXMLNode(html,"target",{visible:targetData.visible,whose:"target"}),convertXMLNode(html,"dc",{visible:dcData.visible,whose:"target"}),dcData.adjustment){const{adjustment}=dcData;convertXMLNode(html,"preadjusted",{classes:["unadjusted"]});const adjustedNode=convertXMLNode(html,"adjusted",{classes:["adjusted",adjustment.direction]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustment.circumstances.length>0&&(adjustedNode.dataset.tooltip=adjustment.circumstances.map(a=>createHTMLElement("div",{children:[`${a.label}: ${signedInteger(a.value)}`]}).outerHTML).join(`
|
|
`))}if(convertXMLNode(html,"unadjusted",{visible:resultData.visible,classes:degree.adjustment?["unadjusted"]:[DEGREE_OF_SUCCESS_STRINGS[degree.value]]}),degree.adjustment){const adjustedNode=convertXMLNode(html,"adjusted",{visible:resultData.visible,classes:[DEGREE_OF_SUCCESS_STRINGS[degree.value],"adjusted"]});if(!adjustedNode)throw ErrorPF2e("Unexpected error processing roll template");adjustedNode.dataset.tooltip=degree.adjustment.label}if(convertXMLNode(html,"offset",{visible:dcData.visible,whose:"target"}),!targetData?.visible&&!dcData.visible){const targetDC=html.querySelector(".target-dc");targetDC&&(targetDC.dataset.visibility="gm"),resultData.visible||(html.dataset.visibility="gm")}return html}}class CheckContextError extends Error{static{__name(this,"CheckContextError")}static{__name2(this,"CheckContextError")}constructor(message,actor,slug){super(message),this.actor=actor,this.slug=slug}}class ActionMacroHelpers{static{__name(this,"ActionMacroHelpers")}static{__name2(this,"ActionMacroHelpers")}static resolveStat(stat){switch(stat){case"perception":return{checkType:"perception-check",property:"perception",stat,subtitle:"PF2E.ActionsCheck.perception"};case"unarmed":return{checkType:"attack-roll",property:"unarmed",stat,subtitle:"PF2E.ActionsCheck.unarmed"};default:return{checkType:"skill-check",property:`skills.${sluggify(stat)}`,stat,subtitle:`PF2E.ActionsCheck.${stat}`}}}static defaultCheckContext(options,data){const{checkType:type,property,stat:slug,subtitle}=this.resolveStat(data.slug),statistic=options.actor.getStatistic(data.slug)??foundry.utils.getProperty(options.actor,property);if(!statistic){const{actor}=options,message=`Actor ${actor.name} (${actor.id}) does not have a statistic for ${slug}.`;throw new CheckContextError(message,actor,slug)}const{item,rollOptions:contextualRollOptions}=options.buildContext({actor:options.actor,item:data.item,rollOptions:[...data.rollOptions],target:options.target});return{item,modifiers:data.modifiers??[],rollOptions:contextualRollOptions,slug,statistic,subtitle,type}}static note(selector,translationPrefix,outcome,translationKey){const outcomes=game.settings.get("pf2e","metagame_showResults")?[outcome]:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey??`${translationPrefix}.Notes.${outcome}`),outcome:outcomes})}static outcomesNote(selector,translationKey,outcomes){const visibleOutcomes=game.settings.get("pf2e","metagame_showResults")?outcomes:[];return new RollNotePF2e({selector,text:game.i18n.localize(translationKey),outcome:visibleOutcomes})}static async simpleRollActionCheck(options){const rollers=[];if(Array.isArray(options.actors)?rollers.push(...options.actors):options.actors?rollers.push(options.actors):rollers.push(...getSelectedOrOwnActors()),rollers.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const targetData=options.target?.()??this.target();for(const actor of rollers)try{const selfToken=actor.getActiveTokens(!1,!0).shift(),{item:weapon,modifiers=[],rollOptions:combinedOptions,statistic,subtitle,type}=await options.checkContext({actor,buildContext:args=>{const combinedOptions2=compact([args.rollOptions,options.traits].flat());return combinedOptions2.push(...args.item?.getRollOptions("item")??[]),{item:args.item,rollOptions:combinedOptions2.sort(),target:args.target}},target:targetData.actor}),header=await renderTemplate("systems/pf2e/templates/chat/action/header.hbs",{glyph:options.actionGlyph,subtitle,title:options.title}),actionTraits2=(options.traits??[]).filter(t=>t in CONFIG.PF2E.actionTraits),notes=options.extraNotes?.(statistic.slug)??[],label=await options.content?.(header)??header,title=`${game.i18n.localize(options.title)} - ${game.i18n.localize(subtitle)}`;if(statistic instanceof Statistic){const dc=this.#resolveCheckDC({unresolvedDC:options.difficultyClass});await statistic.roll({...eventToRollParams(options.event,{type:"check"}),token:selfToken,label,title,dc,extraRollNotes:notes,extraRollOptions:combinedOptions,modifiers,target:targetData.actor,traits:actionTraits2,createMessage:options.createMessage,callback:(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})}})}else{const check=new CheckModifier(label,statistic,modifiers),dc=this.#resolveCheckDC({target:targetData.actor,unresolvedDC:options.difficultyClass,fully:!0}),finalOptions=new Set(combinedOptions);ensureProficiencyOption(finalOptions,statistic.rank??-1),check.calculateTotal(finalOptions);const selfActor=actor.getContextualClone(combinedOptions.filter(o=>o.startsWith("self:"))),distance=(()=>{const reach=selfActor.isOfType("creature")&&weapon?.isOfType("weapon")?selfActor.getReach({action:"attack",weapon})??null:null;return selfToken?.object&&targetData?.token?.object?selfToken.object.distanceTo(targetData.token.object,{reach}):null})(),rangeIncrement=weapon?.isOfType("weapon")&&typeof distance=="number"?getRangeIncrement(weapon,distance):null,domains=["all",type,statistic.slug],targetInfo=targetData.token&&targetData.actor&&typeof distance=="number"?{token:targetData.token,actor:targetData.actor,distance,rangeIncrement}:null,substitutions=extractRollSubstitutions(actor.synthetics.rollSubstitutions,domains,finalOptions),dosAdjustments=extractDegreeOfSuccessAdjustments(actor.synthetics,domains);await CheckPF2e.roll(check,{actor:selfActor,token:selfToken,item:weapon,createMessage:options.createMessage,target:targetInfo,dc,type,options:finalOptions,notes:[...notes,...statistic.notes??[]],dosAdjustments,substitutions,traits:actionTraits2,title},options.event,(roll,outcome,message)=>{options.callback?.({actor,message,outcome,roll})})}}catch(cce){if(cce instanceof CheckContextError){const message=game.i18n.format("PF2E.ActionsWarning.NoStatistic",{id:cce.actor.id,name:cce.actor.name,statistic:cce.slug});ui.notifications.error(message);continue}throw cce}}static target(){const target=Array.from(game.user.targets).filter(t=>t.actor?.isOfType("creature")).shift()?.document??null,targetActor=target?.actor??null;return{token:target,actor:targetActor}}static getWeaponPotencyModifier(item,selector){const slug="potency";return AutomaticBonusProgression.isEnabled(item.actor)?new ModifierPF2e({slug,type:"potency",label:"PF2E.AutomaticBonusProgression.attackPotency",modifier:item.actor.synthetics.weaponPotency["strike-attack-roll"]?.[0]?.bonus??0,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):item.system.runes.potency>0?new ModifierPF2e({slug,type:"item",label:"PF2E.Item.Weapon.Rune.Potency",modifier:item.system.runes.potency,adjustments:extractModifierAdjustments(item.actor.synthetics.modifierAdjustments,[selector],slug)}):null}static getApplicableEquippedWeapons(actor,trait){return actor.isOfType("character")?actor.system.actions.flatMap(s=>s.ready&&s.item.traits.has(trait)?s.item:[]):actor.itemTypes.weapon.filter(w=>w.isEquipped&&w.traits.has(trait))}static#resolveCheckDC({unresolvedDC=null,target=null,fully=!1}){return typeof unresolvedDC=="string"?fully?target?.getStatistic(unresolvedDC)?.dc??null:{slug:unresolvedDC}:typeof unresolvedDC=="function"?unresolvedDC(target):unresolvedDC}}class SelectItemDialog extends Application{static{__name(this,"SelectItemDialog")}static{__name2(this,"SelectItemDialog")}#item=null;#resolve;#action;constructor(action2,resolve){super(),this.#action=action2,this.#resolve=resolve}static get defaultOptions(){return{...super.defaultOptions,width:270}}get template(){return this.#action==="craft"?"systems/pf2e/templates/system/actions/craft-target-item.hbs":"systems/pf2e/templates/system/actions/repair/select-item-dialog.hbs"}get title(){const key=sluggify(this.#action,{camel:"bactrian"});return game.i18n.localize(`PF2E.Actions.${key}.SelectItemDialog.Title`)}async getData(options={}){return options.classes=[`select-${this.#action}-item-dialog`],{...await super.getData(options),item:this.#item}}activateListeners($html){super.activateListeners($html);const html=$html[0];html.addEventListener("drop",async event2=>{const json2=event2.dataTransfer?.getData("text/plain");if(!json2?.startsWith("{")||!json2.endsWith("}"))return;const data=JSON.parse(json2),uuid=data.uuid??data.pf2e?.itemUuid,item=uuid?await fromUuid(uuid):null;if(this.#action==="repair"&&item&&!(item?.isEmbedded&&item.isOwner))ui.notifications.error("DOCUMENT.UsePermissionWarn",{localize:!0});else if(item instanceof PhysicalItemPF2e)this.#item=item,this.render();else{const key=sluggify(this.#action,{camel:"bactrian"});ui.notifications.error(game.i18n.localize(`PF2E.Actions.${key}.Error.ItemReferenceMismatch`))}}),htmlQuery(html,`[data-event-handler=${this.#action}]`)?.addEventListener("click",()=>{this.close()}),htmlQuery(html,"[data-event-handler=cancel]")?.addEventListener("click",()=>{this.#item=null,this.close()})}close(options){return this.#resolve(this.#item),super.close(options)}static async getItem(action2){return new Promise(resolve=>{new this(action2,resolve).render(!0)})}}async function repair(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("repair"));if(item&&!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Repair.Warning.NotPhysicalItem",{item:item.name??""}));return}const dc=options.difficultyClass??(()=>{if(item){const pwol=game.pf2e.settings.variants.pwol.enabled;return{label:game.i18n.format("PF2E.Actions.Repair.Labels.ItemLevelRepairDC",{level:item.level}),value:calculateDC(item.level,{pwol}),visibility:"all"}}})(),targetItemOptions=Array.from(item?.traits??[]).map(trait=>`target:trait:${trait}`),slug=options?.skill??"crafting",rollOptions=["action:repair",...targetItemOptions],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Repair.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),content:async title=>{if(item){const templatePath="systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs",templateData={item},content=await renderTemplate(templatePath,templateData);return title+content}},traits:["exploration","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Repair","criticalFailure")],createMessage:!1,callback:async result=>{const{actor}=result;if(item&&result.message instanceof ChatMessagePF2e&&actor.isOfType("creature")){const messageSource=result.message.toObject(),flavor=await(async()=>{const proficiencyRank=actor.skills.crafting.rank??0;if(result.outcome==="criticalSuccess"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(10+proficiencyRank*10);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="success"){const label="PF2E.Actions.Repair.Labels.RestoreItemHitPoints",restored=String(5+proficiencyRank*5);return renderRepairResult(item,"restore",label,restored)}else if(result.outcome==="criticalFailure")return renderRepairResult(item,"roll-damage","PF2E.Actions.Repair.Labels.RollItemDamage","2d6");return""})();flavor&&(messageSource.flavor+=flavor),await ChatMessage.create(messageSource)}}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(repair,"repair"),__name2(repair,"repair");async function onRepairChatCardEvent(event2,message,card){const itemUuid=card.dataset.itemUuid,item=await fromUuid(itemUuid??""),button=event2.currentTarget;if(!(item instanceof PhysicalItemPF2e)||!(button instanceof HTMLElement))return;const repair2=button.dataset.repair,speaker=message&&ChatMessagePF2e.getSpeaker({actor:message.actor,alias:message.alias,token:message.token});if(repair2==="restore"){const value=Number(button.dataset.repairValue)||0,beforeRepair=item.system.hp.value,afterRepair=Math.min(item.system.hp.max,beforeRepair+value);await item.update({"system.hp.value":afterRepair});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemRepaired",{itemName:item.name,repairedDamage:afterRepair-beforeRepair,afterRepairHitPoints:afterRepair,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else if(repair2==="roll-damage"){const roll=await Roll.create("2d6").evaluate({async:!0}),templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",flavor=await renderTemplate(templatePath,{damage:{dealt:Math.max(0,roll.total-item.system.hardness),rolled:roll.total},item});await roll.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor,speaker})}else if(repair2==="damage"){const hardness=Math.max(0,item.system.hardness),damage=(message?.rolls.at(0)?.total??0)-hardness;if(damage>0){const beforeDamage=item.system.hp.value,afterDamage=Math.max(0,item.system.hp.value-damage);await item.update({"system.hp.value":afterDamage});const content=game.i18n.format("PF2E.Actions.Repair.Chat.ItemDamaged",{itemName:item.name,damageDealt:beforeDamage-afterDamage,afterDamageHitPoints:afterDamage,maximumHitPoints:item.system.hp.max});await ChatMessage.create({content,speaker})}else{const templatePath="systems/pf2e/templates/system/actions/repair/roll-damage-chat-message.hbs",content=await renderTemplate(templatePath,{damage:{dealt:0,rolled:message?.rolls.at(0)?.total??0},item});await ChatMessage.create({content,speaker})}}}__name(onRepairChatCardEvent,"onRepairChatCardEvent"),__name2(onRepairChatCardEvent,"onRepairChatCardEvent");async function renderRepairResult(item,result,buttonLabel,value){const templatePath="systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs",label=game.i18n.format(buttonLabel,{value});return renderTemplate(templatePath,{item,label,result,value})}__name(renderRepairResult,"renderRepairResult"),__name2(renderRepairResult,"renderRepairResult");class ChatCards{static{__name(this,"ChatCards")}static{__name2(this,"ChatCards")}static#lastClick=0;static listen(message,html){const selector=["a[data-action], button[data-action]"].join(",");for(const button of htmlQueryAll(html,selector))button.addEventListener("click",async event2=>this.#onClickButton({message,event:event2,html,button}))}static async#onClickButton({message,event:event2,html,button}){const currentTime=Date.now();if(currentTime-this.#lastClick<500)return;this.#lastClick=currentTime;const action2=button.dataset.action??"",item=message.item,actor=item?.actor??message.actor;if(!actor||!game.user.isGM&&!actor.isOwner&&!["spell-save","expand-description"].includes(action2))return;const strikeAction=message._strike;if(strikeAction&&action2?.startsWith("strike-")){const context=message.rolls.some(r=>r instanceof CheckRoll)?message.flags.pf2e.context??null:null,mapIncreases=context&&"mapIncreases"in context&&tupleHasValue([0,1,2],context.mapIncreases)?context.mapIncreases:null,altUsage=context&&"altUsage"in context?context.altUsage:null,target=message.target?.token?.object??null,rollArgs={event:event2,altUsage,mapIncreases,checkContext:context,target};switch(sluggify(action2??"")){case"strike-attack":strikeAction.variants[0].roll(rollArgs);return;case"strike-attack2":strikeAction.variants[1].roll(rollArgs);return;case"strike-attack3":strikeAction.variants[2].roll(rollArgs);return;case"strike-damage":{const method=button.dataset.outcome==="success"?"damage":"critical";strikeAction[method]?.(rollArgs);return}}}if(item){const spell=item.isOfType("spell")?item:item.isOfType("consumable")?item.embeddedSpell:null;switch(action2){case"spell-attack":return spell?.rollAttack(event2);case"spell-attack-2":return spell?.rollAttack(event2,2);case"spell-attack-3":return spell?.rollAttack(event2,3);case"spell-damage":spell?.rollDamage(event2);return;case"spell-save":return this.#rollActorSaves({event:event2,button,actor,item});case"affliction-save":item?.isOfType("affliction")&&item.rollRecovery();return;case"spell-counteract":spell?.rollCounteract(event2);return;case"spell-template":spell?.placeTemplate(message);return;case"spell-template-clear":{const templateIds=canvas.scene?.templates.filter(t=>t.message===message).map(t=>t.id)??[];button.disabled=!0,await canvas.scene?.deleteEmbeddedDocuments("MeasuredTemplate",templateIds),button.disabled=!1;return}case"spell-variant":{const castLevel=Number(htmlQuery(html,"div.chat-card")?.dataset.castLevel)||1,overlayIds=button.dataset.overlayIds?.split(",").map(id=>id.trim());if(overlayIds){const variantSpell=spell?.loadVariant({overlayIds,castLevel});if(variantSpell){const variantMessage=await variantSpell.toMessage(void 0,{create:!1,data:{castLevel}});if(variantMessage){const messageSource=variantMessage.toObject();await message.update(messageSource)}}}else if(spell){const originalMessage=await(spell?.original??spell).toMessage(void 0,{create:!1,data:{castLevel}});originalMessage&&await message.update(originalMessage.toObject())}return}case"consume":{if(item.isOfType("consumable"))item.consume();else if(item.isOfType("melee")){const consumable=actor.items.get(button.dataset.item??"");if(consumable?.isOfType("consumable")){const oldQuant=consumable.quantity,consumableString=game.i18n.localize("TYPES.Item.consumable"),toReplace=`${consumable.name} - ${consumableString} (${oldQuant})`;await consumable.consume();const currentQuant=oldQuant===1?0:consumable.quantity;let flavor=message.flavor.replace(toReplace,`${consumable.name} - ${consumableString} (${currentQuant})`);if(currentQuant===0){const buttonStr=`>${game.i18n.localize("PF2E.ConsumableUseLabel")}</button>`;flavor=flavor?.replace(buttonStr,` disabled${buttonStr}`)}await message.update({flavor}),message.render(!0)}}return}case"expand-description":{const{description}=item,element=htmlClosest(button,".description");element&&(element.innerHTML=await TextEditor.enrichHTML(description,{async:!0,rollData:actor.getRollData()}),element.scrollIntoView({behavior:"smooth",block:"center"}));break}case"apply-effect":{button.disabled=!0;const target=fromUuidSync(button.dataset.targets??""),effect=item.isOfType("action","feat")&&item.system.selfEffect?await fromUuid(item.system.selfEffect.uuid):null;if(target instanceof ActorPF2e&&effect instanceof ItemPF2e&&effect.isOfType("effect")){await target.createEmbeddedDocuments("Item",[effect.clone().toObject()]);const parsedMessageContent=(()=>{const container=document.createElement("div");return container.innerHTML=message.content,container})(),buttons=htmlQuery(parsedMessageContent,".message-buttons");if(buttons){const span=createHTMLElement("span",{classes:["effect-applied"]}),anchor=effect.toAnchor({attrs:{draggable:"true"}}),locKey="PF2E.Item.Action.SelfAppliedEffect.Applied",statement=game.i18n.format(locKey,{effect:anchor.outerHTML});span.innerHTML=statement,buttons.replaceChildren(span),await message.update({content:parsedMessageContent.innerHTML})}}break}case"elemental-blast-damage":{if(!actor.isOfType("character"))return;const roll=message.rolls.find(r=>r instanceof CheckRoll&&r.options.action==="elemental-blast"),checkContext=roll?message.flags.pf2e.context??null:null,outcome=button.dataset.outcome==="success"?"success":"criticalSuccess",[element,damageType,meleeOrRanged,actionCost]=roll?.options.identifier?.split(".")??[];objectHasKey(elementTraits,element)&&objectHasKey(CONFIG.PF2E.damageTypes,damageType)&&await new ElementalBlast(actor).damage({element,damageType,melee:meleeOrRanged==="melee",actionCost:Number(actionCost)||1,checkContext,outcome,event:event2})}}}else if(action2&&actor.isOfType("character","npc")){const buttonGroup=htmlClosest(button,".chat-card, .message-buttons"),physicalItem=await(async()=>{const itemUuid=buttonGroup?.dataset.itemUuid??"",maybeItem=await fromUuid(itemUuid);return maybeItem instanceof PhysicalItemPF2e?maybeItem:null})(),quantity=Number(buttonGroup?.dataset.craftingQuantity)||1;if(action2==="repair-item"&&buttonGroup)await onRepairChatCardEvent(event2,message,buttonGroup);else if(physicalItem&&action2==="pay-crafting-costs"){const quantity2=Number(buttonGroup?.dataset.craftingQuantity)||1,craftingCost=CoinsPF2e.fromPrice(physicalItem.price,quantity2),coinsToRemove=button.classList.contains("full")?craftingCost:craftingCost.scale(.5);if(!await actor.inventory.removeCoins(coinsToRemove)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"));return}if(isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")){craftSpellConsumable(physicalItem,quantity2,actor),ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}});return}const itemObject=physicalItem.toObject();if(itemObject.system.quantity=quantity2,!await actor.addToInventory(itemObject,void 0)){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.CantAddItem"));return}ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.LoseMaterials",{actorName:actor.name,cost:coinsToRemove.toString(),quantity:quantity2,itemName:physicalItem.name}),speaker:{alias:actor.name}})}else if(physicalItem&&action2==="lose-materials"){const coinsToRemove=CoinsPF2e.fromPrice(physicalItem.price,quantity).scale(.5).scale(.1);await actor.inventory.removeCoins(coinsToRemove)?ChatMessagePF2e.create({user:game.user.id,content:game.i18n.format("PF2E.Actions.Craft.Information.PayAndReceive",{actorName:actor.name,cost:coinsToRemove.toString()}),speaker:{alias:actor.name}}):ui.notifications.warn(game.i18n.localize("PF2E.Actions.Craft.Warning.InsufficientCoins"))}else if(action2==="receieve-crafting-item"&&physicalItem)return isSpellConsumable(physicalItem.id)&&physicalItem.isOfType("consumable")?craftSpellConsumable(physicalItem,quantity,actor):craftItem(physicalItem,quantity,actor)}else if(action2==="army-strike-damage"&&actor.isOfType("army")){const roll=message.rolls.find(r=>r instanceof CheckRoll&&r.options.action==="army-strike"),checkContext=roll?message.flags.pf2e.context??null:null,action22=button.dataset.outcome==="success"?"damage":"critical";actor.strikes[roll?.options.identifier??""]?.[action22]({checkContext,event:event2})}}static async#rollActorSaves({event:event2,button,actor,item}){const tokens=game.user.getActiveTokens();if(tokens.length===0){ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0});return}const saveType=button.dataset.save;if(!tupleHasValue(SAVE_TYPES,saveType))throw ErrorPF2e(`"${saveType}" is not a recognized save type`);const dc=Number(button.dataset.dc??"NaN");for(const token of tokens){const save=token.actor?.saves?.[saveType];if(!save)return;save.check.roll({...eventToRollParams(event2,{type:"check"}),dc:Number.isInteger(dc)?{value:Number(dc)}:null,item,origin:actor})}}}const DamageTaken={listen:async(message,html)=>{const damageTakenCard=htmlQuery(html,".damage-taken");if(!damageTakenCard)return;const settingEnabled=game.pf2e.settings.tokens.nameVisibility;if(!game.user.isGM&&settingEnabled&&message.token&&!message.token.playersCanSeeName){const nameElem=htmlQuery(damageTakenCard,".target-name");nameElem&&(nameElem.innerText=game.i18n.localize("PF2E.Actor.ApplyDamage.TheTarget"))}const iwrInfo=htmlQuery(damageTakenCard,".iwr");if(!iwrInfo)return;const iwrApplications=(()=>{try{const parsed=JSON.parse(iwrInfo?.dataset.applications??"null");return Array.isArray(parsed)&&parsed.every(a=>a instanceof Object&&"category"in a&&typeof a.category=="string"&&"type"in a&&typeof a.type=="string"&&"adjustment"in a&&typeof a.adjustment=="number")?parsed:null}catch{return null}})();iwrApplications&&$(iwrInfo).tooltipster({theme:"crb-hover",maxWidth:400,content:await renderTemplate("systems/pf2e/templates/chat/damage/iwr-breakdown.hbs",{applications:iwrApplications}),contentAsHTML:!0})}},DegreeOfSuccessHighlights={listen:(message,html)=>{if(htmlQueryAll(html,".pf2e-reroll-indicator").length>0)return;const firstRoll=message.rolls.at(0);if(!firstRoll||message.isDamageRoll)return;const firstDice=firstRoll.dice.at(0);if(!(firstDice instanceof Die&&firstDice.faces===20&&message.isContentVisible))return;const diceTotal=htmlQuery(html,".dice-total"),results=firstDice.results.filter(r=>r.active);results.every(r=>r.result===20)?diceTotal?.classList.add("success"):results.every(r=>r.result===1)&&diceTotal?.classList.add("failure")}},SetAsInitiative={listen:li=>{const message=game.messages.get(li.dataset.messageId??"",{strict:!0}),token=message.token;if(!(message.rolls.some(r=>r instanceof CheckRoll&&["skill-check","perception-check"].includes(r.options.type??""))&&(!message.blind||game.user.isGM)&&token?.actor))return;const button=createHTMLElement("button",{classes:["set-as-initiative"],dataset:{action:"set-as-initiative",tooltip:game.i18n.format("PF2E.Check.SetAsInitiative",{actor:token.name})},children:[fontAwesomeIcon("swords")]});button.type="button";const selector=message.isReroll?".pf2e-reroll-second .dice-total":".dice-total";li.querySelector(selector)?.appendChild(button)}};class RollInspector extends Application{static{__name(this,"RollInspector")}static{__name2(this,"RollInspector")}constructor(message,options={}){super(options),this.message=message}static get defaultOptions(){return{...super.defaultOptions,title:"PF2E.ChatRollDetails.Title",template:"systems/pf2e/templates/chat/roll-inspector.hbs",classes:["roll-inspector"],filters:[{inputSelector:"input[type=search]",contentSelector:".roll-options > ul"}],resizable:!0,width:600,height:420}}getData(){const{context}=this.message.flags.pf2e,rollOptions=(()=>{const allOptions=context?.options??[],topLevelOptions=allOptions.filter(option=>!option.includes(":")),remainingOptions=allOptions.filter(option=>option.includes(":"));return[...topLevelOptions.sort(),...remainingOptions.sort()]})(),modifiers=this.message.flags.pf2e.modifiers?.map(mod=>({...mod,value:signedInteger(mod.modifier),critical:typeof mod.critical=="boolean"?game.i18n.localize(`PF2E.RuleEditor.General.CriticalBehavior.${mod.critical}`):null}))??[],dice=this.message.flags.pf2e.dice?.map(dice2=>({...dice2,value:`+${dice2.diceNumber}${dice2.dieSize}`,critical:typeof dice2.critical=="boolean"?game.i18n.localize(`PF2E.RuleEditor.General.CriticalBehavior.${dice2.critical}`):null}))??[];return{context,domains:context?.domains?.sort()??[],modifiers,dice,rollOptions}}_onSearchFilter(_event,query,_rgx,html){for(const row of htmlQueryAll(html,":scope > li"))row.hidden=query.length>0&&!row.innerText.includes(query)}}class ChatMessagePF2e extends ChatMessage{static{__name(this,"ChatMessagePF2e")}static{__name2(this,"ChatMessagePF2e")}constructor(data={},context={}){const expandedFlags=foundry.utils.expandObject(data.flags??{});data.flags=foundry.utils.mergeObject(expandedFlags,{core:{canPopout:expandedFlags.core?.canPopout??!0},pf2e:{}}),super(data,context)}get isDamageRoll(){const firstRoll=this.rolls.at(0);if(!firstRoll||firstRoll.terms.some(t=>t instanceof FateDie||t instanceof Coin))return!1;if(this.flags.pf2e.context?.type==="damage-roll")return!0;const isCheck=firstRoll instanceof CheckRoll||firstRoll.dice[0]?.faces===20,fromRollTable=!!this.flags.core.RollTable;return!(isCheck||fromRollTable)}get actor(){return ChatMessagePF2e.getSpeakerActor(this.speaker)}get target(){const context=this.flags.pf2e.context;if(!context)return null;const targetUUID="target"in context?context.target?.token:null;if(!targetUUID)return null;const match=/^Scene\.(\w+)\.Token\.(\w+)$/.exec(targetUUID??"")??[],token=game.scenes.get(match[1]??"")?.tokens.get(match[2]??""),actor=token?.actor;return actor?{actor,token}:null}get journalEntry(){const uuid=this.flags.pf2e.journalEntry;if(!uuid)return null;const entryId=/^JournalEntry.([A-Za-z0-9]{16})$/.exec(uuid)?.at(1);return game.journal.get(entryId??"")??null}get isCheckRoll(){return this.rolls[0]instanceof CheckRoll}get isReroll(){const context=this.flags.pf2e.context;return!!context&&"isReroll"in context&&!!context.isReroll}get isRerollable(){const roll=this.rolls[0];return!!(this.actor?.isOwner&&(this.isAuthor||this.isOwner)&&roll instanceof CheckRoll&&roll.isRerollable)}get item(){if(this.flags.pf2e.context?.type==="self-effect")return this.actor?.items.get(this.flags.pf2e.context.item)??null;const strike=this._strike;if(strike?.item)return strike.item;const item=(()=>{const{actor}=this,embeddedSpell=this.flags.pf2e.casting?.embeddedSpell;if(actor&&embeddedSpell)return new ItemProxyPF2e(embeddedSpell,{parent:actor});const origin=this.flags.pf2e?.origin??null,match=/Item\.(\w+)/.exec(origin?.uuid??"")??[];return actor?.items.get(match?.[1]??"")??null})();if(!item)return null;const{tradition}=this.flags.pf2e?.casting??{},isCharacter=!!item.actor?.isOfType("character");if(tradition&&item.isOfType("spell")&&!item.spellcasting&&isCharacter){const trick=new TrickMagicItemEntry(item.actor,traditionSkills[tradition]);item.trickMagicEntry=trick}if(item?.isOfType("spell")){const overlayIds=this.flags.pf2e.origin?.variant?.overlays,castLevel=this.flags.pf2e.origin?.castLevel??item.rank;return item.loadVariant({overlayIds,castLevel})??item}return item}get _strike(){const{actor}=this,identifier=this.rolls.find(r=>r instanceof CheckRoll)?.options.identifier??htmlQuery(document.body,`li.message[data-message-id="${this.id}"] [data-identifier]`)?.dataset.identifier,[itemId,slug,meleeOrRanged]=identifier?.split(".")??[null,null,null];if(!meleeOrRanged||!["melee","ranged"].includes(meleeOrRanged))return null;const strikeData=actor?.system.actions?.find(s=>s.slug===slug&&s.item.id===itemId),itemMeleeOrRanged=strikeData?.item.isMelee?"melee":"ranged";return meleeOrRanged===itemMeleeOrRanged?strikeData??null:strikeData?.altUsages?.find(u=>{const altUsageMeleeOrRanged=u.item.isMelee?"melee":"ranged";return meleeOrRanged===altUsageMeleeOrRanged})??null}async showDetails(){this.flags.pf2e.context&&new RollInspector(this).render(!0)}get token(){if(!game.scenes)return null;const sceneId=this.speaker.scene??"",tokenId=this.speaker.token??"";return game.scenes.get(sceneId)?.tokens.get(tokenId)??null}getRollData(){const{actor,item}=this;return{...actor?.getRollData(),...item?.getRollData()}}async getHTML(){const{actor}=this;if(this.isContentVisible){const rollData=this.getRollData();this.flavor=await TextEditorPF2e.enrichHTML(this.flavor,{async:!0,rollData,processVisibility:!1})}const $html=await super.getHTML(),html=$html[0];!this.flags.pf2e.suppressDamageButtons&&this.isDamageRoll&&htmlQueryAll(html,".damage-application").forEach((buttons,index)=>{buttons.dataset.rollIndex=index.toString()}),UserVisibilityPF2e.process(html,{message:this}),await DamageTaken.listen(this,html),CriticalHitAndFumbleCards.appendButtons(this,$html),ChatCards.listen(this,html),InlineRollLinks.listen(html,this),DegreeOfSuccessHighlights.listen(this,html),canvas.ready&&SetAsInitiative.listen(html);const roll=this.rolls[0];if(actor?.isOwner&&roll instanceof DamageRoll&&roll.options.evaluatePersistent){const damageType=roll.instances.find(i=>i.persistent)?.type;if(damageType?this.actor?.getCondition(`persistent-damage-${damageType}`):null){const template="systems/pf2e/templates/chat/persistent-damage-recovery.hbs",section=parseHTML(await renderTemplate(template));html.querySelector(".message-content")?.append(section),html.dataset.actorIsTarget="true"}htmlQuery(html,"[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{const{actor:actor2}=this;if(!actor2)return;const damageType2=roll.instances.find(i=>i.persistent)?.type;if(!damageType2)return;const condition2=actor2.getCondition(`persistent-damage-${damageType2}`);if(!condition2?.system.persistent){const damageTypeLocalized=game.i18n.localize(CONFIG.PF2E.damageTypes[damageType2]??damageType2),message=game.i18n.format("PF2E.Item.Condition.PersistentDamage.Error.DoesNotExist",{damageType:damageTypeLocalized});ui.notifications.warn(message);return}condition2.rollRecovery()})}return this.flags.pf2e.appliedDamage?.isReverted||this.actor?.isOwner||htmlQuery(html,"button[data-action=revert-damage]")?.remove(),html.addEventListener("mouseenter",event2=>this.#onHoverIn(event2)),html.addEventListener("mouseleave",event2=>this.#onHoverOut(event2)),UserVisibilityPF2e.processMessageSender(this,html),!actor&&this.content&&UserVisibilityPF2e.process(html,{document:this}),$html}#onHoverIn(nativeEvent){if(!canvas.ready)return;const token=this.token?.object;token?.isVisible&&!token.controlled&&token.emitHoverIn(nativeEvent)}#onHoverOut(nativeEvent){canvas.ready&&this.token?.object?.emitHoverOut(nativeEvent)}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.isRoll&&game.settings.get("pf2e","drawCritFumble")&&CriticalHitAndFumbleCards.handleDraw(this)}}class PCAttackTraitHelpers extends AttackTraitHelpers{static{__name(this,"PCAttackTraitHelpers")}static{__name2(this,"PCAttackTraitHelpers")}static adjustWeapon(weapon){const traits=weapon.system.traits.value;for(const trait of[...traits])switch(trait.replace(/-d?\d{1,3}$/,"")){case"fatal-aim":{if(weapon.range?.increment&&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=/(d\d{1,2})$/.exec(trait)?.[1];setHasElement(DAMAGE_DIE_FACES,die)&&(weapon.system.damage.die=die)}break}}}static createAttackModifiers({item,domains}){const{actor}=item;if(!actor)throw ErrorPF2e("The weapon must be embedded");const traitsAndTags=compact([item.system.traits.value,item.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:["attribute:str:mod",2]}),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({item}),...pcSpecificModifiers]}}class WeaponAuxiliaryAction{static{__name(this,"WeaponAuxiliaryAction")}static{__name2(this,"WeaponAuxiliaryAction")}weapon;action;actions;carryType;hands;annotation;fullAnnotation;constructor({weapon,action:action2,annotation,hands}){this.weapon=weapon,this.action=action2,this.annotation=annotation??null,this.hands=hands??null;const[actions,carryType,fullPurpose]=(()=>{switch(annotation){case"draw":return[1,"held",`${annotation}${hands}H`];case"pick-up":return[1,"held",`${annotation}${hands}H`];case"retrieve":{const{container}=weapon;if(container?.isHeld)return[1,"held",`${annotation}${hands}H`];const usage=container?.system.usage;return[usage?.type==="held"||usage?.where==="backpack"?2:1,"held",`${annotation}${hands}H`]}case"grip":return[action2==="interact"?1:0,"held",annotation];case"sheathe":return[1,"worn",annotation];case"modular":return[1,null,annotation];case"drop":return[0,"dropped",annotation];case"tower-shield":return[this.action==="take-cover"?1:0,null,null];default:return[1,null,null]}})();this.actions=actions,this.carryType=carryType,this.fullAnnotation=fullPurpose}get actor(){return this.weapon.parent}get label(){const actionKey=sluggify(this.action,{camel:"bactrian"}),purposeKey=this.fullAnnotation?sluggify(this.fullAnnotation,{camel:"bactrian"}):null;return purposeKey?game.i18n.localize(`PF2E.Actions.${actionKey}.${purposeKey}.Title`):game.i18n.localize(`PF2E.Actions.${actionKey}.ShortTitle`)}get glyph(){return getActionGlyph(this.actions)}get options(){return this.annotation==="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,COVER_UUID="Compendium.pf2e.other-effects.Item.I9lfZUiCwMiGogVi";if(this.carryType)await actor.adjustCarryType(this.weapon,{carryType:this.carryType,handsHeld:this.hands??0});else if(selection&&tupleHasValue(weapon.system.traits.toggles.modular.options,selection)){if(!await toggleWeaponTrait({weapon,trait:"modular",selection}))return}else if(this.action==="raise-a-shield"){if(actor.itemTypes.effect.some(e=>e.slug==="raise-a-shield"))return;const effect=await fromUuid("Compendium.pf2e.equipment-effects.Item.2YgXoHvJfrDHucMr");effect instanceof EffectPF2e&&await actor.createEmbeddedDocuments("Item",[{...effect.toObject(),_id:null}])}else if(this.action==="take-cover"){const effect=await fromUuid(COVER_UUID);if(effect instanceof EffectPF2e){const data={...effect.toObject(),_id:null};data.system.traits.otherTags.push("tower-shield");const rule=data.system.rules.find(r=>r.key==="ChoiceSet");rule&&(rule.selection={bonus:4,level:"greater"}),await actor.createEmbeddedDocuments("Item",[data])}}else this.action==="end-cover"&&await actor.itemTypes.effect.find(e=>e.sourceId===COVER_UUID)?.delete();if(!game.combat)return;const templates={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"},actionKey=sluggify(this.action,{camel:"bactrian"}),annotationKey=this.annotation?sluggify(this.annotation,{camel:"bactrian"}):null,fullAnnotationKey=this.fullAnnotation?sluggify(this.fullAnnotation,{camel:"bactrian"}):null,flavorAction={title:`PF2E.Actions.${actionKey}.Title`,subtitle:fullAnnotationKey?`PF2E.Actions.${actionKey}.${fullAnnotationKey}.Title`:null,glyph:this.glyph},[traits,message]=this.action==="raise-a-shield"?[[],`PF2E.Actions.${actionKey}.Content`]:["take-cover","end-cover"].includes(this.action)?[[],`PF2E.Actions.${actionKey}.${annotationKey}.Description`]:[[traitSlugToObject("manipulate",CONFIG.PF2E.actionTraits)],`PF2E.Actions.${actionKey}.${fullAnnotationKey}.Description`],flavor=await renderTemplate(templates.flavor,{action:flavorAction,traits}),content=await renderTemplate(templates.content,{imgPath:weapon.img,message:game.i18n.format(message,{actor:actor.name,weapon:weapon.name,shield:weapon.shield?.name??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})}}function imposeOversizedWeaponCondition(actor){if(actor.conditions.clumsy)return;const wieldedOversizedWeapon=actor.itemTypes.weapon.find(w=>w.isEquipped&&w.isOversized&&w.category!=="unarmed"),compendiumCondition=game.pf2e.ConditionManager.getCondition("clumsy"),conditionSource=wieldedOversizedWeapon&&actor.conditions.bySlug("clumsy").length===0?foundry.utils.mergeObject(compendiumCondition.toObject(),{_id:"xxxxOVERSIZExxxx",system:{slug:"clumsy",references:{parent:{id:wieldedOversizedWeapon.id}}}}):null;if(!conditionSource)return;const clumsyOne=new ItemProxyPF2e(conditionSource,{parent:actor});clumsyOne.prepareSiblingData(),clumsyOne.prepareActorData();for(const rule of clumsyOne.prepareRuleElements())rule.beforePrepareData?.();actor.conditions.set(clumsyOne.id,clumsyOne)}__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){const slug="hindering";return actor.wornArmor?.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.mod>=(armor.strength??-1/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");function loreSkillsFromActors(actors){const characters=(Array.isArray(actors)?actors:[actors]).filter(a=>a?.type==="character");return Object.fromEntries(characters.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>[s.slug,s.label]))}__name(loreSkillsFromActors,"loreSkillsFromActors"),__name2(loreSkillsFromActors,"loreSkillsFromActors");async function getActions(){const indexFields=["system.slug"],pack=game.packs.get("pf2e.actionspf2e");if(pack){const actions=(await pack.getIndex({fields:indexFields})).map(a=>[a.system.slug,a.name]);return Object.fromEntries(actions)}else return{}}__name(getActions,"getActions"),__name2(getActions,"getActions");class CheckPromptDialog extends Application{static{__name(this,"CheckPromptDialog")}static{__name2(this,"CheckPromptDialog")}#actions;#lores;static get defaultOptions(){return{...super.defaultOptions,classes:["dialog"],id:"generate-check-prompt",tabs:[{navSelector:".skill-save-navigation",contentSelector:".check-prompt-content",initial:"skills"},{navSelector:".dc-navigation",contentSelector:".dc-content",initial:"set-dc"}],template:"systems/pf2e/templates/gm/check-prompt.hbs",title:game.i18n.localize("PF2E.Actor.Party.CheckPrompt.Title"),width:400,height:"auto"}}async getData(){return this.#actions=await getActions(),this.#lores=loreSkillsFromActors(this.options.actors??game.actors.party?.members??[]),{proficiencyRanks:this.#prepareProficiencyRanks(),dcAdjustments:this.#prepareDCAdjustments()}}#prepareProficiencyRanks(){const pwol=game.pf2e.settings.variants.pwol.enabled;return PROFICIENCY_RANKS.map(value=>({value,label:`${value} (${calculateSimpleDC(value,{pwol})})`}))}#prepareDCAdjustments(){return Object.entries(CONFIG.PF2E.dcAdjustments).filter(([value,_])=>value!=="normal").map(([value,name2])=>({value,label:`${game.i18n.localize(name2)} (${signedInteger(adjustDC(0,value))})`}))}activateListeners($html){const html=$html[0],skillEl=html.querySelector("input#check-prompt-skills"),skills={...omit(CONFIG.PF2E.skillList,["lore"]),perception:"PF2E.PerceptionLabel"};tagify(skillEl,{whitelist:skills});const saveEl=html.querySelector("input#check-prompt-saves");tagify(saveEl,{whitelist:CONFIG.PF2E.saves});const loreEl=html.querySelector("input#check-prompt-lores"),loreOptions=isEmpty(this.#lores||{})?{}:{whitelist:this.#lores};tagify(loreEl,loreOptions);const actionEl=html.querySelector("input#check-prompt-actions"),actionOptions=isEmpty(this.#actions||{})?{}:{whitelist:this.#actions,enforceWhitelist:!1};tagify(actionEl,actionOptions);const traitEl=html.querySelector("input#check-prompt-traits");tagify(traitEl,{whitelist:CONFIG.PF2E.actionTraits,enforceWhitelist:!1}),html.querySelector("div.form-group a.add-roll-options")?.addEventListener("click",()=>{const sectionEl=html.querySelector("section.check-prompt-content");sectionEl&§ionEl.classList.toggle("show-roll-options")}),htmlQuery(html,"[data-action=post]")?.addEventListener("click",async()=>{this.#generatePrompt()}),htmlQuery(html,"[data-action=cancel]")?.addEventListener("click",async()=>{this.close()})}#generatePrompt(){const html=this.element[0],types=[],traits=[],extras=[],activeSkillSaveTab=htmlQuery(html,"section.check-prompt-content section.tab.active");if(activeSkillSaveTab?.dataset.tab==="skills"?(types.push(...this.#htmlQueryTags(html,"input#check-prompt-skills")),types.push(...this.#htmlQueryTags(html,"input#check-prompt-lores").map(t=>this.#formatLoreType(t))),traits.push(...this.#htmlQueryTags(html,"input#check-prompt-traits")),traits.push(...this.#htmlQueryTags(html,"input#check-prompt-actions").map(a=>this.#formatActionType(a))),html.querySelector("input#check-prompt-secret:checked")&&!traits.includes("secret")&&traits.push("secret")):activeSkillSaveTab?.dataset.tab==="saves"&&(types.push(...this.#htmlQueryTags(html,"input#check-prompt-saves")),htmlQuery(html,"input#check-prompt-basic-save:checked")&&extras.push("basic:true")),types.length>0){const titleEl=htmlQuery(html,"input#check-prompt-title"),flavor=titleEl?.value?`<h4 class="action"><strong>${titleEl.value}</strong></h4><hr>`:"",dc=this.#getDC(html),content=types.map(type=>this.#constructCheck(type,dc,traits,extras)).join("");ChatMessagePF2e.create({user:game.user.id,flavor,content})}}#htmlQueryTags(html,selector){const el=htmlQuery(html,selector);return(el instanceof HTMLInputElement&&el.value?JSON.parse(el.value):[]).map(tag=>tag.id||tag.value)}#formatLoreType(type){let loreType=type.toLowerCase().replaceAll(" ","-").trim();return loreType.includes("lore")||(loreType=loreType.concat("-lore")),loreType}#formatActionType(type){return`action:${type.toLowerCase().replace("action:","").trim()}`}#getDC(html){const dc=(()=>{const pwol=game.pf2e.settings.variants.pwol.enabled,activeDCTab=htmlQuery(html,"section.dc-content section.tab.active");if(activeDCTab?.dataset.tab==="set-dc")return Number(htmlQuery(html,"input#check-prompt-dc")?.value||NaN);if(activeDCTab?.dataset.tab==="simple-dc"){const profRank=htmlQuery(html,"select#check-prompt-simple-dc")?.value;if(tupleHasValue(PROFICIENCY_RANKS,profRank))return calculateSimpleDC(profRank,{pwol})}else if(activeDCTab?.dataset.tab==="level-dc"){const level=Number(htmlQuery(html,"input#check-prompt-level-dc")?.value||NaN);if(Number.isInteger(level))return calculateDC(+level,{pwol})}return NaN})();if(Number.isInteger(dc)){const dcAdjustment=htmlQuery(html,"select#check-prompt-adjust-difficulty")?.value;return dcAdjustment?adjustDC(dc,dcAdjustment):dc}return null}#constructCheck(type,dc,traits,extras){return`<p>@Check[${[type,Number.isInteger(dc)?`dc:${dc}`:null,traits.length?`traits:${traits.join(",")}`:null].concat(...extras).filter(p=>p).join("|")}]</p>`}}async function checkPrompt(options={}){new CheckPromptDialog(options.actors?{actors:options.actors}:{}).render(!0)}__name(checkPrompt,"checkPrompt"),__name2(checkPrompt,"checkPrompt");function escapeHtml(text){const p=document.createElement("p");return p.innerText=text,p.innerHTML}__name(escapeHtml,"escapeHtml"),__name2(escapeHtml,"escapeHtml");function isExperiencedProfessional(actor){return actor.itemTypes.feat.some(i=>i.slug==="experienced-professional")}__name(isExperiencedProfessional,"isExperiencedProfessional"),__name2(isExperiencedProfessional,"isExperiencedProfessional");function degreeOfSuccessLabel(degreeIndex){const degreeSlug=DEGREE_OF_SUCCESS_STRINGS[degreeIndex];return game.i18n.localize(`PF2E.Check.Result.Degree.Check.${degreeSlug}`)}__name(degreeOfSuccessLabel,"degreeOfSuccessLabel"),__name2(degreeOfSuccessLabel,"degreeOfSuccessLabel");function coinsToString(coins,degreeOfSuccess){return degreeOfSuccess===0?"none":coins.toString()}__name(coinsToString,"coinsToString"),__name2(coinsToString,"coinsToString");function chatTemplate(skillName,earnIncomeResult){const degreeOfSuccess=degreeOfSuccessLabel(earnIncomeResult.degreeOfSuccess),payPerDay=escapeHtml(coinsToString(earnIncomeResult.rewards.perDay,earnIncomeResult.degreeOfSuccess)),combinedPay=escapeHtml(coinsToString(earnIncomeResult.rewards.combined,earnIncomeResult.degreeOfSuccess)),level=earnIncomeResult.level,daysSpentWorking=earnIncomeResult.daysSpentWorking,forDays=daysSpentWorking>1?`<p><strong>Salary for ${daysSpentWorking} days</strong> ${combinedPay}</p>`:"",successColor=earnIncomeResult.degreeOfSuccess>1?"darkgreen":"darkred",dc=earnIncomeResult.dc,roll=earnIncomeResult.roll;return`
|
|
<div class="pf2e chat-card">
|
|
<header class="card-header flexrow">
|
|
<img src="systems/pf2e/icons/equipment/treasure/currency/gold-pieces.webp" title="Income" width="36" height="36">
|
|
<h3>Earn Income Level ${level}</h3>
|
|
</header>
|
|
<div class="card-content">
|
|
<p><strong>Result</strong> <span style="color: ${successColor}">${degreeOfSuccess} (DC: ${dc}, Roll: ${roll})</span></p>
|
|
<p><strong>Skill</strong> ${escapeHtml(skillName)}</p>
|
|
<p><strong>Salary per day</strong> ${payPerDay}</p>
|
|
${forDays}
|
|
</div>
|
|
</div>
|
|
`}__name(chatTemplate,"chatTemplate"),__name2(chatTemplate,"chatTemplate");function postToChat(skillName,earnIncomeResult){const content=chatTemplate(skillName,earnIncomeResult);return ChatMessagePF2e.create({user:game.user.id,content,speaker:ChatMessage.getSpeaker()})}__name(postToChat,"postToChat"),__name2(postToChat,"postToChat");function calculateIncome({actor,skill,rollBrief,level,days,dc}){const options={useLoreAsExperiencedProfessional:isExperiencedProfessional(actor)&&!!skill.lore},proficiency=Math.max(1,skill.rank??1),result=earnIncome({level,days,rollBrief,proficiency,options,dc});postToChat(skill.label,result)}__name(calculateIncome,"calculateIncome"),__name2(calculateIncome,"calculateIncome");function runEarnIncome({actor,event:event2,skill,level,days}){const dc=calculateDC(level,{pwol:game.pf2e.settings.variants.pwol.enabled}),options=new Set(actor.getRollOptions(["all","skill-check",skill.slug]));options.add("action:earn-income"),game.pf2e.Check.roll(new game.pf2e.CheckModifier(`Earn Income: ${skill.label}`,skill,[]),{actor,type:"skill-check",dc:{value:dc},options},event2,roll=>{const dieValue=roll.dice[0].results[0].result,modifier=roll.total-dieValue;calculateIncome({actor,skill,rollBrief:{dieValue,modifier},level,days,dc})})}__name(runEarnIncome,"runEarnIncome"),__name2(runEarnIncome,"runEarnIncome");function askSkillPopupTemplate(skills){const level=Number(localStorage.getItem("earnIncomeLevel"))||0,days=Number(localStorage.getItem("earnIncomeDays"))||1,skillAcronym=localStorage.getItem("earnIncomeSkillAcronym"),skillOptions=skills.map(skill=>{const skillName=escapeHtml(skill.label),selected=skillAcronym===skill.slug?"selected":"";return`<option value="${skill.slug}" ${selected}>${skillName}</option>`}).join(""),levelOptions=Array(21).fill(0).map((_,index)=>`<option value="${index}" ${index===level?"selected":""}>${index}</option>`).join("");return`
|
|
<form>
|
|
<div class="form-group">
|
|
<label>Trained Skills/Lores</label>
|
|
<select name="skillAcronym">
|
|
${skillOptions}
|
|
</select>
|
|
</div>
|
|
<div class="form-group">
|
|
<label>Level</label>
|
|
<select name="level">
|
|
${levelOptions}
|
|
</select>
|
|
</div>
|
|
<div class="form-group">
|
|
<label>Days</label>
|
|
<input type="number" name="days" value="${days}">
|
|
</div>
|
|
</form>
|
|
`}__name(askSkillPopupTemplate,"askSkillPopupTemplate"),__name2(askSkillPopupTemplate,"askSkillPopupTemplate");function showEarnIncomePopup(actor){if(!actor?.isOfType("character")){ui.notifications.error("You must select at least one PC");return}const skills=Object.values(actor.skills).filter(s=>!!s?.proficient);new Dialog({title:"Earn Income",content:askSkillPopupTemplate(skills),buttons:{no:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"},yes:{icon:fontAwesomeIcon("coins").outerHTML,label:"Earn Income",callback:($html,event2)=>{const html=$html[0],level=Number(html.querySelector("[name=level]")?.value)||0,days=Number(html.querySelector("[name=days]")?.value)||1,skillAcronym=html.querySelector("[name=skillAcronym]")?.value??"soc",skill=skills.find(s=>s.slug===skillAcronym);if(!skill)throw ErrorPF2e("Skill not found");localStorage.setItem("earnIncomeLevel",level.toString()),localStorage.setItem("earnIncomeDays",days.toString()),localStorage.setItem("earnIncomeSkillAcronym",skillAcronym),runEarnIncome({actor,event:event2,skill,level,days})}}},default:"yes"}).render(!0)}__name(showEarnIncomePopup,"showEarnIncomePopup"),__name2(showEarnIncomePopup,"showEarnIncomePopup");class PersistentDamageDialog extends Application{static{__name(this,"PersistentDamageDialog")}static{__name2(this,"PersistentDamageDialog")}constructor(actor,options={}){super(options),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:this.#prepareDamageTypes()}}#prepareDamageTypes(){return Object.keys(CONFIG.PF2E.damageTypes).map(type=>{const labels=CONFIG.PF2E.damageTypes,faGlyph=DAMAGE_TYPE_ICONS[type]??"question";return{type,iconClass:`fa-${faGlyph}`,label:game.i18n.localize(labels[type]??type)}}).sort((a,b)=>a.label.localeCompare(b.label))}#reportFormulaValidity(formula,input){return input?(formula.length>0&&DamageRoll.validate(formula)&&new DamageRoll(formula,{evaluatePersistent:!0}).maximumValue>=0?input.setCustomValidity(""):(input.setCustomValidity(game.i18n.localize("PF2E.Item.Condition.PersistentDamage.Dialog.Invalid")),input.addEventListener("input",()=>input.setCustomValidity(""),{once:!0})),input.reportValidity()):!1}activateListeners($html){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=this.#getInputElements(section);for(const element of Object.values(elements))element?.addEventListener("change",()=>{const formula=elements.formula?.value.trim()??"",damageType=elements.damageType?.value,dc=Number(elements.dc?.value)||15;this.#reportFormulaValidity(formula,elements.formula)&&existing.update({system:{persistent:{formula,damageType,dc}}})});htmlQuery(section,"a[data-action=delete")?.addEventListener("click",()=>{existing.delete()})}html.querySelector("a[data-action=add]")?.addEventListener("click",event2=>{const section=htmlClosest(event2.target,".persistent-entry");if(!section)return;const elements=this.#getInputElements(section),formula=elements.formula?.value.trim()||"1d6",damageType=elements.damageType?.value,dc=Number(elements.dc?.value)||15;if(this.#reportFormulaValidity(`(${formula})[${damageType}]`,elements.formula)){const baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),persistentSource=foundry.utils.mergeObject(baseConditionSource,{system:{persistent:{formula,damageType,dc}}});this.actor.createEmbeddedDocuments("Item",[persistentSource])}}),html.querySelector("a[data-action=roll-persistent]")?.addEventListener("click",()=>{const existing=this.actor.itemTypes.condition.filter(c=>c.slug==="persistent-damage");for(const condition of existing)condition.onEndTurn()})}#getInputElements(section){return{formula:htmlQuery(section,".formula"),damageType:htmlQuery(section,".damageType"),dc:htmlQuery(section,".dc")}}_injectHTML($html){super._injectHTML($html);const html=$html[0];((this.options.editing?htmlQuery(html,`[data-id=${this.options.editing}] .formula`):null)??htmlQuery(html,".new .formula"))?.focus()}}async function editPersistent(options){const actors=Array.isArray(options.actors)?options.actors:[options.actors];if(!actors?.length){ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.NoTokenSelected"));return}for(const actor of actors)actor&&new PersistentDamageDialog(actor).render(!0)}__name(editPersistent,"editPersistent"),__name2(editPersistent,"editPersistent");function encouragingWords(options){const localize=localizer("PF2E.Actions.EncouragingWords"),actors=Array.isArray(options.actors)?options.actors:[options.actors],actor=actors[0];if(actors.length>1||!(actor instanceof CharacterPF2e)){ui.notifications.error(localize("BadArgs"));return}const encouragingWordsMacro=__name2(async(DC,bonus,diplomacy)=>{diplomacy.roll({dc:{value:DC},extraRollOptions:["action:encouraging-words"],callback:async roll=>{let healFormula,successLabel;const degreeOfSuccess=Number(roll.options.degreeOfSuccess)||0,bonusString=bonus>0?`+ ${bonus}`:"";if(degreeOfSuccess===3?(healFormula=`2d8${bonusString}`,successLabel=localize("CritSuccess")):degreeOfSuccess===2?(healFormula=`1d8${bonusString}`,successLabel=localize("Success")):degreeOfSuccess===1?successLabel=localize("Failure"):degreeOfSuccess===0&&(healFormula="1d8",successLabel=localize("CritFailure")),healFormula){const healRoll=await new Roll(healFormula).roll({async:!0}),rollType=degreeOfSuccess>1?localize("Recovery"):localize("Damage"),token=actor.getActiveTokens().shift()?.document??null;ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor,token}),type:CONST.CHAT_MESSAGE_TYPES.ROLL,flavor:`<strong>${rollType} ${localize("Title")}</strong> (${successLabel})`,rolls:[healRoll.toJSON()]})}}})},"encouragingWordsMacro"),applyChanges=__name2($html=>{const{diplomacy}=actor.skills,mod=Number($html.find("[name=modifier]").val())||0,requestedProf=Number($html.find("[name=dc-type]").val())||1,rank=diplomacy.rank??0,usedProf=requestedProf<=rank?requestedProf:rank,roll=[()=>ui.notifications.warn(localize("NotTrained",{name:actor.name})),()=>encouragingWordsMacro(15+mod,0,diplomacy),()=>encouragingWordsMacro(20+mod,5,diplomacy),()=>encouragingWordsMacro(30+mod,15,diplomacy),()=>encouragingWordsMacro(40+mod,25,diplomacy)][usedProf];roll()},"applyChanges");new Dialog({title:localize("Title"),content:`
|
|
<div>${localize("ContentMain")}</div>
|
|
<hr/>
|
|
<form>
|
|
<div class="form-group">
|
|
<label for="dc-type">${localize("ContentLabel1")}</label>
|
|
<select id="dc-type" name="dc-type">
|
|
<option value="1">${localize("ContentOption1")}</option>
|
|
<option value="2">${localize("ContentOption2")}</option>
|
|
<option value="3">${localize("ContentOption3")}</option>
|
|
<option value="4">${localize("ContentOption4")}</option>
|
|
</select>
|
|
</div>
|
|
</form>
|
|
<form>
|
|
<div class="form-group">
|
|
<label for="modifier">${localize("ContentLabel2")}</label>
|
|
<input id="modifier" name="modifier" type="number" />
|
|
</div>
|
|
</form>
|
|
`,buttons:{yes:{icon:fontAwesomeIcon("hand-holding-medical").outerHTML,label:localize("Title"),callback:applyChanges},no:{icon:fontAwesomeIcon("times").outerHTML,label:localize("Cancel")}},default:"yes"}).render(!0)}__name(encouragingWords,"encouragingWords"),__name2(encouragingWords,"encouragingWords");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","crossbow","firearm","sling"]);[...MELEE_WEAPON_GROUPS,...MANDATORY_RANGED_GROUPS];const WEAPON_PROPERTY_RUNE_TYPES=new Set(["ancestralEchoing","anchoring","ashen","astral","authorized","bane","bloodbane","bloodthirsty","brilliant","called","coating","conducting","corrosive","crushing","cunning","dancing","deathdrinking","decaying","demolishing","disrupting","earthbinding","energizing","extending","fanged","fearsome","flaming","flurrying","frost","ghostTouch","giantKilling","greaterGiantKilling","greaterAnchoring","greaterAshen","greaterAstral","greaterBloodbane","greaterBrilliant","greaterCorrosive","greaterCrushing","greaterDecaying","greaterDisrupting","greaterExtending","greaterFanged","greaterFearsome","greaterFlaming","greaterFrost","greaterHauling","greaterImpactful","greaterRooting","greaterShock","greaterThundering","grievous","hauling","holy","hopeful","hooked","impactful","impossible","keen","kinWarding","majorFanged","majorRooting","merciful","pacifying","returning","rooting","serrating","shifting","shock","speed","spellStoring","swarming","thundering","trueRooting","underwater","unholy","vorpal","wounding"]),THROWN_RANGES=new Set([10,15,20,30,40,60,80,100]),WEAPON_RANGES=new Set([...THROWN_RANGES,50,70,90,110,120,140,150,180,200,240,300]);async function craft(options){const item=options.item??(options.uuid?await fromUuid(options.uuid):await SelectItemDialog.getItem("craft"));if(item){if(!(item instanceof PhysicalItemPF2e)){ui.notifications.warn(game.i18n.format("PF2E.Actions.Craft.Warning.NotPhysicalItem",{item:item.name??""}));return}}else{console.warn("PF2e System | No item selected to craft: aborting");return}const quantity=options.quantity??1,pwol=game.pf2e.settings.variants.pwol.enabled,dc=options.difficultyClass??{value:calculateDC(item.level,{pwol}),visible:!0},free=!!options.free,slug=options?.skill??"crafting",rollOptions=["action:craft"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Craft.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,difficultyClass:dc,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Craft","criticalFailure")],createMessage:!1,callback:async result=>{if(result.message instanceof ChatMessagePF2e){const message=result.message,flavor=await(async()=>["criticalSuccess","success","criticalFailure"].includes(result.outcome??"")?await renderCraftingInline(item,result.roll,quantity,result.actor,free):"")();flavor&&message.updateSource({flavor:message.flavor+flavor}),ChatMessage.create(message.toObject())}else console.error("PF2E | Unable to amend chat message with craft result.",result.message);options.callback?.(result)}}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(craft,"craft"),__name2(craft,"craft");function createEmptySpellcastingEntry(actor){return new SpellcastingEntryPF2e({name:"Untitled",type:"spellcastingEntry",system:{ability:{value:"cha"},spelldc:{value:0,dc:0},tradition:{value:"arcane"},prepared:{value:"innate"}}},{actor})}__name(createEmptySpellcastingEntry,"createEmptySpellcastingEntry"),__name2(createEmptySpellcastingEntry,"createEmptySpellcastingEntry");class SpellcastingCreateAndEditDialog extends FormApplication{static{__name(this,"SpellcastingCreateAndEditDialog")}static{__name2(this,"SpellcastingCreateAndEditDialog")}actor;constructor(object,options){super(object instanceof ActorPF2e?createEmptySpellcastingEntry(object):object.clone({},{keepId:!0}),options),this.actor=object instanceof ActorPF2e?object:object.actor}static get defaultOptions(){const options=super.defaultOptions;return options.id="spellcasting-dialog",options.classes=[],options.title=game.i18n.localize("PF2E.SpellcastingSettings.Title"),options.template="systems/pf2e/templates/actors/spellcasting-dialog.hbs",options.width=350,options.submitOnChange=!0,options.closeOnSubmit=!1,options}async getData(){const{actor}=this,extraStatistics=actor.synthetics.statistics.values(),classDCs=actor.isOfType("character")?Object.values(actor.system.proficiencies.classDCs).filter(cdc=>cdc.rank>0):[],selectedStatistic=actor.getStatistic(this.object.system.proficiency.slug);return{...await super.getData(),actor,system:this.object.toObject().system,statistics:[...extraStatistics,...classDCs.map(c=>({slug:c.slug,label:game.i18n.format("PF2E.Actor.Character.ClassDC.LabelSpecific",{class:c.label})}))],magicTraditions:CONFIG.PF2E.magicTraditions,spellcastingTypes:omit(CONFIG.PF2E.preparationType,["ritual"]),attributes:CONFIG.PF2E.abilities,isAttributeConfigurable:this.#canSetAttribute(),selectedAttribute:selectedStatistic?.attribute??this.object.attribute}}#canSetAttribute(){const slug=this.object._source.system.proficiency.slug,baseStat=this.actor.isOfType("character")?this.actor.getStatistic(slug):null;return!slug||!!baseStat&&!baseStat.attribute}async _updateObject(event2,formData){const wasInnate=this.object.isInnate,inputData=foundry.utils.expandObject(formData),system=foundry.utils.mergeObject(inputData.system??{},{prepared:{value:this.object.system.prepared.value},ability:{value:"cha"}},{overwrite:!1});if(inputData.system=system,system.prepared.value==="innate"&&!wasInnate&&(system.ability.value="cha"),system.proficiency?.slug&&(system.ability.value=""),system?.autoHeightenLevel&&(system.autoHeightenLevel.value||=null),this.object.updateSource(inputData),this.object.reset(),event2.type!=="submit"){await this.render();return}return this.updateAndClose()}async updateAndClose(){const updateData=this.object.toObject();if(this.object.isRitual&&(updateData.system.tradition.value="",updateData.system.ability.value=""),this.object.isPrepared||delete updateData.system.prepared.flexible,this.object.id===null)updateData.name=(()=>{const preparationType=game.i18n.localize(CONFIG.PF2E.preparationType[updateData.system.prepared.value])??"",magicTraditions2=CONFIG.PF2E.magicTraditions,traditionSpells=game.i18n.localize(magicTraditions2[this.object.tradition??""]);return this.object.isRitual||!traditionSpells?preparationType:game.i18n.format("PF2E.SpellCastingFormat",{preparationType,traditionSpells})})(),await this.actor.createEmbeddedDocuments("Item",[updateData]);else{const actualEntry=this.actor.spellcasting.get(this.object.id);if(!(actualEntry instanceof SpellcastingEntryPF2e))return;const system=pick(updateData.system,["prepared","tradition","ability","proficiency","autoHeightenLevel"]);await actualEntry.update({system})}this.close()}}async function createSpellcastingDialog(event2,object){return new SpellcastingCreateAndEditDialog(object,{top:event2.clientY-80,left:window.innerWidth-710,height:"auto"}).render(!0)}__name(createSpellcastingDialog,"createSpellcastingDialog"),__name2(createSpellcastingDialog,"createSpellcastingDialog");class SpellPreparationSheet extends ActorSheet{static{__name(this,"SpellPreparationSheet")}static{__name2(this,"SpellPreparationSheet")}constructor(item,options){super(item.actor,options),this.item=item}itemRenderer=new ItemSummaryRenderer(this);#searchEngine=new MiniSearch({fields:["name"],idField:"id",processTerm:t=>t.length>1?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0}});static get defaultOptions(){return{...super.defaultOptions,classes:["default","sheet","spellcasting-entry","preparation"],width:480,height:600,template:"systems/pf2e/templates/actors/spell-preparation-sheet.hbs",scrollY:[".sheet-content"],filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],sheetConfig:!1}}get id(){return`${super.id}-spellprep-${this.item.id}`}get title(){return game.i18n.format("PF2E.Actor.Creature.SpellPreparation.Title",{actor:this.actor.name})}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.class==="close")}async getData(){this.#searchEngine.removeAll();const entry=await this.item.getSheetData(),spells=Object.values(entry.spellPrepList??{}).flat().map(s=>pick(s.spell,["id","name"]));return this.#searchEngine.addAll(spells),{...await super.getData(),owner:this.actor.isOwner,entry}}activateListeners($html){super.activateListeners($html),$html[0].addEventListener("click",event2=>{const anchor=htmlClosest(event2.target,"[data-action]"),action2=anchor?.dataset.action;if(anchor&&action2)switch(action2){case"edit-spell":{this.#getSpellFromEvent(event2).sheet.render(!0);return}case"delete-spell":{this.#getSpellFromEvent(event2).delete();return}case"spell-to-chat":{this.#getSpellFromEvent(event2).toMessage(event2);return}case"toggle-flexible-collection":{const spell=this.#getSpellFromEvent(event2);spell.update({"system.location.signature":!spell.system.location.signature});return}case"toggle-summary":{const element=htmlClosest(anchor,"[data-item-id]");element&&this.itemRenderer.toggleSummary(element);return}case"create-spell":{onClickCreateSpell(this.actor,{...anchor?.dataset,location:this.item.id});return}case"browse-spells":{const maxRank=Number(anchor.dataset.rank)||10,category=anchor.dataset.category??null;game.pf2e.compendiumBrowser.openSpellTab(this.item,maxRank,category)}}})}#getSpellFromEvent(event2){const itemId=htmlClosest(event2.target,"li[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});if(!item.isOfType("spell"))throw ErrorPF2e("Unexpected item type");return item}_onSearchFilter(_event,query,_rgx,html){const matches=query.length>1?new Set(this.#searchEngine.search(query).map(s=>s.id)):new Set;for(const row of htmlQueryAll(html,"li[data-item-id]"))row.hidden=query.length>1&&!matches.has(row.dataset.itemId??"")}async _onDropItemCreate(itemSource){const spellSources=(Array.isArray(itemSource)?itemSource:[itemSource]).filter(source=>source.type==="spell");for(const spellSource of spellSources)spellSource.system.location.value=this.item.id;return super._onDropItemCreate(spellSources)}async _onSortItem(event2,itemData){if(itemData.type!=="spell")return[];const spell=this.actor.items.get(itemData._id);return itemData.system.location.value!==this.item.id&&spell?.isOfType("spell")?[await this.item.spells?.addSpell(spell)??[]].flat():super._onSortItem(event2,itemData)}async _renderInner(data,options){return this.itemRenderer.saveAndRestoreState(()=>super._renderInner(data,options))}}class CreatureSheetPF2e extends ActorSheetPF2e{static{__name(this,"CreatureSheetPF2e")}static{__name2(this,"CreatureSheetPF2e")}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.icon=this.getProficiencyIcon(save.rank),save.hover=CONFIG.PF2E.proficiencyLevels[save.rank],save.label=CONFIG.PF2E.saves[key]}if(sheetData.data.attributes!==void 0&&(sheetData.data.attributes.perception.icon=this.getProficiencyIcon(sheetData.data.attributes.perception.rank),sheetData.data.attributes.perception.hover=CONFIG.PF2E.proficiencyLevels[sheetData.data.attributes.perception.rank]),sheetData.data.abilities)for(const key of ATTRIBUTE_ABBREVIATIONS)sheetData.data.abilities[key].label=CONFIG.PF2E.abilities[key];if(sheetData.data.skills){const skills=sheetData.data.skills;for(const[key,skill]of Object.entries(skills)){const label=objectHasKey(CONFIG.PF2E.skills,key)?CONFIG.PF2E.skills[key]:null;skill.icon=this.getProficiencyIcon(skill.rank??0),skill.hover=CONFIG.PF2E.proficiencyLevels[skill.rank??0],skill.label=skill.label??label??""}}return{...sheetData,languages:createSheetTags(CONFIG.PF2E.languages,actor.system.traits.languages),abilities:CONFIG.PF2E.abilities,actorSizes:CONFIG.PF2E.actorSizes,rarity:CONFIG.PF2E.rarityTraits,frequencies:CONFIG.PF2E.frequencies,attitude:CONFIG.PF2E.attitude,pfsFactions:CONFIG.PF2E.pfsFactions,dying:{maxed:actor.attributes.dying.value>=actor.attributes.dying.max,remainingDying:Math.max(actor.attributes.dying.max-actor.attributes.dying.value),remainingWounded:Math.max(actor.attributes.wounded.max-actor.attributes.wounded.value)}}}openSpellPreparationSheet(entryId){const entry=this.actor.items.get(entryId);if(entry?.isOfType("spellcastingEntry")&&entry.isPrepared){const offset=this.element.find(`.item-container[data-container-id="${entry.id}"] .prepared-toggle`).offset()??{left:0,top:0};new SpellPreparationSheet(entry,{top:offset.top-60,left:offset.left+200}).render(!0)}}async prepareSpellcasting(){return(await Promise.all(this.actor.spellcasting.map(async entry=>entry.getSheetData()))).sort((a,b)=>a.sort-b.sort)}getProficiencyIcon(level){return[...Array(level)].map(()=>fontAwesomeIcon("check-circle").outerHTML).join("")}activateListeners($html){super.activateListeners($html);const html=$html[0],carryMenuListener=__name2(event2=>{if(!(event2.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving carry-type link");const menu=event2.currentTarget,toggle=menu.nextElementSibling;toggle?.classList.contains("carry-type-hover")&&$(toggle).tooltipster("close");const carryType=menu.dataset.carryType;if(!setHasElement(ITEM_CARRY_TYPES,carryType))throw ErrorPF2e("Unexpected error retrieving requested carry type");const itemId=htmlClosest(menu,"[data-item-id]")?.dataset.itemId,item=this.actor.inventory.get(itemId,{strict:!0}),handsHeld=Number(menu.dataset.handsHeld)||0;if(!tupleHasValue([0,1,2],handsHeld))throw ErrorPF2e("Invalid number of hands specified");const inSlot=menu.dataset.inSlot==="true",current=item.system.equipped;(carryType!==current.carryType||inSlot!==current.inSlot||carryType==="held"&&handsHeld!==current.handsHeld)&&this.actor.adjustCarryType(item,{carryType,handsHeld,inSlot})},"carryMenuListener");for(const carryTypeMenu of htmlQueryAll(html,".tab.inventory a[data-carry-type]"))carryTypeMenu.addEventListener("click",carryMenuListener);const selectors="input[data-item-id][data-item-property], select[data-item-id][data-item-property]";$html.find(selectors).on("change",event2=>{const $target=$(event2.target),{itemId,itemProperty}=event2.target.dataset;if(!itemId||!itemProperty)return;const value=(()=>{const value2=$(event2.target).val();if(typeof value2>"u"||value2===null)return value2;switch($target.attr("data-dtype")??($target.attr("type")==="checkbox"?"Boolean":["number","range"].includes($target.attr("type")??"")?"Number":"String")){case"Boolean":return typeof value2=="boolean"?value2:value2==="true";case"Number":return Number(value2);case"String":return String(value2);default:return value2}})();this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[itemProperty]:value}])}),$html.find(".dots.dying, .dots.wounded").on("click contextmenu",event2=>{const condition=Array.from(event2.delegateTarget.classList).find(className=>["dying","wounded"].includes(className));if(condition){const currentMax=this.actor.system.attributes[condition]?.max;event2.type==="click"&¤tMax?this.actor.increaseCondition(condition,{max:currentMax}):event2.type==="contextmenu"&&this.actor.decreaseCondition(condition)}}),$html.find("[data-action=recovery-check]").tooltipster({theme:"crb-hover"}).filter(":not(.disabled)").on("click",event2=>{this.actor.rollRecovery(event2)});for(const anchor of htmlQueryAll(html,".skill-name.rollable, .skill-score.rollable"))anchor.addEventListener("click",()=>{const skill=anchor.closest("[data-skill]")?.dataset.skill??"",key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill,rollParams=eventToRollParams(event,{type:"check"});this.actor.skills[key]?.check.roll(rollParams)});for(const element of htmlQueryAll(html,"a[data-action=perception-check]"))element.addEventListener("click",event2=>{const extraRollOptions=element.dataset.secret?["secret"]:[];this.actor.perception.roll({...eventToRollParams(event2,{type:"check"}),extraRollOptions})});$html.find(".prepared-toggle").on("click",async event2=>{event2.preventDefault();const itemId=$(event2.currentTarget).parents(".item-container").attr("data-container-id")??"";this.openSpellPreparationSheet(itemId)});for(const toggle of htmlQueryAll(html,".slotless-level-toggle"))toggle.addEventListener("click",async()=>{const itemId=htmlClosest(toggle,".item-container")?.dataset.containerId??"",spellcastingEntry=this.actor.items.get(itemId);if(!spellcastingEntry?.isOfType("spellcastingEntry"))throw ErrorPF2e("Tried to toggle visibility of slotless levels on a non-spellcasting entry");await spellcastingEntry.update({"system.showSlotlessLevels.value":!spellcastingEntry.showSlotlessLevels})});for(const button of htmlQueryAll(html,"button[data-action=cast-spell]"))button.addEventListener("click",()=>{const spellEl=htmlClosest(button,".item"),{itemId,slotLevel,slotId,entryId}=spellEl?.dataset??{},collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),spell=collection.get(itemId,{strict:!0});collection.entry.cast(spell,{slot:Number(slotId??NaN),level:Number(slotLevel??NaN)})});$html.find(".spell-slots-increment-reset").on("click",event2=>{const target=$(event2.currentTarget),itemId=target.data().itemId,itemLevel=target.data().level,item=this.actor.items.get(itemId);if(item?.isOfType("spellcastingEntry")){const{system}=item.toObject();if(!system.slots)return;const slotLevel=goesToEleven(itemLevel)?`slot${itemLevel}`:"slot0";system.slots[slotLevel].value=system.slots[slotLevel].max,item.update({system})}else if(item?.isOfType("spell")){const max=item.system.location.uses?.max;if(!max)return;item.update({"system.location.uses.value":max})}}),$html.find(".focus-pool").on("change",event2=>{this.actor.update({"system.resources.focus.max":$(event2.target).val()})});for(const anchor of htmlQueryAll(html,".toggle-signature-spell"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,".item")?.dataset.itemId,spell=this.actor.items.get(itemId,{strict:!0});spell?.isOfType("spell")&&spell.update({"system.location.signature":!spell.system.location.signature})});for(const button of htmlQueryAll(html,".action-browse"))button.addEventListener("click",()=>this.#onClickBrowseActions(button));for(const button of htmlQueryAll(html,".spell-browse"))button.addEventListener("click",()=>this.#onClickBrowseSpells(button))}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers["spellcasting-create"]=event2=>{createSpellcastingDialog(event2,this.actor)},handlers["spellcasting-edit"]=event2=>{const containerId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId,entry=this.actor.items.get(containerId,{strict:!0});entry.isOfType("spellcastingEntry")&&createSpellcastingDialog(event2,entry)},handlers["spellcasting-remove"]=async event2=>{const itemId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0}),title=game.i18n.localize("PF2E.DeleteSpellcastEntryTitle"),content=await renderTemplate("systems/pf2e/templates/actors/delete-spellcasting-dialog.hbs");await Dialog.confirm({title,content})&&item.delete()},handlers}async _onSortItem(event2,itemSource){const dropItemEl=htmlClosest(event2.target,".item"),dropContainerEl=htmlClosest(event2.target,".item-container"),dropSlotType=dropItemEl?.dataset.itemType,dropContainerType=dropContainerEl?.dataset.containerType,item=this.actor.items.get(itemSource._id);if(!item)return[];if(item.isOfType("spell")){if(!(dropItemEl&&dropContainerEl))return[];const entryId=dropContainerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0});if(dropSlotType==="spellLevel"){const{level}=dropItemEl.dataset,spell=await collection.addSpell(item,{slotLevel:Number(level)});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}else if(dropItemEl.dataset.slotId){const dropId=Number(dropItemEl.dataset.slotId),slotRank=Number(dropItemEl.dataset.slotLevel);if(Number.isInteger(dropId)&&Number.isInteger(slotRank)){const allocated=await collection.prepareSpell(item,slotRank,dropId);if(allocated instanceof SpellcastingEntryPF2e)return[allocated]}}else if(dropSlotType==="spell"){const dropId=dropItemEl.dataset.itemId??"",target=this.actor.items.get(dropId);if(target?.isOfType("spell")&&item.id!==dropId){const sourceLocation=item.system.location.value,testSibling=__name2((item2,test)=>item2.isCantrip!==test.isCantrip?!1:!!(item2.isCantrip&&test.isCantrip||item2.isFocusSpell&&test.isFocusSpell||item2.rank===test.rank),"testSibling");if(sourceLocation===entryId&&testSibling(item,target)){const siblings=collection.filter(s=>testSibling(item,s));return await item.sortRelative({target,siblings}),[target]}else{const spell=await collection.addSpell(item,{slotLevel:target.rank});return this.openSpellPreparationSheet(collection.id),[spell??[]].flat()}}}else if(dropContainerType==="spellcastingEntry"){CONFIG.debug.hooks&&console.debug("PF2e System | ***** spell from same actor dropped on a spellcasting entry *****");const dropId=htmlClosest(event2.target,".item-container")?.dataset.containerId,updated=dropId?await item.update({"system.location.value":dropId}):null;return updated?[updated]:[]}}else if(item.isOfType("spellcastingEntry")&&dropContainerType==="spellcastingEntry"){const sourceId=item.id,dropId=dropContainerEl?.dataset.containerId??"",source=this.actor.items.get(sourceId),target=this.actor.items.get(dropId);if(source?.isOfType("spellcastingEntry")&&target?.isOfType("spellcastingEntry")&&source.id!==target.id){const siblings=this.actor.itemTypes.spellcastingEntry;return await source.sortRelative({target,siblings}),[source]}}return super._onSortItem(event2,itemSource)}async _handleDroppedItem(event2,item,data){const containerEl=htmlClosest(event2.target,".item-container[data-container-type=spellcastingEntry]");if(containerEl&&item.isOfType("spell")&&!item.isRitual){const entryId=containerEl.dataset.containerId,collection=this.actor.spellcasting.collections.get(entryId,{strict:!0}),slotLevel=Number(htmlClosest(event2.target,"[data-slot-level]")?.dataset.slotLevel??0);return this.openSpellPreparationSheet(collection.id),[await collection.addSpell(item,{slotLevel:Math.max(slotLevel,item.baseRank)})??[]].flat()}return super._handleDroppedItem(event2,item,data)}_getHeaderButtons(){const buttons=super._getHeaderButtons();if(!this.actor.isOfType("character","npc"))return buttons;if(this.isEditable){const index=buttons.findIndex(b=>b.class==="close");buttons.splice(index,0,{label:"Configure",class:"configure-creature",icon:"fa-solid fa-user-gear",onclick:()=>this.#onConfigureActor()})}return buttons}#onConfigureActor(){this.actorConfigClass&&new this.actorConfigClass(this.actor).render(!0)}#onClickBrowseActions(anchor){const types=(anchor.dataset.actionType||"").split(","),traits=(anchor.dataset.actionTrait||"").split(","),categories=(anchor.dataset.actionCategory||"").split(",");game.pf2e.compendiumBrowser.openActionTab({types,traits,categories})}#onClickBrowseSpells(anchor){const spellcastingIndex=htmlClosest(anchor,"[data-container-id]")?.dataset.containerId??"",entry=this.actor.spellcasting.get(spellcastingIndex);if(!entry)return;const maxRank=Number(anchor.dataset.rank)||10,category=anchor.dataset.category??null;game.pf2e.compendiumBrowser.openSpellTab(entry,maxRank,category)}async _updateObject(event2,formData){const heldShield=this.actor.heldShield;return heldShield&&typeof formData["system.attributes.shield.hp.value"]=="number"&&await heldShield.update({"system.hp.value":formData["system.attributes.shield.hp.value"]}),delete formData["system.attributes.shield.hp.value"],super._updateObject(event2,formData)}}async function add(actor,event2){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,template=await renderTemplate("systems/pf2e/templates/actors/add-combat-proficiency-dialog.hbs",{message:game.i18n.localize("PF2E.AddCombatProficiency.Message"),weaponGroups:weaponGroups2,baseWeapons});new Dialog({title:game.i18n.localize("PF2E.AddCombatProficiency.Title"),content:template,buttons:{add:{icon:fontAwesomeIcon("check").outerHTML,label:game.i18n.localize("PF2E.AddShortLabel"),callback:async $dialog=>{const selection=$dialog.find("select[name=proficiency]").val();if(typeof selection=="string"&&selection){const proficiencyKey=selection in weaponGroups2?`weapon-group-${selection}`:`weapon-base-${selection}`;await actor.addAttackProficiency(proficiencyKey);const tab=htmlClosest(event2.currentTarget,".tab.skills");if(tab){const $tab=$(tab);$tab.animate({scrollTop:$tab.height()},"slow")}}}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}__name(add,"add"),__name2(add,"add");function remove(actor,event2){const weaponGroups2=CONFIG.PF2E.weaponGroups,baseWeapons=CONFIG.PF2E.baseWeaponTypes,baseShields=CONFIG.PF2E.baseShieldTypes,key=htmlClosest(event2.currentTarget,"li.skill.custom")?.dataset.slug??"",translationKey=key?.replace(/^weapon-(?:base|group)-/,"")??"",name2=objectHasKey(weaponGroups2,translationKey)?game.i18n.localize(weaponGroups2[translationKey]):baseWeapons[translationKey]??baseShields[translationKey]??translationKey,localize=localizer("PF2E.RemoveCombatProficiency"),message=localize("Message",{proficiency:name2});Dialog.confirm({title:localize("Title"),content:`<p>${message}</p>`,defaultYes:!1,yes:()=>{key in(actor._source.system.proficiencies?.attacks??{})&&actor.update({[`system.proficiencies.attacks.-=${key}`]:null})}})}__name(remove,"remove"),__name2(remove,"remove");const ManageAttackProficiencies={add,remove};class AttributeBuilder extends Application{static{__name(this,"AttributeBuilder")}static{__name2(this,"AttributeBuilder")}actor;#abpEnabled;constructor(actor){super(),this.actor=actor,this.#abpEnabled=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor),actor.apps[this.appId]=this}static get defaultOptions(){return{...super.defaultOptions,classes:["attribute-builder"],title:game.i18n.localize("PF2E.Actor.Character.Attribute.Boosts"),template:"systems/pf2e/templates/actors/character/attribute-builder.hbs",width:"auto",height:"auto"}}get id(){return`attribute-builder-${this.actor.uuid}`}async getData(options={}){const{actor}=this,build=actor.system.build.attributes;return{...await super.getData(options),actor,attributes:CONFIG.PF2E.abilities,manual:build.manual,ancestry:actor.ancestry,background:actor.background,class:actor.class,attributeModifiers:mapValues$1(actor.abilities,(value,attribute)=>{const mod=build.manual?actor._source.system.abilities?.[attribute].mod??0:value.base;return{mod:Number(mod.toFixed(1)).signedString(),label:CONFIG.PF2E.abilities[attribute]}}),manualKeyAttribute:actor.keyAttribute,keyOptions:build.keyOptions,...this.#calculateAncestryBoosts(),backgroundBoosts:this.#calculateBackgroundBoosts(),legacyFlaws:actor.ancestry?.system.voluntary?.boost!==void 0,levelBoosts:this.#calculateLeveledBoosts()}}#createButtons(){return Array.from(ATTRIBUTE_ABBREVIATIONS).reduce((accumulated,attribute)=>(accumulated[attribute]={ability:attribute},accumulated),{})}#calculateAncestryBoosts(){const{actor}=this,ancestry=actor.ancestry;if(!ancestry)return{ancestryBoosts:null,voluntaryFlaws:null};const buttons=this.#createButtons(),[maxBoosts,selectedBoosts]=(()=>{const alternateAncestryBoosts=ancestry.system.alternateAncestryBoosts;if(alternateAncestryBoosts)return[2,alternateAncestryBoosts];const baseBoosts=Object.values(ancestry.system.boosts),selectedBoosts2=baseBoosts.map(b=>b.selected).filter(b=>!!b);return[baseBoosts.filter(b=>b.value.length>0||b.selected).length,selectedBoosts2]})(),build=actor.system.build.attributes,netBoosted=difference(build.boosts.ancestry,build.flaws.ancestry),remaining=maxBoosts-selectedBoosts.length,lockedBoosts=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedBoosts,lockedFlaws=ancestry.system.alternateAncestryBoosts?null:ancestry.lockedFlaws;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons[attribute],selected=selectedBoosts.includes(attribute);state.boost={selected,locked:lockedBoosts?.includes(attribute),disabled:selected?!1:!remaining||netBoosted.includes(attribute)},lockedFlaws?.includes(attribute)&&(state.flaw={selected:!0,locked:!0})}const voluntaryFlaws=(()=>{const voluntary=ancestry.system.voluntary??{flaws:[]},legacyFlaws=voluntary.boost!==void 0,flawsComplete=legacyFlaws&&voluntary.flaws.length>=2,buttons2=this.#createButtons();for(const attribute of ATTRIBUTE_ABBREVIATIONS){const state=buttons2[attribute],numFlaws=voluntary.flaws.filter(f=>f===attribute).length;if(state.flaw={selected:numFlaws>0,disabled:!numFlaws&&flawsComplete},legacyFlaws){lockedBoosts?.includes(attribute)&&(state.flaw.second={selected:numFlaws>1,disabled:!numFlaws||numFlaws<2&&flawsComplete});const boosted=voluntary.boost===attribute;state.boost={selected:boosted,disabled:boosted?!1:!flawsComplete||!!voluntary.boost||netBoosted.includes(attribute)}}}return{remaining:voluntary&&legacyFlaws&&!voluntary.boost?1:0,buttons:buttons2,voluntaryBoostsRemaining:0,labels:this.#getBoostFlawLabels(ancestry.system.flaws)}})();return{ancestryBoosts:{buttons,remaining,labels:this.#getBoostFlawLabels(ancestry.system.boosts),flawLabels:this.#getBoostFlawLabels(ancestry.system.flaws),alternate:!!ancestry.system.alternateAncestryBoosts},voluntaryFlaws}}#calculateBackgroundBoosts(){const{actor}=this;if(!actor.background)return null;const buttons=this.#createButtons(),boosts=Object.values(actor.background.system.boosts).filter(b=>b.value.length>0),selectedBoosts=boosts.map(b=>b.selected).filter(b=>!!b),unselectedRestricted=boosts.filter(b=>b.value.length<6&&!b.selected).flatMap(b=>b.value),remaining=boosts.length-selectedBoosts.length;for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=selectedBoosts.includes(attribute),mightBeForced=unselectedRestricted.includes(attribute);buttons[attribute].boost={selected,disabled:!(selected||remaining)||!!unselectedRestricted.length&&!mightBeForced}}const labels=this.#getBoostFlawLabels(actor.background.system.boosts),tooltip=(()=>{const boosts2=actor.background?.system.boosts??{};if(Object.values(boosts2).length===2&&Object.values(boosts2)[0].value.length===2&&Object.values(boosts2)[1].value.length===6){const choices=Object.values(boosts2)[0].value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b]));return game.i18n.format("PF2E.Actor.Character.AttributeBuilder.BackgroundBoostDescription",{a:choices[0],b:choices[1]})}else return null})();return{buttons,remaining,labels,tooltip}}#calculateLeveledBoosts(){const build=this.actor.system.build.attributes,isGradual=game.settings.get("pf2e","gradualBoostsVariant"),boostIsPartial=__name2((attribute,level,isApex)=>{if(level<5||build.manual||isApex)return!1;const boosts=compact([build.boosts.ancestry.find(a=>a===attribute),build.boosts.background.find(a=>a===attribute),build.boosts.class===attribute?attribute:null,build.boosts[1].find(a=>a===attribute),level===20?build.boosts[20].find(a=>a===attribute):null,level>=15?build.boosts[15].find(a=>a===attribute):null,level>=10?build.boosts[10].find(a=>a===attribute):null,level>=5?build.boosts[5].find(a=>a===attribute):null]).length,flaws=Number(build.flaws.ancestry.some(a=>a===attribute)),netBoosts=boosts-flaws,cssClasses={0:!1,1:!0};return netBoosts>=5?cssClasses[netBoosts%2]:!1},"boostIsPartial");return[1,5,10,15,17,20].flatMap(level=>{const isApex=level===17;if(isApex&&!this.#abpEnabled)return[];const remaining=isApex?+!build.apex:build.allowedBoosts[level]-build.boosts[level].length,buttons=this.#createButtons();for(const attribute of ATTRIBUTE_ABBREVIATIONS){const selected=isApex?build.apex===attribute:build.boosts[level].includes(attribute),partial=selected&&boostIsPartial(attribute,level,isApex);buttons[attribute].boost={selected,partial,disabled:!remaining}}const eligible=isApex?this.actor.level>=17:build.allowedBoosts[level]>0,minLevel=isGradual&&!isApex?Math.max(1,level-3):level;return{buttons,remaining,level,eligible,minLevel,isApex}})}#getBoostFlawLabels(boostData){return Object.values(boostData).flatMap(boosts=>boosts.value.length===6?game.i18n.localize("PF2E.AbilityFree"):boosts.value.length>0?boosts.value.map(b=>game.i18n.localize(CONFIG.PF2E.abilities[b])).join(" or "):[])}async _render(force,options){return maintainFocusInRender(this,()=>super._render(force,options))}async close(options={}){return delete this.actor.apps[this.appId],super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0],{actor}=this;$html.find("[data-tooltip-content]").tooltipster({contentAsHTML:!0,arrow:!1,debug:!1,interactive:!0,maxWidth:350,side:["bottom"],theme:"crb-hover"});for(const input of htmlQueryAll(html,"input[type=text], input[type=number]"))input.addEventListener("focus",()=>{input.type==="text"&&input.dataset.dtype==="Number"&&(input.value=input.value.replace(/[^-.0-9]/g,""),input.type="number"),input.select()}),input.addEventListener("blur",()=>{if(input.type==="number"&&input.dataset.dtype==="Number"){input.type="text";const newValue=Math.clamped(Number(input.value)||0,-5,10);input.value=signedInteger(newValue);const propertyPath=input.dataset.property;if(!propertyPath)throw ErrorPF2e("Empty property path");actor.update({[propertyPath]:newValue})}});htmlQuery(html,"[data-action=toggle-alternate-ancestry-boosts]")?.addEventListener("click",()=>{actor.ancestry&&(actor.ancestry.system.alternateAncestryBoosts?actor.ancestry.update({"system.-=alternateAncestryBoosts":null}):actor.ancestry.update({"system.alternateAncestryBoosts":[]}))}),htmlQuery(html,"[data-action=toggle-legacy-voluntary-flaw]")?.addEventListener("click",async()=>{const ancestry=actor.ancestry;if(!ancestry)return;const voluntary=ancestry.system.voluntary;if(voluntary?.boost!==void 0){const flaws=uniq(voluntary.flaws);ancestry.update({system:{voluntary:{"-=boost":null,flaws}}})}else{const flaws=voluntary?.flaws.slice(0,2)??[];ancestry.update({system:{voluntary:{boost:null,flaws}}})}});for(const button of htmlQueryAll(html,"[data-section=ancestry] .boost"))button.addEventListener("click",async()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;if(ancestry.system.alternateAncestryBoosts){const existingBoosts=ancestry.system.alternateAncestryBoosts,boosts=existingBoosts.includes(attribute)?existingBoosts.filter(b=>b!==attribute):[...existingBoosts,attribute].slice(0,2);ancestry.update({"system.alternateAncestryBoosts":boosts});return}const boostToRemove=Object.entries(ancestry.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){await ancestry.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(ancestry.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&await ancestry.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"[data-section=voluntary] .boost-button"))button.addEventListener("click",()=>{const ancestry=actor.ancestry,attribute=button.dataset.attribute;if(!ancestry||!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const removing=button.classList.contains("selected");if(button.dataset.action==="flaw"){const{flaws,boost}=ancestry.system.voluntary??{flaws:[]},alreadyHasFlaw=flaws.includes(attribute),isLegacy=boost!==void 0;if(removing&&alreadyHasFlaw&&!boost){flaws.splice(flaws.indexOf(attribute),1),ancestry.update({system:{voluntary:{flaws}}});return}const canDoubleFlaw=ancestry.lockedBoosts.includes(attribute)&&isLegacy,maxFlaws=isLegacy?2:6;flaws.length<maxFlaws&&(!alreadyHasFlaw||canDoubleFlaw)&&(flaws.push(attribute),ancestry.update({system:{voluntary:{flaws}}}))}else{const boost=removing?null:attribute;ancestry.update({system:{voluntary:{boost}}})}});for(const button of htmlQueryAll(html,"[data-section=background] .boost"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))return;const boostToRemove=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>b.selected===attribute);if(boostToRemove){actor.background?.update({[`system.boosts.${boostToRemove[0]}.selected`]:null});return}const freeBoost=Object.entries(actor.background?.system.boosts??{}).find(([,b])=>!b.selected&&b.value.length>0);freeBoost&&actor.background?.update({[`system.boosts.${freeBoost[0]}.selected`]:attribute})});for(const button of htmlQueryAll(html,"button[data-action=class-key-attribute]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);actor.system.build.attributes.manual?actor.update({"system.details.keyability.value":attribute}):actor.class?.update({"system.keyAbility.selected":attribute})});for(const button of htmlQueryAll(html,"[data-level] .boost"))button.addEventListener("click",()=>{const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)||!tupleHasValue([1,5,10,15,20],level))return;const buildSource=foundry.utils.mergeObject(actor.toObject().system.build??{},{attributes:{boosts:{}}}),boosts=buildSource.attributes.boosts[level]??=[];boosts.includes(attribute)?boosts.splice(boosts.indexOf(attribute),1):boosts.push(attribute),actor.update({"system.build":buildSource})});for(const button of htmlQueryAll(html,"button[data-action=apex]"))button.addEventListener("click",()=>{const attribute=button.dataset.attribute;if(!setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute))throw ErrorPF2e(`Unrecognized attribute abbreviation: ${attribute}`);const current=this.actor.system.build.attributes.apex;actor.update({"system.build.attributes.apex":this.#abpEnabled&&attribute!==current?attribute:null})});htmlQuery(html,"input[name=toggle-manual-mode]")?.addEventListener("click",()=>{this.#toggleAttributeManagement()}),htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>this.close())}async#toggleAttributeManagement(){const{actor}=this;if(Object.keys(actor._source.system.abilities??{}).length===0){const baseAbilities=Array.from(ATTRIBUTE_ABBREVIATIONS).reduce((accumulated,abbrev)=>({...accumulated,[abbrev]:{value:10}}),{});await actor.update({"system.abilities":baseAbilities})}else await actor.update({"system.abilities":null})}}class CreatureConfig extends DocumentSheet{static{__name(this,"CreatureConfig")}static{__name2(this,"CreatureConfig")}get title(){const namespace=this.actor.isOfType("character")?"Character":"NPC";return game.i18n.localize(`PF2E.Actor.${namespace}.Configure.Title`)}get template(){return`systems/pf2e/templates/actors/${this.actor.type}/config.hbs`}get actor(){return this.object}static get defaultOptions(){const options=super.defaultOptions;return options.width=450,options}async getData(options={}){const source=this.actor._source,alliance=source.system.details?.alliance===null?"neutral":source.system.details?.alliance??"default",defaultValue=game.i18n.localize(this.actor.hasPlayerOwner?"PF2E.Actor.Creature.Alliance.Party":"PF2E.Actor.Creature.Alliance.Opposition"),allianceOptions={default:game.i18n.format("PF2E.Actor.Creature.Alliance.Default",{alliance:defaultValue}),opposition:"PF2E.Actor.Creature.Alliance.Opposition",party:"PF2E.Actor.Creature.Alliance.Party",neutral:"PF2E.Actor.Creature.Alliance.Neutral"};return{...await super.getData(options),alliances:createSheetOptions(allianceOptions,{value:[alliance]})}}async _updateObject(event2,formData){const key="system.details.alliance",alliance=formData[key];if(alliance==="default")delete formData[key],formData["system.details.-=alliance"]=null;else if(alliance==="neutral")formData[key]=null;else if(!setHasElement(ALLIANCES,alliance))throw ErrorPF2e("Unrecognized alliance");return super._updateObject(event2,formData)}}class CharacterConfig extends CreatureConfig{static{__name(this,"CharacterConfig")}static{__name2(this,"CharacterConfig")}async getData(options={}){const{showBasicUnarmed}=this.actor.flags.pf2e;return{...await super.getData(options),showBasicUnarmed}}}class CraftingFormula{static{__name(this,"CraftingFormula")}static{__name2(this,"CraftingFormula")}constructor(item,{dc,batchSize,deletable=!1}={}){this.item=item,this.dc=dc??calculateDC(item.level,{rarity:item.rarity,pwol:game.pf2e.settings.variants.pwol.enabled}),this.batchSize=Math.max(batchSize??1,this.defaultBatchSize),this.deletable=deletable}dc;batchSize;deletable;get uuid(){return this.item.uuid}get img(){return this.item.img}get name(){return this.item.name}get level(){return this.item.level}get rarity(){return this.item.rarity}get price(){return this.item.price}get cost(){return CoinsPF2e.fromPrice(this.price,this.batchSize)}get minimumBatchSize(){return STACK_DEFINITIONS[this.item.system.stackGroup??""]?.size??1}get defaultBatchSize(){const{item}=this,isMundaneAmmo=item instanceof ConsumablePF2e&&item.isAmmo&&!item.isMagical,isConsumable=item instanceof ConsumablePF2e&&item.category!=="wand"||item instanceof WeaponPF2e&&item.baseType==="alchemical-bomb";return Math.max(this.minimumBatchSize,isMundaneAmmo?10:isConsumable?4:1)}get description(){return this.item.description}}class CraftingEntry{static{__name(this,"CraftingEntry")}static{__name2(this,"CraftingEntry")}preparedCraftingFormulas;preparedFormulaData;name;selector;isAlchemical;isDailyPrep;isPrepared;craftableItems;maxSlots;fieldDiscovery;batchSize;fieldDiscoveryBatchSize;maxItemLevel;parentItem;constructor(actor,knownFormulas,data){this.selector=data.selector,this.name=data.name,this.isAlchemical=!!data.isAlchemical,this.isDailyPrep=!!data.isDailyPrep,this.isPrepared=!!data.isPrepared,this.maxSlots=data.maxSlots??0,this.maxItemLevel=data.maxItemLevel||actor.level,this.fieldDiscovery=data.fieldDiscovery?new PredicatePF2e(data.fieldDiscovery):null,this.batchSize=data.batchSize,this.fieldDiscoveryBatchSize=data.fieldDiscoveryBatchSize,this.craftableItems=new PredicatePF2e(data.craftableItems),this.preparedFormulaData=(data.preparedFormulaData||[]).map(prepData=>knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID)?prepData:null).filter(prepData=>!!prepData),this.parentItem=actor.items.get(data.parentItem,{strict:!0}),this.preparedCraftingFormulas=this.preparedFormulaData.sort((prepDataA,prepDataB)=>(prepDataA.sort??0)-(prepDataB.sort??0)).map(prepData=>{const formula=knownFormulas.find(formula2=>formula2.uuid===prepData.itemUUID);return formula?Object.assign(new CraftingFormula(formula.item),{quantity:prepData.quantity||1,expended:!!prepData.expended,isSignatureItem:!!prepData.isSignatureItem,sort:prepData.sort??0}):null}).filter(prepData=>!!prepData)}get actor(){return this.parentItem.actor}get formulas(){const formulas=this.preparedCraftingFormulas.map(formula=>({uuid:formula.uuid,img:formula.img,name:formula.name,expended:formula.expended,quantity:formula.quantity,isSignatureItem:formula.isSignatureItem}));if(this.maxSlots>0){const fill=this.maxSlots-formulas.length;if(fill>0){const nulls=new Array(fill).fill(null);return formulas.concat(nulls)}}return formulas}get reagentCost(){if(!this.isAlchemical)return 0;const fieldDiscoveryQuantity=this.preparedCraftingFormulas.filter(f=>!!this.fieldDiscovery?.test(f.item.getRollOptions("item"))||f.isSignatureItem).reduce((sum,current)=>sum+current.quantity,0),otherQuantity=this.preparedCraftingFormulas.filter(f=>!this.fieldDiscovery?.test(f.item.getRollOptions("item"))&&!f.isSignatureItem).reduce((sum,current)=>sum+current.quantity,0),fieldDiscoveryBatchSize=this.fieldDiscoveryBatchSize||3,batchSize=this.batchSize||2;return Math.floor(fieldDiscoveryQuantity/fieldDiscoveryBatchSize)+Math.ceil((fieldDiscoveryQuantity%fieldDiscoveryBatchSize+otherQuantity)/batchSize)}static isValid(data){return!!data&&!!data.name&&!!data.selector}async prepareFormula(formula){this.checkEntryRequirements(formula);const index=this.preparedFormulaData.findIndex(f=>f.itemUUID===formula.uuid);if(this.isAlchemical&&index!==-1){const formula2=this.preparedFormulaData[index];formula2.quantity?formula2.quantity+=1:formula2.quantity=2}else this.preparedFormulaData.push({itemUUID:formula.uuid,quantity:1});return this.#updateRE()}checkEntryRequirements(formula,{warn=!0}={}){return this.maxSlots&&this.formulas.filter(f=>f!==null).length>=this.maxSlots?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxSlots")),!1):this.actor.level<formula.level?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.CharacterLevel")),!1):formula.level>this.maxItemLevel?(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MaxItemLevel")),!1):this.craftableItems.test(formula.item.getRollOptions("item"))?!0:(warn&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.ItemMissingTraits")),!1)}async unprepareFormula(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return this.preparedFormulaData.splice(index,1),this.#updateRE()}async increaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity?formula.quantity+=1:formula.quantity=2,this.#updateRE()}async decreaseFormulaQuantity(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID)){if(formula.quantity?formula.quantity-=1:formula.quantity=0,formula.quantity<=0){await this.unprepareFormula(index,itemUUID);return}return this.#updateRE()}}async setFormulaQuantity(index,itemUUID,quantity){if(quantity<=0){await this.unprepareFormula(index,itemUUID);return}const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.quantity=quantity,this.#updateRE()}async toggleFormulaExpended(index,itemUUID){const formula=this.preparedFormulaData[index];if(!(!formula||formula.itemUUID!==itemUUID))return formula.expended=!formula.expended,this.#updateRE()}async toggleSignatureItem(itemUUID){const formula=this.preparedFormulaData.find(f=>f.itemUUID===itemUUID);if(formula)return formula.isSignatureItem=!formula.isSignatureItem,this.#updateRE()}async updateFormulas(formulas){return this.preparedFormulaData=formulas,this.#updateRE()}async#updateRE(){const rules=this.parentItem.toObject().system.rules,thisRule=rules.find(r=>r.key==="CraftingEntry"&&r.selector===this.selector);thisRule&&(thisRule.preparedFormulas=this.preparedFormulaData,await this.parentItem.update({"system.rules":rules}))}}class PCSheetTabManager{static{__name(this,"PCSheetTabManager")}static{__name2(this,"PCSheetTabManager")}constructor(actor,link){this.actor=actor,this.link=link,renderTemplate("systems/pf2e/templates/actors/character/manage-tabs.hbs").then(template=>{$(this.link).tooltipster({content:template,contentAsHTML:!0,delay:250,interactive:!0,theme:"crb-hover",title:game.i18n.localize("PF2E.TabManageTabsLabel"),trigger:"custom",triggerOpen:{click:!0},triggerClose:{originClick:!0,mouseleave:!0},functionReady:(_origin,helper)=>this.onReady(helper.tooltip),functionAfter:()=>this.onClose()})})}static initialize(actor,link){new this(actor,link)}onReady(tooltip){const tabVisibility=this.actor.flags.pf2e.sheetTabs,tabs=this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[];for(const tab of Array.from(tabs)){const tabName=tab.dataset.tab??"",selector=`input[data-tab-name="${tabName}"]`,input=tooltip.querySelector(selector);input&&(input.checked=tabVisibility[tabName]),tab.classList.contains("hidden")&&(tab.classList.remove("hidden"),tab.classList.add("to-hide"))}const checkboxes=Array.from(tooltip.querySelectorAll('input[type="checkbox"]'));for(const checkbox of checkboxes)this.handleOnChange(checkbox,checkboxes)}handleOnChange(checkbox,checkboxes){checkbox.addEventListener("change",async()=>{const nav=this.link.closest("nav"),tabName=checkbox?.dataset.tabName??"",tab=nav?.querySelector(`a.item[data-tab="${tabName}"]`);for(const c of checkboxes)c.readOnly=!0;checkbox.checked?(tab?.classList.remove("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.-=${tabName}`]:null},{render:!1})):(tab?.classList.add("to-hide"),await this.actor.update({[`flags.pf2e.sheetTabs.${tabName}`]:!1},{render:!1}));for(const c of checkboxes)c.readOnly=!1})}onClose(){const tabs=Array.from(this.link.closest("nav")?.querySelectorAll("a.item[data-tab]")??[]);for(const tab of tabs)tab.classList.contains("to-hide")&&(tab.classList.remove("to-hide"),tab.classList.add("hidden"))}}class CharacterSheetPF2e extends CreatureSheetPF2e{static{__name(this,"CharacterSheetPF2e")}static{__name2(this,"CharacterSheetPF2e")}actorConfigClass=CharacterConfig;#knownFormulas={};#formulaQuantities={};static get defaultOptions(){const options=super.defaultOptions;return options.classes=[...options.classes,"character"],options.width=750,options.height=800,options.scrollY.push(".tab.active .tab-content"),options.dragDrop.push({dragSelector:"ol[data-strikes] > li, ol[data-elemental-blasts] > li"}),options.tabs=[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"character"},{navSelector:".actions-nav",contentSelector:".actions-panels",initial:"encounter"}],options}get template(){return`systems/pf2e/templates/actors/character/${this.actor.limited&&!game.user.isGM?"limited":"sheet"}.hbs`}async getData(options){const sheetData=await super.getData(options),{actor}=this;if(this.actor.limited){const tab=options?.tabs.find(t=>t.navSelector===".sheet-navigation");tab&&(tab.initial="biography")}sheetData.numberToRank=mapToObj([0,1,2,3,4],n=>[n,game.i18n.localize(`PF2E.ProficiencyLevel${n}`)]),sheetData.martialProficiencies={attacks:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.attacks,(data,key)=>{const groupMatch=/^weapon-group-([-\w]+)$/.exec(key),baseWeaponMatch=/^weapon-base-([-\w]+)$/.exec(key);if(objectHasKey(CONFIG.PF2E.weaponCategories,key)){const locKey=sluggify(key,{camel:"bactrian"});data.label=setHasElement(WEAPON_CATEGORIES,key)?`PF2E.Actor.Character.Proficiency.Attack.${locKey}`:CONFIG.PF2E.weaponCategories[key]}else if(Array.isArray(groupMatch)){const weaponGroup=groupMatch[1];data.label=CONFIG.PF2E.weaponGroups[weaponGroup]??weaponGroup}else if(Array.isArray(baseWeaponMatch)){const baseType=baseWeaponMatch[1],baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes;data.label=baseWeaponTypes2[baseType]??baseShieldTypes2[baseType]??baseType}else data.label??=key;const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data})),defenses:sortLabeledRecord(mapValues$1(sheetData.data.proficiencies.defenses,(data,key)=>{if(key in CONFIG.PF2E.armorCategories){const locKey=sluggify(key,{camel:"bactrian"});data.label=`PF2E.Actor.Character.Proficiency.Defense.${locKey}`}const rank=data.rank??0;return data.value=createProficiencyModifier({actor,rank,domains:[]}).value,data}))};for(const key of["light-barding","heavy-barding"])sheetData.martialProficiencies.defenses[key]?.rank===0&&delete sheetData.martialProficiencies.defenses[key];sheetData.ancestry=actor.ancestry,sheetData.heritage=actor.heritage,sheetData.background=actor.background,sheetData.class=actor.class,sheetData.deity=actor.deity,sheetData.data.resources.heroPoints.hover=game.i18n.format(actor.heroPoints.value===1?"PF2E.HeroPointRatio.One":"PF2E.HeroPointRatio.Many",actor.heroPoints),sheetData.attributeBoostsAllocated=(()=>{const{build}=sheetData.data;if(build.attributes.manual||!isReallyPC(actor))return!0;const keyAttributeSelected=!sheetData.class||build.attributes.keyOptions.includes(sheetData.data.details.keyability.value),ancestryBoostsSelected=(sheetData.ancestry?.system.alternateAncestryBoosts?.length===2||Object.values(sheetData.ancestry?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected))&&sheetData.ancestry?.system.voluntary?.boost!==null,backgroundBoostsSelected=Object.values(sheetData.background?.system.boosts??{}).every(b=>b.value.length===0||!!b.selected);return ancestryBoostsSelected&&backgroundBoostsSelected&&keyAttributeSelected&&[1,5,10,15,20].filter(l=>build.attributes.allowedBoosts[l]>build.attributes.boosts[l].length).length===0})();const allClassDCs=Object.values(sheetData.data.proficiencies.classDCs),classDCs=allClassDCs.filter(cdc=>cdc.rank>0||allClassDCs.length>1).map(classDC=>({...classDC,icon:this.getProficiencyIcon(classDC.rank),hover:CONFIG.PF2E.proficiencyLevels[classDC.rank]})).sort((a,b)=>a.primary?-1:b.primary?1:a.slug.localeCompare(b.slug)),primaryClassDC=sheetData.data.attributes.classDC?.slug??null;sheetData.classDCs={dcs:classDCs,primary:primaryClassDC,perDCDetails:classDCs.length>1||!primaryClassDC};const abpEnabled=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(actor);sheetData.apexAttributeOptions=abpEnabled?[]:this.actor.itemTypes.equipment.flatMap(e=>e.system.apex?.selected===!1&&e.isInvested&&e.system.apex.attribute!==actor.system.build.attributes.apex?e.system.apex.attribute:[]),sheetData.magicTraditions=CONFIG.PF2E.magicTraditions,sheetData.preparationType=CONFIG.PF2E.preparationType,sheetData.spellcastingEntries=await this.prepareSpellcasting(),sheetData.hasNormalSpellcasting=sheetData.spellcastingEntries.some(s=>s.usesSpellProficiency),sheetData.data.attributes.perception.rankName=game.i18n.format(`PF2E.ProficiencyLevel${sheetData.data.attributes.perception.rank}`),sheetData.data.saves={fortitude:sheetData.data.saves.fortitude,reflex:sheetData.data.saves.reflex,will:sheetData.data.saves.will};for(const save of Object.values(sheetData.data.saves))save.short=game.i18n.format(`PF2E.Saves${save.label}Short`);sheetData.data.details.keyability.singleOption=actor.class?.system.keyAbility.value.length===1,sheetData.hasStamina=game.pf2e.settings.variants.stamina,sheetData.actions=this.#prepareAbilities(),sheetData.feats=[...actor.feats,actor.feats.bonus];const craftingFormulas=await actor.getCraftingFormulas(),formulasByLevel=groupBy$1(craftingFormulas,f=>f.level),flags=actor.flags.pf2e,hasQuickAlchemy=!!(actor.rollOptions.all["feature:quick-alchemy"]||actor.rollOptions.all["feat:quick-alchemy"]);sheetData.crafting={noCost:flags.freeCrafting,hasQuickAlchemy,knownFormulas:formulasByLevel,entries:await this.#prepareCraftingEntries(craftingFormulas)},this.#knownFormulas=Object.values(formulasByLevel).flat().reduce((result,entry)=>(entry.batchSize=this.#formulaQuantities[entry.uuid]??entry.batchSize,result[entry.uuid]=entry,result),{}),sheetData.abpEnabled=AutomaticBonusProgression.isEnabled(actor),sheetData.data.skills=Object.fromEntries(Object.entries(sheetData.data.skills).sort(([_keyA,skillA],[_keyB,skillB])=>game.i18n.localize(skillA.label??"").localeCompare(game.i18n.localize(skillB.label??""),game.i18n.lang))),sheetData.tabVisibility=foundry.utils.deepClone(actor.flags.pf2e.sheetTabs);const rollData=actor.getRollData(),biography=sheetData.biography=actor.system.details.biography,enrichmentOptions={rollData,secrets:actor.isOwner,async:!0},enrichPromises={appearance:TextEditor.enrichHTML(biography.appearance,enrichmentOptions),backstory:TextEditor.enrichHTML(biography.backstory,enrichmentOptions),campaignNotes:TextEditor.enrichHTML(biography.campaignNotes,enrichmentOptions),allies:TextEditor.enrichHTML(biography.allies,enrichmentOptions),enemies:TextEditor.enrichHTML(biography.enemies,enrichmentOptions),organizations:TextEditor.enrichHTML(biography.organizations,enrichmentOptions)};await Promise.all(Object.values(enrichPromises));for(const[key,content]of Object.entries(enrichPromises))sheetData.enrichedContent[key]=await content;try{const action2=new ElementalBlast(this.actor),blastData=(await Promise.all(action2.configs.map(c=>this.#getBlastData(action2,c)))).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));sheetData.elementalBlasts=blastData}catch{sheetData.elementalBlasts=[]}return sheetData}async prepareItems(sheetData){const actorData=sheetData.actor,lores=[];for(const itemData of sheetData.items)if(itemData.type==="lore"){itemData.system.icon=this.getProficiencyIcon((itemData.system.proficient||{}).value),itemData.system.hover=CONFIG.PF2E.proficiencyLevels[(itemData.system.proficient||{}).value];const rank=itemData.system.proficient?.value||0,proficiency=createProficiencyModifier({actor:this.actor,rank,domains:[]}).modifier,modifier=actorData.system.abilities.int.mod,itemBonus=Number((itemData.system.item||{}).value||0);itemData.system.itemBonus=itemBonus,itemData.system.value=modifier+proficiency+itemBonus,itemData.system.breakdown=`int modifier(${modifier}) + proficiency(${proficiency}) + item bonus(${itemBonus})`,lores.push(itemData)}actorData.pfsBoons=this.actor.pfsBoons,actorData.deityBoonsCurses=this.actor.deityBoonsCurses,actorData.lores=lores}#prepareAbilities(){const{actor}=this,result={encounter:{action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}},exploration:{active:[],other:[]},downtime:[]};for(const item of actor.items){if(!item.isOfType("action")&&!(item.isOfType("feat")&&item.actionCost)||item.slug==="elemental-blast"&&this.actor.flags.pf2e.kineticist)continue;const img=(()=>{const actionIcon=getActionIcon(item.actionCost),defaultIcon=ItemPF2e.getDefaultArtwork(item._source).img;return item.isOfType("action")&&![actionIcon,defaultIcon].includes(item.img)?item.img:item.system.selfEffect?.img??actionIcon})(),traits=item.system.traits.value,traitDescriptions2=item.isOfType("feat")?CONFIG.PF2E.featTraits:CONFIG.PF2E.actionTraits,action2={...pick(item,["id","name","actionCost","frequency"]),img,glyph:getActionGlyph(item.actionCost),traits:createSheetTags(traitDescriptions2,traits),feat:item.isOfType("feat")?item:null,hasEffect:!!item.system.selfEffect};if(traits.includes("exploration")){const active=actor.system.exploration.includes(item.id);action2.exploration={active},(active?result.exploration.active:result.exploration.other).push(action2)}else traits.includes("downtime")?result.downtime.push(action2):result.encounter[item.actionCost?.type??"free"]?.actions.push(action2)}for(const list of["action","reaction","free"])result.encounter[list].actions.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));return result.exploration.active.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.exploration.other.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result.downtime.sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),result}async#prepareCraftingEntries(formulas){const craftingEntries={dailyCrafting:!1,other:[],alchemical:{entries:[],totalReagentCost:0,infusedReagents:this.actor.system.resources.crafting.infusedReagents}};for(const entry of await this.actor.getCraftingEntries(formulas))entry.isAlchemical?(craftingEntries.alchemical.entries.push(entry),craftingEntries.alchemical.totalReagentCost+=entry.reagentCost||0,craftingEntries.dailyCrafting=!0):(craftingEntries.other.push(entry),entry.isDailyPrep&&(craftingEntries.dailyCrafting=!0));return craftingEntries}prepareInventoryItem(item){const data=super.prepareInventoryItem(item);data.isInvestable=!item.isInContainer&&item.isIdentified&&item.isInvested!==null;const invested=this.actor.inventory.invested,canInvest=invested&&invested.value<invested.max;return item.isOfType("armor")&&item.isEquipped&&!item.isInvested&&data.isInvestable&&canInvest&&(data.notifyInvestment=!0),data}openTab(name2){["encounter","exploration","downtime"].includes(name2)?(super.openTab("actions"),this._tabs[1].activate(name2)):super.openTab(name2)}activateListeners($html){super.activateListeners($html);const html=$html[0];this.#activateNavListeners(html),this.toggleInitiativeLink(),htmlQuery(html,".sidebar a[data-action=roll-initiative]")?.addEventListener("mouseenter",()=>{this.toggleInitiativeLink()});const heroPointsPips=htmlQuery(html,"[data-action=adjust-hero-points]");heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(this.actor.heroPoints.value+1,this.actor.heroPoints.max);await this.actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(this.actor.heroPoints.value-1,0);await this.actor.update({"system.resources.heroPoints.value":newValue})}),$html.find(".adjust-item-stat").on("click contextmenu",event2=>this.#onClickAdjustItemStat(event2)),$html.find(".adjust-item-stat-select").on("change",event2=>this.#onChangeAdjustItemStat(event2));const mainPanel=htmlQuery(html,".tab[data-tab=character]");if(mainPanel&&this.isEditable){new ContextMenu(mainPanel,".detail-item-control",[{name:"PF2E.EditItemTitle",icon:fontAwesomeIcon("edit").outerHTML,callback:$target=>{const itemId=htmlClosest($target[0],"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId,{strict:!0}).sheet.render(!0,{focus:!0})}},{name:"PF2E.DeleteItemTitle",icon:fontAwesomeIcon("trash").outerHTML,callback:$target=>{const itemId=htmlClosest($target[0],"[data-item-id]")?.dataset.itemId,item=this.actor.items.get(itemId,{strict:!0});this.deleteItem(item)}}],{eventName:"click"});for(const link of htmlQueryAll(html,".crb-tag-selector"))link.addEventListener("click",()=>this.openTagSelector(link,{allowCustom:!1}));htmlQuery(mainPanel,"button[data-action=edit-attribute-boosts]")?.addEventListener("click",()=>{(Object.values(this.actor.apps).find(a=>a instanceof AttributeBuilder)??new AttributeBuilder(this.actor)).render(!0)});for(const link of htmlQueryAll(mainPanel,"a[data-action=apex-attribute]"))link.addEventListener("click",()=>{if(game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this.actor))return;const attribute=htmlClosest(link,"[data-attribute]")?.dataset.attribute;if(setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)){const apexItems=this.actor.itemTypes.equipment.filter(e=>e.system.apex),selection=apexItems.find(e=>e.isInvested&&e.system.apex?.attribute===attribute);this.actor.updateEmbeddedDocuments("Item",apexItems.map(e=>({_id:e.id,"system.apex.selected":e===selection})))}})}const actionsPanel=htmlQuery(html,".tab[data-tab=actions]");htmlQuery(actionsPanel,".toggle-unready-strikes")?.addEventListener("click",()=>{this.actor.setFlag("pf2e","showUnreadyStrikes",!this.actor.flags.pf2e.showUnreadyStrikes)});for(const strikeElem of htmlQueryAll(actionsPanel,"ol[data-strikes] > li")){const versatileToggleButtons=htmlQueryAll(strikeElem,"button[data-action=toggle-versatile]");for(const button of versatileToggleButtons)button.addEventListener("click",()=>{const weapon=this.getStrikeFromDOM(button)?.item,baseType=weapon?.system.damage.damageType??null,selection=button.classList.contains("selected")||button.value===baseType?null:button.value,selectionIsValid=objectHasKey(CONFIG.PF2E.damageTypes,selection)||selection===null;weapon&&selectionIsValid&&toggleWeaponTrait({trait:"versatile",weapon,selection})});const auxActionButtons=htmlQueryAll(strikeElem,"button[data-action=auxiliary-action]");for(const button of auxActionButtons){const modularSelect=htmlQuery(button,"select");button.addEventListener("click",()=>{const auxiliaryActionIndex=Number(button.dataset.auxiliaryActionIndex??NaN),strike=this.getStrikeFromDOM(button),selection=modularSelect?.value??null;strike?.auxiliaryActions?.at(auxiliaryActionIndex)?.execute({selection})});for(const eventType of["change","click","dragenter","input"])modularSelect?.addEventListener(eventType,event2=>{event2.stopImmediatePropagation()})}const ammoSelect=htmlQuery(strikeElem,"select[data-action=link-ammo]");ammoSelect?.addEventListener("change",event2=>{event2.stopPropagation();const weapon=this.getStrikeFromDOM(ammoSelect)?.item,ammo=this.actor.items.get(ammoSelect.value);weapon?.update({system:{selectedAmmoId:ammo?.id??null}})})}for(const customModifierEl of htmlQueryAll(html,".modifiers-tooltip")){const stat=customModifierEl.dataset.stat;if(!stat)continue;for(const removeButton of htmlQueryAll(customModifierEl,"[data-action=remove-modifier]")){const slug=removeButton.dataset.slug??"";removeButton.addEventListener("click",()=>{this.actor.removeCustomModifier(stat,slug)})}const modifierValueEl=htmlQuery(customModifierEl,".add-modifier input[type=number]");htmlQuery(customModifierEl,"[data-action=increment]")?.addEventListener("click",()=>{modifierValueEl?.stepUp()}),htmlQuery(customModifierEl,"[data-action=decrement]")?.addEventListener("click",()=>{modifierValueEl?.stepDown()}),htmlQuery(customModifierEl,"[data-action=create-custom-modifier]")?.addEventListener("click",()=>{const modifier=modifierValueEl?.valueAsNumber||1,type=htmlQuery(customModifierEl,".add-modifier-type")?.value??"",label=htmlQuery(customModifierEl,".add-modifier-name")?.value?.trim()??game.i18n.localize(`PF2E.ModifierType.${type}`);if(!setHasElement(MODIFIER_TYPES,type)){ui.notifications.error("Type is required.");return}this.actor.addCustomModifier(stat,label,modifier,type)})}this.#activateBlastListeners(actionsPanel),$html.find(".hover").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120});const castingPanel=htmlQuery(html,".tab[data-tab=spellcasting]"),focusPips=htmlQueryAll(castingPanel,".focus-pool");if(focusPips.length>0){const listener=__name2(event2=>{const change=event2.type==="click"?1:-1,points=this.actor.system.resources.focus.value+change;this.actor.update({"system.resources.focus.value":points})},"listener");for(const pips of focusPips)pips.addEventListener("click",listener),pips.addEventListener("contextmenu",listener)}for(const select of htmlQueryAll(html,"select[data-action=update-spellcasting-rank]"))select.addEventListener("change",()=>{const newRank=Number(select.value);if(![1,2,3,4].includes(newRank))throw ErrorPF2e("Unexpected rank received while changing proficiency");const autoChanges=(this.actor.system.autoChanges["system.proficiencies.spellcasting.rank"]??[]).filter(ac=>typeof ac.value=="number"&&ac.mode==="upgrade"),highestUpgrade=sortBy(autoChanges,ac=>Number(ac.value)).at(-1);if(typeof highestUpgrade?.value=="number"&&highestUpgrade.value>newRank){const rank=CONFIG.PF2E.proficiencyLevels[highestUpgrade.value];ui.notifications.warn(game.i18n.format("PF2E.Actor.Character.Proficiency.HigherUpgrade",{ability:highestUpgrade.source,rank:game.i18n.format(rank)})),this.render()}else{const entries=this.actor.itemTypes.spellcastingEntry.filter(e=>!e.system.proficiency.slug);this.actor.updateEmbeddedDocuments("Item",entries.map(e=>({_id:e.id,"system.proficiency.value":newRank})))}});const craftingTab=htmlQuery(html,".tab[data-tab=crafting]");for(const element of htmlQueryAll(craftingTab,"li.formula-item")){const quantity=htmlQuery(element,"input[data-action=enter-quantity]");quantity?.addEventListener("change",async()=>{const itemUUID=element.dataset.itemId??"",formula=this.#knownFormulas[itemUUID],minBatchSize=formula.minimumBatchSize,newValue=Number(quantity.value)||minBatchSize;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}this.#formulaQuantities[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});for(const button of htmlQueryAll(element,"[data-action=increase-quantity], [data-action=decrease-quantity]"))button.addEventListener("click",async()=>{if(!quantity)return;const itemUUID=element.dataset.itemId??"",formula=this.#knownFormulas[itemUUID],minBatchSize=formula.minimumBatchSize,step2=button.dataset.action==="increase-quantity"?minBatchSize:-minBatchSize,newValue=(Number(quantity.value)||step2)+step2;if(newValue<1)return;const entrySelector=htmlClosest(element,"li.crafting-entry")?.dataset.entrySelector;if(entrySelector){const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const index=element.dataset.itemIndex;await craftingEntry.setFormulaQuantity(Number(index),itemUUID??"",newValue);return}this.#formulaQuantities[formula.uuid]=Math.max(newValue,minBatchSize),this.render()});const craftButton=htmlQuery(element,"a[data-action=craft-item]");craftButton?.addEventListener("click",async event2=>{const{itemUuid,free,prepared}=craftButton.dataset,itemQuantity=Number(quantity?.value)||1,formula=this.#knownFormulas[itemUuid??""];if(!formula)return;if(prepared==="true"){if(element.dataset.expendedState==="true"){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.FormulaExpended"));return}const index=element.dataset.itemIndex,entrySelector=htmlClosest(craftButton,"li.crafting-entry")?.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUuid)}if(this.actor.flags.pf2e.quickAlchemy){const reagentValue=this.actor.system.resources.crafting.infusedReagents.value-1;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}return await this.actor.update({"system.resources.crafting.infusedReagents.value":reagentValue},{render:!1}),craftItem(formula.item,1,this.actor,!0)}if(this.actor.flags.pf2e.freeCrafting){const itemId=itemUuid?.split(".").pop()??"";return isSpellConsumable(itemId)&&formula.item.isOfType("consumable")?craftSpellConsumable(formula.item,itemQuantity,this.actor):craftItem(formula.item,itemQuantity,this.actor)}const difficultyClass={value:formula.dc,visible:!0,scope:"check"};craft({difficultyClass,item:formula.item,quantity:itemQuantity,actors:this.actor,event:event2,free:free==="true"})}),htmlQuery(element,"a.formula-delete")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId;if(!itemUuid)return;const name2=this.#knownFormulas[itemUuid]?.name,content=`<p class="note">${game.i18n.format("PF2E.CraftingTab.RemoveFormulaDialogQuestion",{name:name2})}</p>`,title=game.i18n.localize("PF2E.CraftingTab.RemoveFormulaDialogTitle");if(await Dialog.confirm({title,content})){const actorFormulas=this.actor.toObject().system.crafting?.formulas??[];actorFormulas.findSplice(f=>f.uuid===itemUuid),this.actor.update({"system.crafting.formulas":actorFormulas})}}),htmlQuery(element,"a.formula-unprepare")?.addEventListener("click",async()=>{const itemUuid=element.dataset.itemId,index=element.dataset.itemIndex,entrySelector=element.dataset.entrySelector;if(!itemUuid||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");const name2=this.#knownFormulas[itemUuid]?.name,content=`<p class="note">${game.i18n.format("PF2E.CraftingTab.UnprepareFormulaDialogQuestion",{name:name2})}</p>`,title=game.i18n.localize("PF2E.CraftingTab.UnprepareFormulaDialogTitle");await Dialog.confirm({title,content})&&await craftingEntry.unprepareFormula(Number(index),itemUuid)})}const $craftingTab=craftingTab?$(craftingTab):$html.find(".tab[data-tab=crafting]"),$craftingOptions=$craftingTab.find(".crafting-options input:checkbox");$craftingOptions.on("click",async event2=>{const flags=[];$craftingOptions.each((_index,element)=>{element!==event2.target&&flags.push($(element).attr("flag"))}),flags.forEach(async flag=>{await this.actor.setFlag("pf2e",flag,!1)})}),$craftingTab.find("a[data-action=quick-add]").on("click",async event2=>{const{itemUuid}=event2.currentTarget.dataset,formula=(await this.actor.getCraftingFormulas()).find(f=>f.uuid===itemUuid);if(!formula)return;const entries=(await this.actor.getCraftingEntries()).filter(e=>!!e.selector&&e.checkEntryRequirements(formula,{warn:!1}));for(const entry of entries)await entry.prepareFormula(formula);entries.length===0&&ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.NoEligibleEntry"))});const $formulas=$craftingTab.find(".craftingEntry-list");$formulas.find(".toggle-formula-expended").on("click",async event2=>{const $target=$(event2.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),index=$target.closest("li.formula-item").attr("data-item-index"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!index||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleFormulaExpended(Number(index),itemUUID)}),$formulas.find(".toggle-signature-item").on("click",async event2=>{const $target=$(event2.currentTarget),itemUUID=$target.closest("li.formula-item").attr("data-item-id"),entrySelector=$target.closest("li.crafting-entry").attr("data-entry-selector");if(!itemUUID||!entrySelector)return;const craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)throw ErrorPF2e("Crafting entry not found");await craftingEntry.toggleSignatureItem(itemUUID)}),$formulas.find(".infused-reagents").on("change",event2=>{const change=Number($(event2.target).val()),infusedReagents=this.actor.system.resources.crafting.infusedReagents,value=Math.clamped(change,0,infusedReagents?.max??0);this.actor.update({"system.resources.crafting.infusedReagents.value":value})}),$formulas.find(".daily-crafting").on("click",async()=>await this.actor.performDailyCrafting());for(const spellcastingCollectionEl of htmlQueryAll(castingPanel,".spellcasting-entry[data-item-id]")){const entry=this.actor.spellcasting.get(spellcastingCollectionEl.dataset.itemId??"");htmlQuery(spellcastingCollectionEl,"[data-action=spell-attack]")?.addEventListener("click",event2=>{entry?.statistic?.check.roll(eventToRollParams(event2,{type:"check"}))})}}#activateNavListeners(html){const sheetNavigation=htmlQuery(html,"nav.sheet-navigation");if(!sheetNavigation)return;const navTitleArea=htmlQuery(sheetNavigation,":scope > .panel-title"),activeTab=htmlQuery(sheetNavigation,"a[data-tab].active");if(!(navTitleArea&&activeTab))throw ErrorPF2e("Sheet navigation not found");navTitleArea.innerText=game.i18n.localize(activeTab.dataset.tooltip??"");const manageTabsAnchor=htmlQuery(sheetNavigation,":scope > a[data-action=manage-tabs]");manageTabsAnchor&&PCSheetTabManager.initialize(this.actor,manageTabsAnchor),sheetNavigation.addEventListener("click",event2=>{const anchor=htmlClosest(event2.target,"a[data-tab]");anchor&&(navTitleArea.innerText=game.i18n.localize(anchor.dataset.tooltip??""))})}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers.rest=event2=>{game.pf2e.actions.restForTheNight({event:event2,actors:this.actor})},handlers["open-compendium"]=(_,actionTarget)=>{game.packs.get(actionTarget.dataset.compendium??"")?.render(!0)},handlers["toggle-versatile"]=button=>{if(!(button instanceof HTMLButtonElement))return;const weapon=this.getStrikeFromDOM(button)?.item,baseType=weapon?.system.damage.damageType??null,selection=button.classList.contains("selected")||button.value===baseType?null:button.value,selectionIsValid=objectHasKey(CONFIG.PF2E.damageTypes,selection)||selection===null;weapon&&selectionIsValid&&toggleWeaponTrait({trait:"versatile",weapon,selection})},handlers["toggle-exploration"]=event2=>{const actionId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId;if(!actionId)return;const exploration=this.actor.system.exploration.filter(id=>this.actor.items.has(id));exploration.findSplice(id=>id===actionId)||exploration.push(actionId),this.actor.update({"system.exploration":exploration})},handlers["clear-exploration"]=()=>{this.actor.update({"system.exploration":[]})},handlers["toggle-invested"]=event2=>{const itemId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId;itemId&&this.actor.toggleInvested(itemId)},handlers["add-attack-proficiency"]=event2=>{ManageAttackProficiencies.add(this.actor,event2)},handlers["remove-attack-proficiency"]=event2=>{ManageAttackProficiencies.remove(this.actor,event2)},handlers["browse-feats"]=(_,anchor)=>{this.#onClickBrowseFeats(anchor)},handlers["toggle-bio-visibility"]=event2=>{const section=htmlClosest(event2.target,"a[data-action=toggle-bio-visibility")?.dataset.section;if(tupleHasValue(["appearance","backstory","personality","campaign"],section)){const{biography}=this.actor.system.details,path=`system.details.biography.visibility.${section}`;this.actor.update({[path]:!biography.visibility[section]})}},handlers["add-edict-anathema"]=(_,anchor)=>{anchor.style.pointerEvents="none";const field=htmlClosest(anchor,"[data-field]")?.dataset.field;if(!tupleHasValue(["edicts","anathema"],field))throw ErrorPF2e("Unexpected error adding edicts or anathema");const list=this.actor._source.system.details.biography[field];this.actor.update({[`system.details.biography.${field}`]:[...list,""]})},handlers["delete-edict-anathema"]=(_,anchor)=>{anchor.style.pointerEvents="none";const field=htmlClosest(anchor,"[data-field]")?.dataset.field,index=anchor.dataset.index??"";if(!tupleHasValue(["edicts","anathema"],field)||!/^\d+$/.test(index))throw ErrorPF2e("Unexpected error adding edicts or anathema");const list=[...this.actor._source.system.details.biography[field]];list.splice(Number(index),1),this.actor.update({[`system.details.biography.${field}`]:list})},handlers}async#getBlastData(blast,config){const damageType=config.damageTypes.find(dt=>dt.selected)?.value??"untyped",formulaFor=__name2((outcome,melee=!0)=>blast.damage({element:config.element,damageType,melee,outcome,getFormula:!0}),"formulaFor");return{...config,damageType,formula:{melee:{damage:await formulaFor("success"),critical:await formulaFor("criticalSuccess")},ranged:{damage:await formulaFor("success",!1),critical:await formulaFor("criticalSuccess",!1)}}}}#activateBlastListeners(panel){const blastList=htmlQuery(panel,"ol[data-elemental-blasts]"),{elementTraits:elementTraits2,damageTypes:damageTypes2}=CONFIG.PF2E,selectors=["roll-attack","roll-damage","set-damage-type"].map(s=>`button[data-action=${s}]`).join(",");blastList?.addEventListener("click",async event2=>{const button=htmlClosest(event2.target,selectors),blastRow=htmlClosest(button,"li");if(!(button&&blastRow))return;event2.stopPropagation();const blast=new ElementalBlast(this.actor),{element}=blastRow.dataset,damageType=button.value||blastRow.dataset.damageType;if(!objectHasKey(elementTraits2,element))throw ErrorPF2e("Unexpected error retrieve element");if(!objectHasKey(damageTypes2,damageType))throw ErrorPF2e("Unexpected error retrieving damage type");const melee=button.dataset.melee==="true";switch(button.dataset.action){case"roll-attack":{const mapIncreases=Math.clamped(Number(button.dataset.mapIncreases)||0,0,2);await blast.attack({mapIncreases,element,damageType,melee,event:event2});break}case"roll-damage":{const outcome=button.dataset.outcome==="success"?"success":"criticalSuccess";await blast.damage({element,damageType,melee,outcome,event:event2});break}case"set-damage-type":blast.setDamageType({element,damageType})}})}async#onClickBrowseFeats(element){const maxLevel=Number(element.dataset.level)||this.actor.level,checkboxesFilterCodes=(element.dataset.filter??"").split(",").filter(s=>!!s).map(s=>s.trim()),featTab=game.pf2e.compendiumBrowser.tabs.feat,filter2=await featTab.getFilterData(),level=filter2.sliders.level;level.values.max=Math.min(maxLevel,level.values.upperLimit),level.isExpanded=level.values.max!==level.values.upperLimit;const{category}=filter2.checkboxes,{traits}=filter2.multiselects;for(const filterCode of checkboxesFilterCodes){const[filterType,...rest]=filterCode.split("-"),value=rest.join("-");if(!(filterType&&value))throw ErrorPF2e(`Invalid filter value for opening the compendium browser: "${filterCode}"`);if(filterType==="category"&&value in category.options)category.isExpanded=!0,category.options[value].selected=!0,category.selected.push(value);else if(filterType==="traits"){const trait=traits.options.find(t=>t.value===value);trait&&traits.selected.push(foundry.utils.deepClone(trait))}else filterType==="conjunction"&&(value==="and"||value==="or")&&(filter2.multiselects.traits.conjunction=value)}return featTab.open(filter2)}async#onChangeAdjustItemStat(event2){const $select=$(event2.delegateTarget),propertyKey=$select.attr("data-item-property")??"",selectedValue=Number($select.val()),itemId=$select.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const newValue=(()=>{if(item.isOfType("spellcastingEntry"))return{"system.proficiency.value":()=>Math.clamped(selectedValue,0,4)}[propertyKey]?.();if(item.isOfType("lore"))return Math.clamped(selectedValue,0,4);throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue}),newValue!==foundry.utils.getProperty(item,propertyKey)&&ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.MinimumProfLevelSetByFeatures"))}async#onClickAdjustItemStat(event2){const $button=$(event2.delegateTarget),itemId=$button.closest(".item").attr("data-item-id")??"",item=this.actor.items.get(itemId);if(!item)throw ErrorPF2e("Item not found");const propertyKey=$button.attr("data-item-property")??"",change=event2.type==="click"?1:-1,newValue=(()=>{if(item.isOfType("spellcastingEntry")){const proficiencyRank=item.system.proficiency.value;return{"system.proficiency.value":()=>Math.clamped(proficiencyRank+change,0,4)}[propertyKey]?.()}else if(item.isOfType("lore")){const currentRank=item.system.proficient.value;return Math.clamped(currentRank+change,0,4)}else throw ErrorPF2e("Item not recognized")})();typeof newValue=="number"&&await item.update({[propertyKey]:newValue})}#getFeatSlotData(event2){const groupId=htmlClosest(event2.target,"[data-group-id]")?.dataset.groupId,slotId=htmlClosest(event2.target,"[data-slot-id]")?.dataset.slotId||null;return groupId?{groupId,slotId}:null}toggleInitiativeLink(link){if(link??=htmlQuery(this.element.get(0),".sidebar a[data-action=roll-initiative]"),!link)return;const alreadyRolled=typeof this.actor.combatant?.initiative=="number";if(!!(this.isEditable&&game.combat&&!alreadyRolled))link.classList.remove("disabled"),link.dataset.tooltip="COMBAT.InitiativeRoll";else{link.classList.add("disabled");const reason=this.isEditable?game.combat?alreadyRolled?"AlreadyRolled":null:"NoActiveEncounter":"";reason&&(link.dataset.tooltip=game.i18n.format(`PF2E.Encounter.${reason}`,{actor:this.actor.name}))}}async _onDropItem(event2,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event2,data);if(item.isOfType("feat")){const slotData=this.#getFeatSlotData(event2);return this.actor.feats.insertFeat(item,slotData)}return super._onDropItem(event2,data)}async _onDrop(event2){const dataString=event2.dataTransfer?.getData("text/plain"),dropData=(()=>{try{return JSON.parse(dataString??"")}catch{return null}})();if(dropData)if(isObject(dropData.pf2e)&&dropData.pf2e.type==="CraftingFormula"){const dropEntrySelector=typeof dropData.entrySelector=="string"?dropData.entrySelector:null;if(!dropEntrySelector){const containerEl=htmlClosest(event2.target,".item-container");if(containerEl?.dataset.containerType==="craftingEntry"){const entrySelector=containerEl.dataset.entrySelector??"",craftingEntry=await this.actor.getCraftingEntry(entrySelector);if(!craftingEntry)return;const craftingFormulas=await this.actor.getCraftingFormulas(),uuid2=dropData.pf2e.itemUuid,formula=craftingFormulas.find(f=>f.uuid===uuid2);formula&&craftingEntry.prepareFormula(formula);return}}const uuid=dropData.pf2e.itemUuid;if(typeof uuid=="string"){const formula=this.#knownFormulas[uuid];if(formula){const targetUuid=htmlClosest(event2.target,"li.formula-item")?.dataset.itemId??"";return this.#sortFormulas(formula,targetUuid,dropEntrySelector)}}}else return super._onDrop(event2)}async#sortFormulas(sourceFormula,targetUuid,entrySelector){if(!UUIDUtils.isItemUUID(targetUuid)||sourceFormula.uuid===targetUuid)return;const sourceLevel=sourceFormula.level,targetLevel=this.#knownFormulas[targetUuid].level;if(!entrySelector&&sourceLevel!==targetLevel)return;const performSort=__name2(async(formulas2,source2,target2,siblings)=>{const results=SortingHelpers.performIntegerSort(source2,{target:target2,siblings});if(results.length){for(const result of results){const formula=formulas2.find(f=>f===result.target);formula&&(formula.sort=result.update.sort)}entrySelector?await(await this.actor.getCraftingEntry(entrySelector))?.updateFormulas(formulas2):await this.actor.update({"system.crafting.formulas":formulas2})}},"performSort");if(entrySelector){const entry=await this.actor.getCraftingEntry(entrySelector);if(!entry)throw ErrorPF2e(`Crafting entry "${entrySelector}" doesn't exist!`);const formulas2=foundry.utils.deepClone(entry.preparedFormulaData),source2=formulas2.find(f=>f.itemUUID===sourceFormula.uuid),target2=formulas2.find(f=>f.itemUUID===targetUuid);if(source2&&target2){const siblings=formulas2.filter(f=>f.itemUUID!==source2.itemUUID);return performSort(formulas2,source2,target2,siblings)}}const formulas=this.actor.toObject().system.crafting?.formulas??[],source=formulas.find(f=>f.uuid===sourceFormula.uuid),target=formulas.find(f=>f.uuid===targetUuid);if(source&&target){const siblings=formulas.filter(f=>f.uuid!==source.uuid);return performSort(formulas,source,target,siblings)}}async _onSortItem(event2,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("feat")){const featSlot=this.#getFeatSlotData(event2);if(featSlot){const group=this.actor.feats.get(featSlot.groupId)??null,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return this.actor.feats.insertFeat(item,featSlot)}}return super._onSortItem(event2,itemSource)}_updateObject(event2,formData){for(const field of["edicts","anathema"]){const keys2=Array.fromRange(this.actor._source.system.details.biography[field].length).map(i=>`system.details.biography.${field}.${i}`),lines=keys2.map(k=>String(formData[k]??"").trim());for(const key of keys2)delete formData[key];lines.length>0&&(formData[`system.details.biography.${field}`]=lines)}return super._updateObject(event2,formData)}}class AttackPopout extends CharacterSheetPF2e{static{__name(this,"AttackPopout")}static{__name2(this,"AttackPopout")}type="strike";#strikeItemId="";#strikeSlug="";#strike;#elementTrait;#blasts=[];get template(){return"systems/pf2e/templates/actors/character/attack-popout.hbs"}get id(){const id=super.id;return this.type==="strike"?`${id}-strike-${this.#strikeItemId}-${this.#strikeSlug}`:`${id}-blast-${this.#elementTrait}`}static get defaultOptions(){return{...super.defaultOptions,submitOnChange:!1,submitOnClose:!1,width:480,height:"auto",resizable:!1}}get label(){return this.type==="blast"?this.#blasts.at(0)?.label??null:this.#strike?.label??null}constructor(object,options){if(super(object,options),!options.type)throw ErrorPF2e('AttackPopout is missing mandatory "type" option.');if(options.type==="blast"){if(!options.elementTrait)throw ErrorPF2e('AttackPopout of type "blast" is missing mandatory "elementalTrait" option.');this.#elementTrait=options.elementTrait}else{if(!options.strikeSlug)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeSlug" option.');if(!options.strikeItemId)throw ErrorPF2e('AttackPopout of type "strike" is missing mandatory "strikeItemId" option.');this.#strikeSlug=options.strikeSlug,this.#strikeItemId=options.strikeItemId}this.type=options.type}async getData(options){const base=await super.getData(options);return this.type==="blast"?(base.elementalBlasts=this.#blasts=base.elementalBlasts.filter(b=>b.element===this.#elementTrait),base.data.actions=[],base.toggles=base.toggles.filter(t=>t.domain==="elemental-blast")):(base.elementalBlasts=[],this.#strikeSlug&&this.#strikeItemId&&(this.#strike=base.data.actions.find(a=>a.item.id===this.#strikeItemId&&a.slug===this.#strikeSlug))),{...base,strike:this.#strike,strikeIndex:base.data.actions.findIndex(a=>a===this.#strike),popoutType:this.type}}activateListeners($html){super.activateListeners($html);const html=$html[0],{label}=this;if(label){const title=htmlQuery(htmlClosest(html,"div.window-app"),"h4.window-title");title&&(title.innerHTML=game.i18n.localize(label))}}_getHeaderButtons(){return super._getHeaderButtons().filter(b=>b.label==="Close")}}class MacroPF2e extends Macro{static{__name(this,"MacroPF2e")}static{__name2(this,"MacroPF2e")}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}}async function rollItemMacro(itemId){const speaker=ChatMessage.getSpeaker(),item=(canvas.tokens.get(speaker.token??"")?.actor??game.actors.get(speaker.actor??""))?.items?.get(itemId);if(!item){ui.notifications.warn(`Your controlled Actor does not have an item with ID ${itemId}`);return}return item.isOfType("action","feat")&&item.system.selfEffect?createSelfEffectMessage(item):item.toChat()}__name(rollItemMacro,"rollItemMacro"),__name2(rollItemMacro,"rollItemMacro");async function createActionMacro({actorUUID,actionIndex,elementTrait,slot}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc"))return;const data=(()=>{if(actor.isOfType("character")&&objectHasKey(CONFIG.PF2E.elementTraits,elementTrait)){const config=new ElementalBlast(actor).configs.find(c=>c.element===elementTrait);return config?{name:game.i18n.localize(config.label),command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "blast", elementTrait: "${elementTrait}" })`,img:config.img}:null}else if(actionIndex!==void 0){const action2=actor.system.actions[actionIndex];return action2?{name:`${game.i18n.localize("PF2E.WeaponStrikeLabel")}: ${action2.label}`,command:`game.pf2e.rollActionMacro({ actorUUID: "${actorUUID}", type: "strike", itemId: "${action2.item.id}", slug: "${action2.slug}" })`,img:action2.item.img}:null}return null})();if(!data)return;const actionMacro=game.macros.find(macro=>macro.name===data.name&¯o.command===data.command)??await MacroPF2e.create({command:data.command,name:data.name,type:"script",img:data.img,flags:{pf2e:{actionMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(actionMacro??null,slot)}__name(createActionMacro,"createActionMacro"),__name2(createActionMacro,"createActionMacro");async function rollActionMacro({actorUUID,itemId,elementTrait,slug,type}){const actor=resolveMacroActor(actorUUID);if(!actor?.isOfType("character","npc")){ui.notifications.error("PF2E.MacroActionNoActorError",{localize:!0});return}const strikes=actor.system.actions,strike=strikes.find(s=>s.item.id===itemId&&s.slug===slug)??strikes.find(s=>s.slug===slug);if(actor.isOfType("character")){const closedExisting=__name2(partialId=>{const appId=`AttackPopout-Actor-${actor.id}-${partialId}`,existing=Object.values(actor.apps).find(a=>a?.id===appId);return existing?(existing.close({force:!0}),!0):!1},"closedExisting");switch(type){case"blast":{if(closedExisting(`blast-${elementTrait}`))return;if(!actor.itemTypes.effect.find(e=>e.slug==="effect-kinetic-aura")){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,elementTrait}).render(!0);return}case"strike":{if(closedExisting(`strike-${itemId}-${slug}`))return;if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}new AttackPopout(actor,{type,strikeItemId:itemId,strikeSlug:slug}).render(!0);return}}}if(!strike){ui.notifications.error("PF2E.MacroActionNoActionError",{localize:!0});return}const meleeOrRanged=strike.item.isMelee?"melee":"ranged",identifier=`${strike.item.id}.${strike.slug}.${meleeOrRanged}`,description=await TextEditor.enrichHTML(game.i18n.localize(strike.description),{async:!0}),templateData={actor,strike,identifier,description},content=await renderTemplate("systems/pf2e/templates/chat/strike-card.hbs",templateData),token=actor.token??actor.getActiveTokens(!0,!0).shift()??null,chatData={speaker:ChatMessagePF2e.getSpeaker({actor,token}),content,type:CONST.CHAT_MESSAGE_TYPES.OTHER},rollMode=game.settings.get("core","rollMode");return["gmroll","blindroll"].includes(rollMode)&&(chatData.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),rollMode==="blindroll"&&(chatData.blind=!0),ChatMessagePF2e.create(chatData)}__name(rollActionMacro,"rollActionMacro"),__name2(rollActionMacro,"rollActionMacro");async function createSkillMacro(skill,skillName,actorId,slot){const dictName=SKILL_DICTIONARY[skill]??skill,command=`
|
|
const a = game.actors.get("${actorId}");
|
|
if (a) {
|
|
const opts = a.getRollOptions(["all", "skill-check", "${dictName}"]);
|
|
a.system.skills["${skill}"]?.roll(event, opts);
|
|
} else {
|
|
ui.notifications.error(game.i18n.localize("PF2E.MacroActionNoActorError"));
|
|
}`,macroName=game.i18n.format("PF2E.SkillCheckWithName",{skillName}),skillMacro=game.macros.find(macro=>macro.name===macroName&¯o.command===command)??await MacroPF2e.create({command,name:macroName,type:"script",img:"icons/svg/d20-grey.svg",flags:{pf2e:{skillMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(skillMacro??null,slot)}__name(createSkillMacro,"createSkillMacro"),__name2(createSkillMacro,"createSkillMacro");async function createToggleEffectMacro(effect,slot){const uuid=effect.uuid.startsWith("Actor")?effect.sourceId:effect.uuid;if(!uuid){ui.notifications.error("PF2E.ErrorMessage.CantCreateEffectMacro",{localize:!0});return}const command=`const actors = game.user.getActiveTokens().flatMap((t) => t.actor ?? []);
|
|
if (actors.length === 0) {
|
|
return ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected", { localize: true });
|
|
}
|
|
|
|
const ITEM_UUID = "${uuid}"; // ${effect.name}
|
|
const item = await fromUuid(ITEM_UUID);
|
|
if (item?.type === "condition") {
|
|
for (const actor of actors) {
|
|
actor.toggleCondition(item.slug);
|
|
}
|
|
} else if (item?.type === "effect") {
|
|
const source = item.toObject();
|
|
source.flags = mergeObject(source.flags ?? {}, { core: { sourceId: ITEM_UUID } });
|
|
|
|
for (const actor of actors) {
|
|
const existing = actor.itemTypes.effect.find((e) => e.flags.core?.sourceId === ITEM_UUID);
|
|
if (existing) {
|
|
await existing.delete();
|
|
} else {
|
|
await actor.createEmbeddedDocuments("Item", [source]);
|
|
}
|
|
}
|
|
} else {
|
|
ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.ItemNotFoundByUUID", { uuid: ITEM_UUID }));
|
|
}
|
|
`,toggleMacro=game.macros.contents.find(macro=>macro.name===effect.name&¯o.command===command)??await MacroPF2e.create({command,name:effect.name,type:"script",img:effect.img},{renderSheet:!1});game.user.assignHotbarMacro(toggleMacro??null,slot)}__name(createToggleEffectMacro,"createToggleEffectMacro"),__name2(createToggleEffectMacro,"createToggleEffectMacro");function resolveMacroActor(uuid){if(uuid){const actor=fromUuidSync(uuid);return actor instanceof ActorPF2e?actor:null}const speaker=ChatMessage.getSpeaker();return canvas.tokens.get(speaker.token??"")?.actor??game.actors.get(speaker.actor??"")??null}__name(resolveMacroActor,"resolveMacroActor"),__name2(resolveMacroActor,"resolveMacroActor");async function perceptionForSelected(event2){const actors=canvas.tokens.controlled.flatMap(t=>t.actor??[]).filter(a=>!!a.isOfType("creature"));if(actors.length===0){ui.notifications.error("You must select at least one PC/NPC token.");return}const argsFromEvent=eventToRollParams(event2,{type:"check"});for(const actor of actors)await actor.perception.roll({...argsFromEvent,traits:["secret"]})}__name(perceptionForSelected,"perceptionForSelected"),__name2(perceptionForSelected,"perceptionForSelected");const ITEM_UUID="Compendium.pf2e.equipment-effects.Item.2YgXoHvJfrDHucMr",TEMPLATES={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"};async function raiseAShield(options){const localize=localizer("PF2E.Actions.RaiseAShield"),actors=Array.isArray(options.actors)?options.actors:[options.actors],actor=actors[0];if(actors.length>1||!actor?.isOfType("character","npc")){ui.notifications.error(localize("BadArgs"));return}const existingEffect=actor.itemTypes.effect.find(e=>e.flags.core?.sourceId===ITEM_UUID);if(existingEffect){await existingEffect.delete();return}if(actor.isOfType("character")){const{heldShield}=actor;return actor.system.actions.find(a=>a.ready&&!!a.item.shield&&a.item.shield===heldShield)?.auxiliaryActions.find(aux=>aux.action==="raise-a-shield")?.execute()}const shield=actor.heldShield,speaker=ChatMessagePF2e.getSpeaker({actor}),isSuccess=await(async()=>{if(shield?.isDestroyed)return ui.notifications.warn(localize("ShieldIsDestroyed",{actor:speaker.alias,shield:shield.name})),!1;if(shield?.isBroken===!1){const effect=await fromUuid(ITEM_UUID);if(!(effect instanceof EffectPF2e))throw ErrorPF2e("Raise a Shield effect not found");return await actor.createEmbeddedDocuments("Item",[effect.toObject()]),!0}else return shield?.isBroken?(ui.notifications.warn(localize("ShieldIsBroken",{actor:speaker.alias,shield:shield.name})),!1):(ui.notifications.warn(localize("NoShieldEquipped",{actor:speaker.alias})),!1)})();if(shield&&isSuccess){const combatActor=game.combat?.started&&game.combat.combatant?.actor||null,[actionType,glyph]=combatActor&&combatActor!==actor?["Reaction","R"]:["SingleAction","1"],content=await renderTemplate(TEMPLATES.content,{imgPath:shield.img,message:localize("Content",{actor:speaker.alias,shield:game.i18n.localize("TYPES.Item.shield")})}),flavor=await renderTemplate(TEMPLATES.flavor,{action:{title:localize(`${actionType}Title`),glyph}});await ChatMessagePF2e.create({type:CONST.CHAT_MESSAGE_TYPES.EMOTE,speaker,flavor,content})}}__name(raiseAShield,"raiseAShield"),__name2(raiseAShield,"raiseAShield");async function restForTheNight(options){const actors=Array.isArray(options.actors)?options.actors:[options.actors],characters=actors.filter(a=>a?.type==="character");if(actors.length===0)return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.NoPCTokenSelected")),[];const localize=localizer("PF2E.Action.RestForTheNight"),promptMessage=(()=>{const element=document.createElement("p");return element.innerText=localize("Prompt"),element.outerHTML})();if(!options.skipDialog&&!await Dialog.confirm({title:localize("Label"),content:promptMessage,defaultYes:!0}))return[];const messages=[];for(const actor of characters){const actorUpdates={attributes:{hp:{value:actor._source.system.attributes.hp.value}},resources:{}},itemUpdates=[],statements=[],{abilities:abilities2,attributes,hitPoints,level}=actor,conModifier=abilities2.con.mod,maxRestored=Math.max(conModifier,1)*level*hitPoints.recoveryMultiplier+hitPoints.recoveryAddend,hpLost=attributes.hp.max-attributes.hp.value,hpRestored=hpLost>=maxRestored?maxRestored:hpLost;if(hpRestored>0){const singularOrPlural=hpRestored===1?"PF2E.Action.RestForTheNight.Message.HitPointsSingle":"PF2E.Action.RestForTheNight.Message.HitPoints";actorUpdates.attributes.hp={value:attributes.hp.value+=hpRestored},statements.push(game.i18n.format(singularOrPlural,{hitPoints:hpRestored}))}const RECOVERABLE_CONDITIONS=["doomed","drained","fatigued","wounded"],conditionChanges={doomed:null,drained:null,fatigued:null,wounded:null};actor.hasCondition("fatigued")&&(await actor.decreaseCondition("fatigued"),conditionChanges.fatigued="removed");for(const slug of["doomed","drained"]){const condition=actor.getCondition(slug);if(!condition)continue;const newValue=(condition.value??1)-1;await actor.decreaseCondition(slug),conditionChanges[slug]=newValue===0?"removed":"reduced"}actor.hasCondition("wounded")&&attributes.hp.value===attributes.hp.max&&(await actor.decreaseCondition("wounded",{forceRemove:!0}),conditionChanges.wounded="removed");const wands=actor.itemTypes.consumable.filter(i=>i.category==="wand"&&i.uses.value<i.uses.max);itemUpdates.push(...wands.map(wand=>({_id:wand.id,"system.uses.value":wand.uses.max})));const wandRecharged=itemUpdates.length>0,resources=actor.system.resources,reagents=resources.crafting.infusedReagents;reagents&&reagents.value<reagents.max&&(actorUpdates.resources.crafting={infusedReagents:{value:reagents.max}},statements.push(localize("Message.InfusedReagents")));const spellcastingRecharge=actor.spellcasting.recharge();itemUpdates.push(...spellcastingRecharge.itemUpdates),spellcastingRecharge.actorUpdates?.["system.resources.focus.value"]&&(actorUpdates.resources.focus={value:spellcastingRecharge.actorUpdates?.["system.resources.focus.value"]});const withFrequency=[...actor.itemTypes.action,...actor.itemTypes.feat].filter(a=>a.frequency&&(tupleHasValue(["turn","round","day"],a.frequency.per)||Duration.fromISO(a.frequency.per)<=Duration.fromISO("PT8H"))&&a.frequency.value<a.frequency.max);if(withFrequency.length>0&&(statements.push(localize("Message.Frequencies")),itemUpdates.push(...withFrequency.map(a=>({_id:a.id,"system.frequency.value":a.frequency?.max??0})))),game.pf2e.settings.variants.stamina){const stamina=attributes.hp.sp??{value:0,max:0},resolve=resources.resolve??{value:0,max:0};stamina.value<stamina.max&&(actorUpdates.attributes.hp.sp={value:stamina.max},statements.push(localize("Message.StaminaPoints"))),resolve.value<resolve.max&&(actorUpdates.resources.resolve={value:resolve.max},statements.push(localize("Message.Resolve")))}const temporaryItems=actor.inventory.filter(i=>i.isTemporary).map(i=>i.id),hasActorUpdates=Object.keys({...actorUpdates.attributes,...actorUpdates.resources}).length>0,hasItemUpdates=itemUpdates.length>0,removeTempItems=temporaryItems.length>0;hasActorUpdates&&await actor.update({system:actorUpdates},{render:!1}),hasItemUpdates&&await actor.updateEmbeddedDocuments("Item",itemUpdates,{render:!1}),removeTempItems&&(await actor.deleteEmbeddedDocuments("Item",temporaryItems,{render:!1}),statements.push(localize("Message.TemporaryItems"))),spellcastingRecharge.actorUpdates&&statements.push(localize("Message.FocusPoints")),spellcastingRecharge.itemUpdates.length>0&&statements.push(localize("Message.SpellSlots")),wandRecharged&&statements.push(localize("Message.WandsCharges"));const reducedConditions=RECOVERABLE_CONDITIONS.filter(c=>conditionChanges[c]==="reduced");for(const slug of reducedConditions){const{name:name2}=game.pf2e.ConditionManager.getCondition(slug);statements.push(localize("Message.ConditionReduced",{condition:name2}))}const removedConditions=RECOVERABLE_CONDITIONS.filter(c=>conditionChanges[c]==="removed");for(const slug of removedConditions){const{name:name2}=game.pf2e.ConditionManager.getCondition(slug);statements.push(localize("Message.ConditionRemoved",{condition:name2}))}const actorAwakens=localize("Message.Awakens",{actor:actor.name}),recoveryList=document.createElement("ul");recoveryList.append(...statements.map(statement=>{const listItem=document.createElement("li");return listItem.innerText=statement,listItem}));const content=[actorAwakens,recoveryList.outerHTML].join(`
|
|
`);messages.push({user:game.user.id,content,speaker:{alias:actor.name}}),await actor.sheet.render(),Hooks.callAll("pf2e.restForTheNight",actor)}return ChatMessagePF2e.createDocuments(messages)}__name(restForTheNight,"restForTheNight"),__name2(restForTheNight,"restForTheNight");async function stealthForSelected(event2){const actors=canvas.tokens.controlled.flatMap(t=>t.actor??[]).filter(a=>!!a.isOfType("creature"));if(actors.length===0){ui.notifications.error("You must select at least one PC/NPC token.");return}const argsFromEvent=eventToRollParams(event2,{type:"check"});for(const actor of actors)await actor.skills.stealth.roll({...argsFromEvent,traits:["secret"]})}__name(stealthForSelected,"stealthForSelected"),__name2(stealthForSelected,"stealthForSelected");function steelYourResolve(options){const localize=localizer("PF2E.Actions.SteelYourResolve"),actors=Array.isArray(options.actors)?options.actors:[options.actors],actor=actors[0];if(actors.length>1||!(actor instanceof CharacterPF2e)){ui.notifications.error(localize("BadArgs"));return}const toChat=__name2((alias,content)=>{ChatMessage.create({user:game.user.id,content,speaker:{alias}})},"toChat");if(!game.pf2e.settings.variants.stamina){ui.notifications.error(localize("StaminaNotEnabled"));return}Dialog.confirm({title:localize("Title"),content:localize("Content"),yes:()=>{const sp=actor.system.attributes.hp.sp??{value:0,max:0},resolve=actor.system.resources.resolve??{value:0,max:0},spRatio=`${sp.value}/${sp.max}`,recoverStamina=localize("RecoverStamina",{name:actor.name,ratio:spRatio}),noStamina=localize("NoStamina",{name:actor.name});if(resolve.value>0){toChat(actor.name,recoverStamina);const newSP=sp.value+Math.floor(sp.max/2);actor.update({"system.attributes.hp.sp.value":Math.min(newSP,sp.max),"system.resources.resolve.value":resolve.value-1})}else toChat(actor.name,noStamina)},defaultYes:!0})}__name(steelYourResolve,"steelYourResolve"),__name2(steelYourResolve,"steelYourResolve");function takeABreather(){let applyChanges=!1;const pcs=uniq(compact(game.user.getActiveTokens().map(t=>t.actor))).filter(a=>a.isOfType("character"));if(game.pf2e.settings.variants.stamina){if(pcs.length===0){ui.notifications.error("PF2E.ErrorMessage.NoPCTokenSelected",{localize:!0});return}}else return;new Dialog({title:"Take a Breather",content:"<div>Rest for 10 minutes, spend a resolve point, and regain stamina?</div>",buttons:{yes:{icon:fontAwesomeIcon("check").outerHTML,label:"Take a Breather",callback:()=>{applyChanges=!0}},no:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"}},default:"yes",close:()=>{if(applyChanges)for(const actor of pcs){const token=actor.getActiveTokens(!0,!0).shift(),name2=token?.name??actor.name,sp=actor.system.attributes.hp.sp,resolve=actor.system.resources.resolve;if(!(sp&&resolve))continue;const speaker=ChatMessagePF2e.getSpeaker({token,actor});resolve.value>0?(actor.update({"system.attributes.hp.sp.value":sp.max,"system.resources.resolve.value":resolve.value-1}),ChatMessagePF2e.create({speaker,content:`${name2} has ${sp.value}/${sp.max} SP and spends a resolve point, taking a 10 minute breather. Stamina refreshed.`})):ChatMessagePF2e.create({speaker,content:`${name2} is tired and needs to go to bed! No resolve points remaining.`})}}}).render(!0)}__name(takeABreather,"takeABreather"),__name2(takeABreather,"takeABreather");var ExplorationActivities=(ExplorationActivities2=>(ExplorationActivities2[ExplorationActivities2.NONE=0]="NONE",ExplorationActivities2[ExplorationActivities2.HALF_SPEED=1]="HALF_SPEED",ExplorationActivities2[ExplorationActivities2.AVOID_NOTICE=2]="AVOID_NOTICE",ExplorationActivities2[ExplorationActivities2.DEFEND=3]="DEFEND",ExplorationActivities2[ExplorationActivities2.DETECT_MAGIC=4]="DETECT_MAGIC",ExplorationActivities2[ExplorationActivities2.SCOUT=5]="SCOUT",ExplorationActivities2[ExplorationActivities2.SEARCH=6]="SEARCH",ExplorationActivities2))(ExplorationActivities||{}),DetectionMode$1=(DetectionMode2=>(DetectionMode2[DetectionMode2.NONE=0]="NONE",DetectionMode2[DetectionMode2.DETECT_EVERYTHING=1]="DETECT_EVERYTHING",DetectionMode2[DetectionMode2.DETECT_BEFORE_WALKING_INTO_IT=2]="DETECT_BEFORE_WALKING_INTO_IT",DetectionMode2))(DetectionMode$1||{});function sneaksAtFullSpeed(activity,explorationOptions){return activity===2&&(explorationOptions.legendarySneak||explorationOptions.swiftSneak)}__name(sneaksAtFullSpeed,"sneaksAtFullSpeed"),__name2(sneaksAtFullSpeed,"sneaksAtFullSpeed");function defendsAtFullSpeed(activity,explorationOptions){return activity===3&&explorationOptions.practicedDefender}__name(defendsAtFullSpeed,"defendsAtFullSpeed"),__name2(defendsAtFullSpeed,"defendsAtFullSpeed");function calculateNormalizedCharacterSpeed(defaultSpeedInFeet,activity,detectionMode,explorationOptions){return Math.max(5,calculateCharacterSpeed(defaultSpeedInFeet,activity,detectionMode,explorationOptions))}__name(calculateNormalizedCharacterSpeed,"calculateNormalizedCharacterSpeed"),__name2(calculateNormalizedCharacterSpeed,"calculateNormalizedCharacterSpeed");function calculateCharacterSpeed(defaultSpeedInFeet,activity,detectionMode,explorationOptions){const halvedSpeed=defaultSpeedInFeet/2;if(sneaksAtFullSpeed(activity,explorationOptions)||defendsAtFullSpeed(activity,explorationOptions))return defaultSpeedInFeet;if(activity===6){let searchSpeedFactor=1;return explorationOptions.expeditiousSearchLegendary?searchSpeedFactor=4:explorationOptions.expeditiousSearch&&(searchSpeedFactor=2),detectionMode===1?Math.min(halvedSpeed,searchSpeedFactor*30):detectionMode===2?Math.min(halvedSpeed,searchSpeedFactor*15):halvedSpeed}else return activity===4?detectionMode===1?Math.min(halvedSpeed,30):detectionMode===2?Math.min(halvedSpeed,15):halvedSpeed:activity===0?defaultSpeedInFeet:halvedSpeed}__name(calculateCharacterSpeed,"calculateCharacterSpeed"),__name2(calculateCharacterSpeed,"calculateCharacterSpeed");var LengthUnit=(LengthUnit2=>(LengthUnit2[LengthUnit2.MILES=0]="MILES",LengthUnit2[LengthUnit2.FEET=1]="FEET",LengthUnit2))(LengthUnit||{});const golarionMileInFeet=6e3;function toFeet(distance){return distance.unit===0?distance.value*golarionMileInFeet:distance.value}__name(toFeet,"toFeet"),__name2(toFeet,"toFeet");function speedToVelocity(speedInFeet){return{distance:{unit:1,value:speedInFeet*10},time:0}}__name(speedToVelocity,"speedToVelocity"),__name2(speedToVelocity,"speedToVelocity");function toFeetPerMinute(velocity){return velocity.time===0?toFeet(velocity.distance):toFeetPerMinute({distance:{unit:velocity.distance.unit,value:velocity.distance.value/60},time:0})}__name(toFeetPerMinute,"toFeetPerMinute"),__name2(toFeetPerMinute,"toFeetPerMinute");var Terrain=(Terrain2=>(Terrain2[Terrain2.NORMAL=0]="NORMAL",Terrain2[Terrain2.DIFFICULT=1]="DIFFICULT",Terrain2[Terrain2.GREATER_DIFFICULT=2]="GREATER_DIFFICULT",Terrain2))(Terrain||{});function increaseDistanceByTerrain(trip2){const feet=toFeet(trip2.distance);return trip2.terrain===1?feet*trip2.terrainSlowdown.difficult.numerator/trip2.terrainSlowdown.difficult.denominator:trip2.terrain===2?feet*trip2.terrainSlowdown.greaterDifficult.numerator/trip2.terrainSlowdown.greaterDifficult.denominator:feet*trip2.terrainSlowdown.normal.numerator/trip2.terrainSlowdown.normal.denominator}__name(increaseDistanceByTerrain,"increaseDistanceByTerrain"),__name2(increaseDistanceByTerrain,"increaseDistanceByTerrain");const minutesPerHour=60,daysPerWeek=7;function toTravelDuration({distanceInFeet,feetPerMinute,hustleDurationInMinutes,hoursPerDay=8}){const minutesPerDay=hoursPerDay*minutesPerHour,minutesPerWeek=minutesPerDay*daysPerWeek,hustleDuration=Math.min(hustleDurationInMinutes,minutesPerDay),normalTravelDuration=minutesPerDay-hustleDuration,averageSpeed=(feetPerMinute*2*hustleDuration+feetPerMinute*normalTravelDuration)/minutesPerDay,totalMinutes=Math.round(distanceInFeet/averageSpeed),weeks=Math.floor(totalMinutes/minutesPerWeek),days=Math.floor((totalMinutes-weeks*minutesPerWeek)/minutesPerDay),remainingMinutesMovingAtDoubleSpeed=(distanceInFeet-weeks*minutesPerWeek*averageSpeed-days*minutesPerDay*averageSpeed)/(feetPerMinute*2),remainingMinutesSpentHustling=Math.min(remainingMinutesMovingAtDoubleSpeed,hustleDurationInMinutes)+Math.max(0,remainingMinutesMovingAtDoubleSpeed-hustleDurationInMinutes)*2,hours=Math.floor(remainingMinutesSpentHustling/minutesPerHour),minutes=Math.round(remainingMinutesSpentHustling-hours*minutesPerHour);return{weeks,days,hours,minutes}}__name(toTravelDuration,"toTravelDuration"),__name2(toTravelDuration,"toTravelDuration");function calculateTravelDuration({journey,velocity,hustleDurationInMinutes=0,hoursPerDay=8}){const distanceInFeet=sumBy(journey,increaseDistanceByTerrain),feetPerMinute=toFeetPerMinute(velocity);return toTravelDuration({distanceInFeet,feetPerMinute,hustleDurationInMinutes,hoursPerDay})}__name(calculateTravelDuration,"calculateTravelDuration"),__name2(calculateTravelDuration,"calculateTravelDuration");class TravelSpeedSheet extends FormApplication{static{__name(this,"TravelSpeedSheet")}static{__name2(this,"TravelSpeedSheet")}formData=void 0;static get defaultOptions(){const options=super.defaultOptions;return options.id="travel-duration",options.classes=["travel-duration"],options.title=game.i18n.localize("PF2E.TravelSpeed.Title"),options.template="systems/pf2e/templates/gm/travel/travel-speed-sheet.hbs",options.width="auto",options.submitOnChange=!0,options.closeOnSubmit=!1,options}async _updateObject(_event,formData){const data=foundry.utils.expandObject(formData);data.actors=toArray(data.actors),this.formData=data,this.render(!0)}actorFormToSheetData(actor,data){return{requiresDetectionMode:data.explorationActivity==="Search"||data.explorationActivity==="DetectMagic",detectionMode:data.detectionMode,explorationActivity:data.explorationActivity,explorationSpeed:parseFloat(calculateNormalizedCharacterSpeed(data.speed,parseExplorationActivity(data.explorationActivity),parseDetectionModeData(data.detectionMode),parseExplorationOptions(actor)).toFixed(2)),speed:data.speed,name:actor.name}}getInitialActorData(actor){return this.actorFormToSheetData(actor,{detectionMode:"before",explorationActivity:"Search",speed:actor.system.attributes.speed.total})}formToSheetData(actors,data){const journey=[{terrainSlowdown:{difficult:data.difficultTerrainSlowdown,greaterDifficult:data.greaterDifficultTerrainSlowdown,normal:data.normalTerrainSlowdown},terrain:parseTerrainData(data.terrain),distance:{value:data.distance,unit:parseDistanceUnit(data.distanceUnit)}}],actorFormData=zipWith(actors,data.actors,(a,d)=>this.actorFormToSheetData(a,d)),partySpeedInFeet=Math.min(...actorFormData.map(data2=>data2.explorationSpeed)),velocity=speedToVelocity(partySpeedInFeet);return{travelDuration:calculateTravelDuration({journey,hoursPerDay:data.hoursPerDay,velocity,hustleDurationInMinutes:data.hustleMinutes}),distance:data.distance,actors:actorFormData,normalTerrainSlowdown:data.normalTerrainSlowdown,difficultTerrainSlowdown:data.difficultTerrainSlowdown,greaterDifficultTerrainSlowdown:data.greaterDifficultTerrainSlowdown,distanceUnit:data.distanceUnit,terrain:data.terrain,partySpeedInFeet,hustleMinutes:data.hustleMinutes,hoursPerDay:data.hoursPerDay}}getInitialFormData(actors){return this.formToSheetData(actors,{actors:actors.map(actor=>this.getInitialActorData(actor)),terrain:"normal",distanceUnit:"miles",normalTerrainSlowdown:{denominator:1,numerator:1},difficultTerrainSlowdown:{denominator:1,numerator:2},greaterDifficultTerrainSlowdown:{denominator:1,numerator:3},distance:1,hustleMinutes:getHustleMinutes(actors),hoursPerDay:8})}getData(){const sheetData=super.getData();let data;return this.formData===void 0?data=this.getInitialFormData(this.options.actors):data=this.formToSheetData(this.options.actors,this.formData),Object.assign(sheetData,data),sheetData}}function parseDistanceUnit(unit){return unit==="feet"?LengthUnit.FEET:LengthUnit.MILES}__name(parseDistanceUnit,"parseDistanceUnit"),__name2(parseDistanceUnit,"parseDistanceUnit");function parseTerrainData(terrain){return terrain==="normal"?Terrain.NORMAL:terrain==="difficult"?Terrain.DIFFICULT:Terrain.GREATER_DIFFICULT}__name(parseTerrainData,"parseTerrainData"),__name2(parseTerrainData,"parseTerrainData");function parseDetectionModeData(detectionMode){return detectionMode==="none"?DetectionMode$1.NONE:detectionMode==="before"?DetectionMode$1.DETECT_BEFORE_WALKING_INTO_IT:DetectionMode$1.DETECT_EVERYTHING}__name(parseDetectionModeData,"parseDetectionModeData"),__name2(parseDetectionModeData,"parseDetectionModeData");function parseExplorationActivity(activity){return activity==="AvoidNotice"?ExplorationActivities.AVOID_NOTICE:activity==="Defend"?ExplorationActivities.DEFEND:activity==="DetectMagic"?ExplorationActivities.DETECT_MAGIC:activity==="Scout"?ExplorationActivities.SCOUT:activity==="Search"?ExplorationActivities.SEARCH:activity==="None"?ExplorationActivities.NONE:ExplorationActivities.HALF_SPEED}__name(parseExplorationActivity,"parseExplorationActivity"),__name2(parseExplorationActivity,"parseExplorationActivity");function getHustleMinutes(actors){return Math.min(...actors.map(actor=>Math.max(1,actor.system.abilities.con.mod)*10))}__name(getHustleMinutes,"getHustleMinutes"),__name2(getHustleMinutes,"getHustleMinutes");function hasFeat(actor,slug){return actor.itemTypes.feat.some(feat=>feat.slug===slug)}__name(hasFeat,"hasFeat"),__name2(hasFeat,"hasFeat");function parseExplorationOptions(actor){return{practicedDefender:hasFeat(actor,"practiced-defender"),swiftSneak:hasFeat(actor,"swift-sneak"),legendarySneak:hasFeat(actor,"legendary-sneak"),expeditiousSearch:hasFeat(actor,"expeditious-search"),expeditiousSearchLegendary:hasFeat(actor,"expeditious-search")&&actor.attributes.perception.rank===4}}__name(parseExplorationOptions,"parseExplorationOptions"),__name2(parseExplorationOptions,"parseExplorationOptions");function toArray(data){return Object.entries(data).sort(([a],[b])=>parseInt(a)-parseInt(b)).map(([_,a])=>a)}__name(toArray,"toArray"),__name2(toArray,"toArray");function launchTravelSheet(actors){new TravelSpeedSheet({},{actors}).render(!0)}__name(launchTravelSheet,"launchTravelSheet"),__name2(launchTravelSheet,"launchTravelSheet");function CheckFeat(actor,slug){return!!actor.items.find(i=>i.slug===slug&&i.type==="feat")}__name(CheckFeat,"CheckFeat"),__name2(CheckFeat,"CheckFeat");async function treatWounds(options){const actor=(Array.isArray(options.actors)?options.actors:[options.actors])[0];if(!actor||!actor.isOfType("creature")){ui.notifications.error("PF2E.ErrorMessage.NoPCTokenSelected",{localize:!0});return}const medicineName=game.i18n.localize("PF2E.SkillMedicine"),chirurgeon=CheckFeat(actor,"chirurgeon"),naturalMedicine=CheckFeat(actor,"natural-medicine"),domIdAppend=foundry.utils.randomID();new Dialog({title:game.i18n.localize("PF2E.Actions.TreatWounds.Label"),content:`
|
|
<div>${game.i18n.localize("PF2E.Actions.TreatWounds.Label")}</div>
|
|
<hr/>
|
|
<form>
|
|
<div class="form-group">
|
|
<label for="skill-${domIdAppend}">${game.i18n.localize("PF2E.Actions.TreatWounds.SkillSelect")}</label>
|
|
<select id="skill-${domIdAppend}"${!chirurgeon&&!naturalMedicine?" disabled":""}>
|
|
<option value="medicine">${medicineName}</option>
|
|
${chirurgeon?`<option value="crafting">${game.i18n.localize("PF2E.SkillCrafting")}</option>`:""}
|
|
${naturalMedicine?`<option value="nature">${game.i18n.localize("PF2E.SkillNature")}</option>`:""}
|
|
</select>
|
|
</div>
|
|
</form>
|
|
<form>
|
|
<div class="form-group">
|
|
<label for="dc-type-${domIdAppend}">${game.i18n.format("PF2E.InlineCheck.DCWithName",{name:medicineName})}</label>
|
|
<select id="dc-type-${domIdAppend}" name="dc-type">
|
|
<option value="1">${game.i18n.localize("PF2E.Actions.TreatWounds.DC.Trained")}</option>
|
|
<option value="2">${game.i18n.localize("PF2E.Actions.TreatWounds.DC.Expert")}</option>
|
|
<option value="3">${game.i18n.localize("PF2E.Actions.TreatWounds.DC.Master")}</option>
|
|
<option value="4">${game.i18n.localize("PF2E.Actions.TreatWounds.DC.Legendary")}</option>
|
|
</select>
|
|
</div>
|
|
</form>
|
|
<form>
|
|
<div class="form-group">
|
|
<label for="modifier-${domIdAppend}">${game.i18n.localize("PF2E.Actions.TreatWounds.DC.Mod")}</label>
|
|
<input id="modifier-${domIdAppend}" type="number" />
|
|
</div>
|
|
</form>
|
|
${CheckFeat(actor,"risky-surgery")?`<form><div class="form-group">
|
|
<label for="risky-surgery-${domIdAppend}">${game.i18n.localize("PF2E.Actions.TreatWounds.Feats.RiskySurgery")}</label>
|
|
<input type="checkbox" id="risky-surgery-${domIdAppend}" />
|
|
</div></form>`:""}
|
|
${CheckFeat(actor,"mortal-healing")?`<form><div class="form-group">
|
|
<label for="mortal-healing-${domIdAppend}">${game.i18n.localize("PF2E.Actions.TreatWounds.Feats.MortalHealing")}</label>
|
|
<input type="checkbox" id="mortal-healing-${domIdAppend}" checked />
|
|
</div></form>`:""}
|
|
</form>
|
|
`,buttons:{yes:{icon:fontAwesomeIcon("hand-holding-medical").outerHTML,label:game.i18n.localize("PF2E.Actions.TreatWounds.Label"),callback:$html=>treat(actor,$html,options.event,domIdAppend)},no:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}},default:"yes"}).render(!0)}__name(treatWounds,"treatWounds"),__name2(treatWounds,"treatWounds");async function treat(actor,$html,event2=null,domIdAppend){const{name:name2}=actor,mod=Number($html.find(`#modifier-${domIdAppend}`).val())||0,requestedProf=Number($html.find(`#dc-type-${domIdAppend}`).val())||1,riskySurgery=$html.find(`#risky-surgery-${domIdAppend}`).prop("checked"),mortalHealing=$html.find(`#mortal-healing-${domIdAppend}`).prop("checked"),skillSlug=String($html.find(`#skill-${domIdAppend}`).val())||"medicine",skill=actor.skills[skillSlug];if(!skill?.proficient){const skillName=objectHasKey(CONFIG.PF2E.skillList,skillSlug)?game.i18n.localize(CONFIG.PF2E.skillList[skillSlug]):skillSlug;ui.notifications.warn(game.i18n.format("PF2E.Actions.TreatWounds.Error",{name:name2,skill:skillName}));return}const rank=skill.rank??1,usedProf=requestedProf<=rank?requestedProf:rank,medicBonus=CheckFeat(actor,"medic-dedication")?(usedProf-1)*5:0,magicHandsBonus=CheckFeat(actor,"magic-hands")?actor.system.details.level.value:0,dcValue=[15,20,30,40][usedProf-1]+mod,bonus=[0,10,30,50][usedProf-1]+medicBonus+magicHandsBonus,rollOptions=actor.getRollOptions(["all","skill-check","medicine"]);rollOptions.push("action:treat-wounds"),riskySurgery&&rollOptions.push("risky-surgery");const dc={value:dcValue,visible:!0},increaseDoS=__name2(locKey=>({adjustments:{success:{label:`PF2E.Actions.TreatWounds.Rolls.${locKey}`,amount:DEGREE_ADJUSTMENT_AMOUNTS.INCREASE}}}),"increaseDoS");(actor.synthetics.degreeOfSuccessAdjustments.medicine??=[]).push(...riskySurgery?[increaseDoS("RiskySurgery")]:mortalHealing?[increaseDoS("MortalHealing")]:[]),skill.check.roll({dc,...eventToRollParams(event2,{type:"check"}),extraRollOptions:rollOptions,callback:async(_roll,outcome,message)=>{const successLabel=outcome?game.i18n.localize(`PF2E.Check.Result.Degree.Check.${outcome}`):"",magicHands=CheckFeat(actor,"magic-hands"),bonusString=bonus>0?`+ ${bonus}`:"",healFormula=(()=>{switch(outcome){case"criticalSuccess":return magicHands?`4d10${bonusString}`:`4d8${bonusString}`;case"success":return magicHands?`2d10${bonusString}`:`2d8${bonusString}`;case"criticalFailure":return"1d8";default:return null}})(),speaker=ChatMessagePF2e.getSpeaker({actor});if(riskySurgery&&ChatMessagePF2e.create({flags:message.toObject().flags,type:CONST.CHAT_MESSAGE_TYPES.ROLL,flavor:`<strong>${game.i18n.localize("PF2E.Actions.TreatWounds.Rolls.RiskySurgery")}</strong>`,rolls:[(await new DamageRoll("{1d8[slashing]}").roll({async:!0})).toJSON()],speaker}),healFormula){const formulaModifier=outcome==="criticalFailure"?"":"[healing]",healRoll=await new DamageRoll(`{(${healFormula})${formulaModifier}}`).roll({async:!0}),rollType=outcome!=="criticalFailure"?game.i18n.localize("PF2E.Actions.TreatWounds.Rolls.TreatWounds"):game.i18n.localize("PF2E.Actions.TreatWounds.Rolls.TreatWoundsCriticalFailure");ChatMessagePF2e.create({flags:message.toObject().flags,type:CONST.CHAT_MESSAGE_TYPES.ROLL,flavor:`<strong>${rollType}</strong> (${successLabel})`,rolls:[healRoll.toJSON()],speaker})}}})}__name(treat,"treat"),__name2(treat,"treat");function getHazards(actors){return actors.filter(a=>a.type==="hazard")}__name(getHazards,"getHazards"),__name2(getHazards,"getHazards");function getLevels(actors,alliance){return actors.filter(a=>a.alliance===alliance).map(a=>a.level)}__name(getLevels,"getLevels"),__name2(getLevels,"getLevels");function dialogTemplate(xp){return`
|
|
<h2>XP</h2>
|
|
<table>
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.PartySize")}</th>
|
|
<td>${xp.partySize}</td>
|
|
</tr>
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.PartyLevel")}</th>
|
|
<td>${xp.partyLevel}</td>
|
|
</tr>
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.Threat")}</th>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats."+xp.rating)} (${xp.totalXP} XP)</td>
|
|
</tr>
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.Reward")}</th>
|
|
<td>${xp.xpPerPlayer} XP</td>
|
|
</tr>
|
|
</table>
|
|
<h2>${game.i18n.localize("PF2E.Encounter.Budget.EncounterBudget")}</h2>
|
|
<table class="pf2-table">
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.Threat")}</th>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.XPBudget")}</th>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.XPNeeded")}</th>
|
|
<th>${game.i18n.localize("PF2E.Encounter.Budget.Reward")}</th>
|
|
</tr>
|
|
<tr>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats.trivial")}</td>
|
|
<td>${xp.encounterBudgets.trivial}</td>
|
|
<td>${xp.encounterBudgets.trivial-xp.totalXP}</td>
|
|
<td>40</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats.low")}</td>
|
|
<td>${xp.encounterBudgets.low}</td>
|
|
<td>${xp.encounterBudgets.low-xp.totalXP}</td>
|
|
<td>60</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats.moderate")}</td>
|
|
<td>${xp.encounterBudgets.moderate}</td>
|
|
<td>${xp.encounterBudgets.moderate-xp.totalXP}</td>
|
|
<td>80</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats.severe")}</td>
|
|
<td>${xp.encounterBudgets.severe}</td>
|
|
<td>${xp.encounterBudgets.severe-xp.totalXP}</td>
|
|
<td>120</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${game.i18n.localize("PF2E.Encounter.Budget.Threats.extreme")}</td>
|
|
<td>${xp.encounterBudgets.extreme}</td>
|
|
<td>${xp.encounterBudgets.extreme-xp.totalXP}</td>
|
|
<td>160</td>
|
|
</tr>
|
|
</table>
|
|
<h2>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureXPAndRole")}</h2>
|
|
<table class="pf2-table">
|
|
<tr>
|
|
<th>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevel")}</th>
|
|
<th>XP</th>
|
|
<th>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.SuggestedRole")}</th>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel-4}</td>
|
|
<td>10</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.-4")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel-3}</td>
|
|
<td>15</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.-3")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel-2}</td>
|
|
<td>20</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.-2")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel-1}</td>
|
|
<td>30</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.-1")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel}</td>
|
|
<td>40</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.0")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel+1}</td>
|
|
<td>60</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.1")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel+2}</td>
|
|
<td>80</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.2")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel+3}</td>
|
|
<td>120</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.3")}</td>
|
|
</tr>
|
|
<tr>
|
|
<td>${xp.partyLevel+4}</td>
|
|
<td>160</td>
|
|
<td>${game.i18n.localize("PF2E.Encounter.CreatureXPAndRole.CreatureLevels.4")}</td>
|
|
</tr>
|
|
</table>`}__name(dialogTemplate,"dialogTemplate"),__name2(dialogTemplate,"dialogTemplate");const askLevelPopupTemplate=__name2(()=>{const partySize=Math.trunc(Number(localStorage.getItem("xpMacroPartySize")??4)),partyLevel=Math.trunc(Number(localStorage.getItem("xpMacroPartyLevel")??1));return`
|
|
<form>
|
|
<div class="form-group">
|
|
<label>${game.i18n.localize("PF2E.Encounter.Budget.PartySize")}</label>
|
|
<input id="party-size" name="party-size" type="number" value="${partySize}">
|
|
</div>
|
|
<div class="form-group">
|
|
<label>${game.i18n.localize("PF2E.Encounter.Budget.PartyLevel")}</label>
|
|
<input id="party-level" name="party-level" type="number" value="${partyLevel}">
|
|
</div>
|
|
</form>
|
|
`},"askLevelPopupTemplate");function showXP(partyLevel,partySize,npcLevels,hazards){const pwol=game.pf2e.settings.variants.pwol.enabled,xp=game.pf2e.gm.calculateXP(partyLevel,partySize,npcLevels,hazards,{pwol});new Dialog({title:"XP",content:dialogTemplate(xp),buttons:{}}).render(!0)}__name(showXP,"showXP"),__name2(showXP,"showXP");function askPartyLevelAndSize(npcLevels,hazards){new Dialog({title:"Party Information",content:askLevelPopupTemplate,buttons:{no:{icon:fontAwesomeIcon("times").outerHTML,label:"Cancel"},yes:{icon:fontAwesomeIcon("calculator").outerHTML,label:"Calculate XP",callback:$html=>{const html=$html[0],partySize=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-size]")?.value||1))),partyLevel=Math.abs(Math.trunc(Number(htmlQuery(html,"[name=party-level]")?.value||1)));localStorage.setItem("xpMacroPartySize",partySize.toString()),localStorage.setItem("xpMacroPartyLevel",partyLevel.toString()),showXP(partyLevel,partySize,npcLevels,hazards)}}},default:"yes"}).render(!0)}__name(askPartyLevelAndSize,"askPartyLevelAndSize"),__name2(askPartyLevelAndSize,"askPartyLevelAndSize");function xpFromEncounter(){const actors=canvas.tokens.controlled.flatMap(a=>a.actor??[]).filter(a=>!a.traits.has("minion")),npcLevels=getLevels(actors,"opposition"),pcLevels=getLevels(actors,"party"),hazards=getHazards(actors);if(npcLevels.length===0&&hazards.length===0){ui.notifications.error("You must select at least one opposition and/or hazard token and optionally all PC tokens");return}pcLevels.length===0?askPartyLevelAndSize(npcLevels,hazards):showXP(pcLevels[0],pcLevels.length,npcLevels,hazards)}__name(xpFromEncounter,"xpFromEncounter"),__name2(xpFromEncounter,"xpFromEncounter");const xpVariantCreatureDifferences=new Map([[-7,9],[-6,12],[-5,14],[-4,18],[-3,21],[-2,26],[-1,32],[0,40],[1,48],[2,60],[3,72],[4,90],[5,108],[6,135],[7,160]]),xpCreatureDifferences=new Map([[-4,10],[-3,15],[-2,20],[-1,30],[0,40],[1,60],[2,80],[3,120],[4,160]]),xpSimpleHazardDifferences=new Map([[-4,2],[-3,3],[-2,4],[-1,6],[0,8],[1,12],[2,16],[3,24],[4,32]]);function getXPFromMap(partyLevel,entityLevel,values){const difference2=entityLevel+1-(partyLevel+1),range2=Math.floor(values.size/2),boundedDifference=Math.clamped(difference2,0-range2,range2);return values.get(boundedDifference)??0}__name(getXPFromMap,"getXPFromMap"),__name2(getXPFromMap,"getXPFromMap");function calculateCreatureXP(partyLevel,npcLevel,dcOptions){return dcOptions.pwol?getXPFromMap(partyLevel,npcLevel,xpVariantCreatureDifferences):getXPFromMap(partyLevel,npcLevel,xpCreatureDifferences)}__name(calculateCreatureXP,"calculateCreatureXP"),__name2(calculateCreatureXP,"calculateCreatureXP");function getHazardXp(partyLevel,hazard,dcOptions){return hazard.isComplex?calculateCreatureXP(partyLevel,hazard.level,dcOptions):getXPFromMap(partyLevel,hazard.level,xpSimpleHazardDifferences)}__name(getHazardXp,"getHazardXp"),__name2(getHazardXp,"getHazardXp");function generateEncounterBudgets(partySize){const budget=partySize*20;return{trivial:Math.floor(budget*.5),low:Math.floor(budget*.75),moderate:budget,severe:Math.floor(budget*1.5),extreme:Math.floor(budget*2)}}__name(generateEncounterBudgets,"generateEncounterBudgets"),__name2(generateEncounterBudgets,"generateEncounterBudgets");const rewardEncounterBudgets=generateEncounterBudgets(4);function calculateEncounterRating(challenge,budgets){return challenge<=budgets.trivial?"trivial":challenge<=budgets.low?"low":challenge<=budgets.moderate?"moderate":challenge<=budgets.severe?"severe":"extreme"}__name(calculateEncounterRating,"calculateEncounterRating"),__name2(calculateEncounterRating,"calculateEncounterRating");function calculateXP(partyLevel,partySize,npcLevels,hazards,dcOptions){const creatureChallenge=npcLevels.map(level=>calculateCreatureXP(partyLevel,level,dcOptions)).reduce((a,b)=>a+b,0),hazardChallenge=hazards.map(hazard=>getHazardXp(partyLevel,hazard,dcOptions)).reduce((a,b)=>a+b,0),totalXP=creatureChallenge+hazardChallenge,encounterBudgets=generateEncounterBudgets(partySize),rating=calculateEncounterRating(totalXP,encounterBudgets),ratingXP=rewardEncounterBudgets[rating];return{partyLevel,partySize,totalXP,encounterBudgets,rating,ratingXP,xpPerPlayer:Math.floor(totalXP/partySize*4)}}__name(calculateXP,"calculateXP"),__name2(calculateXP,"calculateXP");class EncounterPF2e extends Combat{static{__name(this,"EncounterPF2e")}static{__name2(this,"EncounterPF2e")}_sortCombatants(a,b){const resolveTie=__name2(()=>{const[priorityA,priorityB]=[a,b].map(combatant=>combatant.overridePriority(combatant.initiative??0)??(combatant.actor?.system.attributes.initiative?combatant.actor.system.attributes.initiative.tiebreakPriority:3));return priorityA===priorityB?a.id.localeCompare(b.id):priorityA-priorityB},"resolveTie");return typeof a.initiative=="number"&&typeof b.initiative=="number"&&a.initiative===b.initiative?resolveTie():super._sortCombatants(a,b)}getCombatantWithHigherInit(a,b){const sortResult=this._sortCombatants(a,b);return sortResult>0?b:sortResult<0?a:null}analyze(){if(!game.ready)return null;const{party}=game.actors,partyMembers=party?.members.filter(a=>a.alliance==="party"&&isReallyPC(a))??[],fightyPartyMembers=(()=>{const inEncounter=partyMembers.filter(m=>m.combatant?.encounter===this);return inEncounter.length>0?inEncounter:partyMembers})(),opposition=uniq(this.combatants.filter(c=>!!(c.actor?.alliance==="opposition"||c.actor?.isOfType("hazard"))&&!partyMembers.includes(c.actor)).flatMap(c=>c.actor??[]));if(!party||fightyPartyMembers.length===0||opposition.length===0)return null;const partyLevel=Math.round(meanBy(fightyPartyMembers.filter(m=>m.isOfType("character")),m=>m.level)),result=calculateXP(partyLevel,fightyPartyMembers.length,opposition.filter(e=>e.isOfType("character","npc")).map(e=>e.level),opposition.filter(e=>e.isOfType("hazard")),{pwol:game.pf2e.settings.variants.pwol.enabled}),threat=result.rating,budget={spent:result.totalXP,max:result.encounterBudgets[threat],partyLevel},award={xp:Math.floor(result.xpPerPlayer*(fightyPartyMembers.length/partyMembers.length)),recipients:partyMembers};return{threat,budget,award,participants:{party:fightyPartyMembers,opposition}}}prepareDerivedData(){super.prepareDerivedData(),this.metrics=this.analyze()}async createEmbeddedDocuments(embeddedName,data,context={}){const createData=data.filter(datum=>{const token=canvas.tokens.placeables.find(canvasToken=>canvasToken.id===datum.tokenId);if(!token)return!1;const{actor}=token;if(!actor)return ui.notifications.warn(`${token.name} has no associated actor.`),!1;const actorTraits=actor.traits;if(actor.type==="loot"||["minion","eidolon"].some(t=>actorTraits.has(t))){const actorTypes2=CONFIG.PF2E.actorTypes,type=game.i18n.localize(actorTraits.has("minion")?CONFIG.PF2E.creatureTraits.minion:actorTraits.has("eidolon")?CONFIG.PF2E.creatureTraits.eidolon:actorTypes2[actor.type]);return ui.notifications.info(game.i18n.format("PF2E.Encounter.ExcludingFromInitiative",{type,actor:actor.name})),!1}return!0});return super.createEmbeddedDocuments(embeddedName,createData,context)}async rollInitiative(ids,options={}){const extraRollOptions=options.extraRollOptions??[],rollMode=options.messageOptions?.rollMode??options.rollMode;options.secret&&extraRollOptions.push("secret");const fightyCombatants=ids.flatMap(id=>this.combatants.get(id)??[]).filter(c=>!!c.actor?.initiative),initiatives=(await Promise.all(fightyCombatants.map(async combatant=>combatant.actor?.initiative?.roll({...options,combatant,extraRollOptions,updateTracker:!1,rollMode})??null))).flatMap(result=>result?{id:result.combatant.id,value:result.roll.total,statistic:result.roll.options.domains?.find(s=>setHasElement(SKILL_LONG_FORMS,s)||s==="perception")??null}:[]);await this.setMultipleInitiatives(initiatives);const remainingIds=ids.filter(id=>!fightyCombatants.some(c=>c.id===id));return super.rollInitiative(remainingIds,options)}async setMultipleInitiatives(initiatives){const currentId=this.combatant?.id,updates=initiatives.map(i=>({_id:i.id,initiative:i.value,flags:{pf2e:{initiativeStatistic:i.statistic??null,overridePriority:{[i.value]:i.overridePriority}}}}));await this.updateEmbeddedDocuments("Combatant",updates),this.turn!==null&&await this.update({turn:this.turns.findIndex(c=>c.id===currentId)})}async setInitiative(id,value){const combatant=this.combatants.get(id,{strict:!0});if(combatant.actor?.isOfType("character","npc"))return this.setMultipleInitiatives([{id:combatant.id,value,statistic:combatant.actor.attributes.initiative.statistic||"perception"}]);super.setInitiative(id,value)}async resetActors(){const actors=uniq(compact(this.combatants.contents.flatMap(c=>[c.actor,c.actor?.isOfType("character")?c.actor.familiar:null])));resetActors(actors,{sheets:!1,tokens:!0})}_onCreate(data,options,userId){super._onCreate(data,options,userId);const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),game.pf2e.StatusEffects.onUpdateEncounter(this);const{combatant,previous}=this,actor=combatant?.actor;if(!this.started)return;const[newRound,newTurn]=[changed.round,changed.turn],isRoundChange=typeof newRound=="number",isTurnChange=typeof newTurn=="number",isNextRound=isRoundChange&&(previous.round===null||newRound>previous.round),isNextTurn=isTurnChange&&(previous.turn===null||newTurn>previous.turn);(isRoundChange||isTurnChange)&&Promise.resolve().then(async()=>{if(isNextRound||isNextTurn){const previousCombatant=this.combatants.get(previous.combatantId??"");if(game.user===previousCombatant?.actor?.primaryUpdater){const alreadyWent=previousCombatant.flags.pf2e.roundOfLastTurnEnd===previous.round;typeof previous.round=="number"&&!alreadyWent&&await previousCombatant.endTurn({round:previous.round})}if(game.user===actor?.primaryUpdater){const alreadyWent=combatant?.roundOfLastTurn===this.round;combatant&&!alreadyWent&&await combatant.startTurn()}}this.resetActors(),await game.pf2e.effectTracker.refresh(),game.pf2e.effectPanel.refresh()})}_onDelete(options,userId){if(super._onDelete(options,userId),this.started&&(Hooks.callAll("pf2e.endTurn",this.combatant??null,this,userId),game.pf2e.effectTracker.onEncounterEnd(this)),!game.combat){const pcSheets=Object.values(ui.windows).filter(sheet=>sheet.constructor.name==="CharacterSheetPF2e");for(const sheet of pcSheets)sheet.toggleInitiativeLink()}game.user.clearTargets(),this.resetActors()}async _manageTurnEvents(adjustedTurn){if(this.previous||game.release.generation>11)return super._manageTurnEvents(adjustedTurn)}}class CombatantPF2e extends Combatant{static{__name(this,"CombatantPF2e")}static{__name2(this,"CombatantPF2e")}get encounter(){return this.parent}get roundOfLastTurn(){return this.flags.pf2e.roundOfLastTurn}get playersCanSeeName(){return!!this.token?.playersCanSeeName}overridePriority(initiative){return this.flags.pf2e.overridePriority[initiative]??null}hasHigherInitiative({than}){if(this.parent.id!==than.parent.id)throw ErrorPF2e("The initiative of Combatants from different combats cannot be compared");return this.parent.getCombatantWithHigherInit(this,than)===this}static async fromActor(actor,render=!0,options={}){if(!game.combat)return ui.notifications.error(game.i18n.localize("PF2E.Encounter.NoActiveEncounter")),null;const token=actor.getActiveTokens().pop(),existing=game.combat.combatants.find(combatant=>combatant.actor===actor);return existing||(token?(await(options.combat??game.combat).createEmbeddedDocuments("Combatant",[{tokenId:token.id,actorId:token.actor?.id,sceneId:token.scene.id,hidden:token.document.hidden}],{render})).at(0)??null:(ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:actor.name})),null))}static async createDocuments(data=[],context={}){const entries=data.map(d=>({token:(d.sceneId?game.scenes.get(d.sceneId):context.parent?.scene)?.tokens.get(d.tokenId??"")||null,data:d})),tokens=entries.map(e=>e.token);for(const token of tokens)token?.actor?.isOfType("party")&&await token?.actor.addToCombat({combat:context.parent});const nonPartyData=entries.filter(e=>!e.token?.actor?.isOfType("party")).map(e=>e.data);return super.createDocuments(nonPartyData,context)}async startTurn(){const{actor,encounter}=this;if(!encounter||!actor)return;const actorUpdates={};for(const rule of actor.rules)await rule.onTurnStart?.(actorUpdates);await this.update({"flags.pf2e.roundOfLastTurn":encounter.round}),Object.keys(actorUpdates).length>0&&await actor.update(actorUpdates);for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("start");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("start");Hooks.callAll("pf2e.startTurn",this,encounter,game.user.id)}async endTurn(options){const round=options.round,{actor,encounter}=this;if(!encounter||!actor)return;const activeConditions=actor.conditions.active;for(const condition of activeConditions)await condition.onEndTurn({token:this.token});for(const effect of actor.itemTypes.effect)await effect.onTurnStartEnd("end");if(actor.isOfType("character")&&actor.familiar)for(const effect of actor.familiar.itemTypes.effect)await effect.onTurnStartEnd("end");await this.update({"flags.pf2e.roundOfLastTurnEnd":round}),Hooks.callAll("pf2e.endTurn",this,encounter,game.user.id)}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e=foundry.utils.mergeObject(this.flags.pf2e??{},{overridePriority:{}}),this.flags.pf2e.roundOfLastTurn??=null,this.flags.pf2e.initiativeStatistic??=null}async toggleDefeated({to=!this.isDefeated,overlayIcon=!0}={}){to!==this.isDefeated&&(await this.update({defeated:to}),overlayIcon&&await this.token?.object?.toggleEffect(game.settings.get("pf2e","deathIcon"),{active:to,overlay:!0}),this.isDefeated&&this.token?.object?.isTargeted&&this.token.object.setTarget(!1,{releaseOthers:!1}))}updateResource(){return this.isNPC&&!game.user.isGM?this.resource=null:super.updateResource()}_getInitiativeFormula(){const{actor}=this;if(!actor)return"1d20";let bonus=0;return typeof actor.attributes.initiative?.totalModifier=="number"?bonus=actor.attributes.initiative.totalModifier:actor.attributes.perception&&(bonus=actor.attributes.perception.value),["1d20",bonus||0].join("+")}async toggleNameVisibility(){if(!this.token)return;const currentVisibility=this.token.displayName,visibilityToggles={[CONST.TOKEN_DISPLAY_MODES.ALWAYS]:CONST.TOKEN_DISPLAY_MODES.OWNER,[CONST.TOKEN_DISPLAY_MODES.CONTROL]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.HOVER]:CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,[CONST.TOKEN_DISPLAY_MODES.NONE]:CONST.TOKEN_DISPLAY_MODES.HOVER,[CONST.TOKEN_DISPLAY_MODES.OWNER]:CONST.TOKEN_DISPLAY_MODES.ALWAYS,[CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER]:CONST.TOKEN_DISPLAY_MODES.HOVER};await this.token.update({displayName:visibilityToggles[currentVisibility]})}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),this.encounter?.started&&typeof changed.initiative=="number"&&this.encounter.resetActors(),changed.defeated&&game.user.id===userId)for(const action2 of this.actor?.itemTypes.action??[])action2.system.deathNote&&action2.toMessage(void 0,{rollMode:this.actor?.hasPlayerOwner?"publicroll":"gmroll"})}_onDelete(options,userId){super._onDelete(options,userId),this.encounter?.started&&this.encounter.resetActors()}}class ActorInitiative{static{__name(this,"ActorInitiative")}static{__name2(this,"ActorInitiative")}actor;statistic;get attribute(){return this.statistic.attribute}get ability(){return foundry.utils.logCompatibilityWarning("`ActorInitiative#ability` is deprecated. Use `ActorInitiative#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}constructor(actor,{statistic}){this.actor=actor;const base=actor.getStatistic(statistic),ponderousPenalty=actor.isOfType("character")?createPonderousPenalty(actor):null,rollLabel=game.i18n.format("PF2E.InitiativeWithSkill",{skillName:base?.label??""}),data={slug:"initiative",label:base?.label??"PF2E.InitiativeLabel",domains:["initiative"],rollOptions:[base?.slug??[]].flat(),check:{type:"initiative",label:rollLabel},modifiers:[ponderousPenalty??[]].flat()};this.statistic=base?base.extend(data):new Statistic(actor,data)}async roll(args={}){const combatant=args.combatant?.actor===this.actor?args.combatant:await CombatantPF2e.fromActor(this.actor,!1);if(!combatant)return null;combatant.hidden&&(args.rollMode=CONST.DICE_ROLL_MODES.PRIVATE);const roll=await this.statistic.roll(args);return roll?((args.updateTracker??!0)&&combatant.encounter.setInitiative(combatant.id,roll.total),{combatant,roll}):(game.combats.render(!1),null)}getTraceData(){const initiativeData=this.actor.attributes.initiative,tiebreakPriority=initiativeData?.tiebreakPriority??0;return{...this.statistic.getTraceData(),statistic:initiativeData?.statistic??"perception",tiebreakPriority}}}class CreatureSizeRuleElement extends RuleElementPF2e{static{__name(this,"CreatureSizeRuleElement")}static{__name2(this,"CreatureSizeRuleElement")}static validActorTypes=["character","npc","familiar"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),reach:new RecordField(new fields2.StringField({required:!0,nullable:!1,choices:["add","upgrade","override"]}),new ResolvableValueField({required:!0,nullable:!1}),{required:!1,nullable:!1,initial:void 0}),resizeEquipment:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),minimumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0}),maximumSize:new fields2.StringField({required:!1,nullable:!1,choices:SIZES,initial:void 0})}}constructor(data,options){super(data,options),typeof this.value=="string"||typeof this.value=="number"||this.isBracketedValue(this.value)||this.failValidation("value must be a number, string, or bracketed value")}static wordToAbbreviation={tiny:"tiny",small:"sm",medium:"med",large:"lg",huge:"huge",gargantuan:"grg"};static incrementMap={tiny:"sm",sm:"med",med:"lg",lg:"huge",huge:"grg",grg:"grg"};static decrementMap={tiny:"tiny",sm:"tiny",med:"sm",lg:"med",huge:"lg",grg:"huge"};incrementSize(size,amount){return amount===0?size:this.incrementSize(CreatureSizeRuleElement.incrementMap[size],amount-1)}decrementSize(size,amount){return amount===0?size:this.decrementSize(CreatureSizeRuleElement.decrementMap[size],amount-1)}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(!(typeof value=="string"||typeof value=="number")){this.failValidation(`CreatureSize Rule Element on actor ${this.actor.id} (${this.actor.name})`,"has a non-string, non-numeric value");return}const size=CreatureSizeRuleElement.wordToAbbreviation[value]??value;if(typeof size=="string"&&!tupleHasValue(SIZES,size)){this.failValidation(`"${size}" is not a recognized size`);return}const{actor}=this,originalSize=new ActorSizePF2e({value:actor.size});if(value===1){if(this.maximumSize&&!originalSize.isSmallerThan(this.maximumSize))return;actor.system.traits.size.increment()}else if(value===-1){if(this.minimumSize&&!originalSize.isLargerThan(this.minimumSize))return;actor.system.traits.size.decrement()}else if(tupleHasValue(SIZES,size))actor.system.traits.size=new ActorSizePF2e({value:size});else{const validValues=Array.from(new Set(Object.entries(CreatureSizeRuleElement.wordToAbbreviation).flat())).join('", "');this.failValidation(`CreatureSize Rule Element on actor ${actor.id} (${actor.name})`,`has an invalid value: must be one of "${validValues}", +1, or -1`);return}const{reach}=actor.system.attributes;if(reach.base=this.#getReach(originalSize),reach.manipulate=Math.max(reach.manipulate,reach.base),this.resizeEquipment){const sizeDifference=originalSize.difference(actor.system.traits.size,{smallIsMedium:!0});for(const item of actor.inventory.filter(i=>!(i instanceof TreasurePF2e&&i.isCoinage)))sizeDifference<0?item.system.size=this.incrementSize(item.size,Math.abs(sizeDifference)):sizeDifference>0&&(item.system.size=this.decrementSize(item.size,Math.abs(sizeDifference)))}}#getReach(originalSize){const current=this.actor.attributes.reach.base;if(this.reach){const changeValue=(()=>{const resolved=this.resolveValue(this.reach.add??this.reach.upgrade??this.reach.override);return Math.trunc(Math.abs(Number(resolved)))})();if(!Number.isInteger(changeValue))return current;if(this.reach.add)return current+changeValue;if(this.reach.upgrade)return Math.max(current,changeValue);if(this.reach.override)return changeValue}const newSize=this.actor.system.traits.size;return newSize.isLargerThan(originalSize)?Math.max(SIZE_TO_REACH[this.actor.size],current):newSize.isSmallerThan(originalSize)?Math.min(SIZE_TO_REACH[this.actor.size],current):current}}class IWRRuleElement extends RuleElementPF2e{static{__name(this,"IWRRuleElement")}static{__name2(this,"IWRRuleElement")}static get dictionary(){return{}}static defineSchema(){const{fields:fields2}=foundry.data,{DataModelValidationFailure}=foundry.data.validation;return{...super.defineSchema(),mode:new fields2.StringField({required:!0,choices:["add","remove"],initial:"add"}),type:new fields2.ArrayField(new StrictStringField({required:!0,blank:!1,initial:void 0}),{validate:v=>Array.isArray(v)&&v.length>0||new DataModelValidationFailure({message:"must have at least one"})}),definition:new PredicateField({required:!1,initial:void 0}),exceptions:this.createExceptionsField(),override:new fields2.BooleanField}}static createExceptionsField(types){const customExceptionField=new foundry.data.fields.SchemaField({definition:new PredicateField({initial:void 0}),label:new StrictStringField({required:!0,blank:!1,initial:void 0})},{required:!0,initial:void 0}),exceptionField=new DataUnionField([new StrictStringField({required:!0,blank:!1,initial:void 0,choices:types}),customExceptionField],{required:!0,nullable:!1,initial:void 0});return new StrictArrayField(exceptionField)}static validateJoint(source){if(super.validateJoint(source),source.type.some(t=>t==="custom")){if(source.type.length>1)throw Error(' type: "custom" may not be included among other types');if(!source.definition)throw Error(" definition: must be present if defining a custom type")}else if(source.definition)throw Error(" definition: may only be present if defining a custom type");if(source.mode==="remove"&&source.exceptions.length>0)throw Error(' exceptions: may not be included with a mode of "remove"')}#isValid(value){const{dictionary}=this.constructor,unrecognizedTypes=this.type.filter(t=>!(t in dictionary));if(unrecognizedTypes.length>0){for(const type of unrecognizedTypes)this.failValidation(`Type "${type}" is unrecognized`);return!1}return this.mode==="add"&&dictionary!==CONFIG.PF2E.immunityTypes&&(typeof value!="number"||value<0)?(this.failValidation("A `value` must be a positive number"),!1):!0}afterPrepareData(){if(!this.test())return;this.type=this.resolveInjectedProperties(this.type),this.definition=this.resolveInjectedProperties(this.definition);const value=Math.floor(Number(this.resolveValue(this.value)));if(this.#isValid(value))if(this.mode==="add")this.property.push(...this.getIWR(value));else for(const toRemove of this.type)this.property.findSplice(iwr=>iwr.type===toRemove)}}class ImmunityRuleElement extends IWRRuleElement{static{__name(this,"ImmunityRuleElement")}static{__name2(this,"ImmunityRuleElement")}value=null;static defineSchema(){return{...super.defineSchema(),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.immunityTypes}get property(){return this.actor.system.attributes.immunities}getIWR(){const immunities=this.property;return this.type.map(t=>new Immunity({type:t,customLabel:t==="custom"?this.label:null,definition:this.definition,exceptions:this.exceptions,source:this.item.name})).filter(immunity=>!immunities.find(i=>i.type===immunity.type&&(this.exceptions.length===0||equals(i.exceptions,this.exceptions))&&equals(i.definition,this.definition??null))||this.mode==="remove")}}class ResistanceRuleElement extends IWRRuleElement{static{__name(this,"ResistanceRuleElement")}static{__name2(this,"ResistanceRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary),doubleVs:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.resistanceTypes}get property(){return this.actor.system.attributes.resistances}getIWR(value){if(value<=0)return[];const resistances=this.property;for(const resistanceType of[...this.type]){const current=resistances.find(r=>r.type===resistanceType&&equals(r.exceptions,this.exceptions)&&equals(r.doubleVs,this.doubleVs)&&equals(r.definition,this.definition??null));current&&(this.override?resistances.splice(resistances.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(resistanceType),1)))}return this.type.map(t=>new Resistance({type:t,value,customLabel:t==="custom"?this.label:null,definition:this.definition,exceptions:this.exceptions,doubleVs:this.doubleVs,source:this.item.name}))}}class WeaknessRuleElement extends IWRRuleElement{static{__name(this,"WeaknessRuleElement")}static{__name2(this,"WeaknessRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),exceptions:this.createExceptionsField(this.dictionary)}}static get dictionary(){return CONFIG.PF2E.weaknessTypes}get property(){return this.actor.system.attributes.weaknesses}getIWR(value){if(value<=0)return[];const weaknesses=this.property;for(const weaknessType of[...this.type]){const current=weaknesses.find(w=>w.type===weaknessType&&equals(w.exceptions,this.exceptions)&&equals(w.definition,this.definition??null));current&&(this.override?weaknesses.splice(weaknesses.indexOf(current),1):this.mode!=="remove"&&(current.value=Math.max(current.value,value),current.source=this.label,this.type.splice(this.type.indexOf(weaknessType),1)))}return this.type.map(t=>new Weakness({type:t,customLabel:t==="custom"?this.label:null,definition:this.definition,value,exceptions:this.exceptions,source:this.item.name}))}}class SenseRuleElement extends RuleElementPF2e{static{__name(this,"SenseRuleElement")}static{__name2(this,"SenseRuleElement")}static validActorTypes=["character","familiar"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,choices:[...SENSE_TYPES]}),force:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),acuity:new fields2.StringField({required:!1,nullable:!1,choices:SENSE_ACUITIES,initial:void 0}),range:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}beforePrepareData(){if(!this.test())return;const range2=this.resolveValue(this.range,""),newSense=new CreatureSensePF2e({type:this.selector,acuity:this.acuity,value:String(range2),source:this.item.name});this.actor.synthetics.senses.push({sense:newSense,predicate:this.predicate,force:this.force})}}class StrikeRuleElement extends RuleElementPF2e{static{__name(this,"StrikeRuleElement")}static{__name2(this,"StrikeRuleElement")}static validActorTypes=["character","npc"];constructor(source,options){source.img??=source.fist?"icons/skills/melee/unarmed-punch-fist.webp":options.parent.img,super(source,options),this.fist&&(this.label=game.i18n.localize("PF2E.Weapon.Base.fist")),this.slug??=sluggify(this.label),this.battleForm??=!1,this.fist??=!1,this.options??=[],this.graspingAppendage=["fist","claw"].includes(this.baseType??"")?!0:this.category==="unarmed"||this.traits.includes("unarmed")?!!this.graspingAppendage:!1}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),category:new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.weaponCategories,initial:"unarmed"}),group:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.weaponGroups,initial:null}),baseType:new fields2.StringField({required:!0,nullable:!0,blank:!1,choices:CONFIG.PF2E.baseWeaponTypes,initial:null}),traits:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.npcAttackTraits})),traitToggles:new fields2.SchemaField({modular:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null}),versatile:new fields2.StringField({required:!0,blank:!1,nullable:!0,choices:CONFIG.PF2E.damageTypes,initial:null})},{required:!0,nullable:!1,initial:{modular:null,versatile:null}}),otherTags:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:CONFIG.PF2E.otherWeaponTags}),{required:!1,nullable:!1,initial:[]}),range:new fields2.SchemaField({increment:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:5}),max:new fields2.NumberField({required:!1,integer:!0,min:5,nullable:!0,initial:null})},{required:!1,nullable:!0,initial:null}),damage:new fields2.SchemaField({base:new fields2.SchemaField({damageType:new fields2.StringField({required:!0,blank:!1,initial:"bludgeoning"}),dice:new ResolvableValueField({required:!0,nullable:!1,initial:1}),die:new fields2.StringField({required:!0,choices:CONFIG.PF2E.damageDie,initial:"d4"}),modifier:new fields2.NumberField({nullable:!1,integer:!0,initial:0})})}),img:new fields2.FilePathField({categories:["IMAGE"],nullable:!1,initial:()=>"systems/pf2e/icons/default-icons/melee.svg"}),attackModifier:new fields2.NumberField({integer:!0,positive:!0,nullable:!0,initial:null}),replaceAll:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),replaceBasicUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),battleForm:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),ability:new fields2.StringField({required:!1,blank:!1,choices:CONFIG.PF2E.abilities,nullable:!0,initial:null}),options:new fields2.ArrayField(new fields2.StringField,{required:!1,initial:void 0}),fist:new fields2.BooleanField({required:!1,nullable:!1,initial:void 0}),graspingAppendage:new StrictBooleanField({required:!1,nullable:!1,initial:void 0})}}validate(options){return(options?.changes??this._source).fist===!0?!0:super.validate(options)}_initializeSource(source,options){return"fist"in source&&source.fist===!0?source:super._initializeSource(source,options)}_initialize(options){this._source.fist?(this.key="Strike",this.priority=99,this.slug="fist",this.img=this._source.img,this.category="unarmed",this.group="brawling",this.baseType="fist",this.traits=["agile","finesse","nonlethal"],this.traitToggles=foundry.utils.mergeObject({modular:null,versatile:null},this._source.traitToggles??{}),this.otherTags=[],this.range=null,this.damage={base:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0}},this.battleForm=!1,this.fist=!0,this.graspingAppendage=!0,this.replaceAll=!1,this.replaceBasicUnarmed=!1,this.predicate=new PredicatePF2e(Array.isArray(this._source.predicate)?this._source.predicate:[])):super._initialize(options)}beforePrepareData(){if(this.ignored)return;const predicatePassed=this.predicate.length===0||(()=>{const rollOptions=new Set(this.actor.getRollOptions(["attack","attack-roll","strike-attack-roll"]));return this.resolveInjectedProperties(this.predicate).test(rollOptions)})(),damageType=this.resolveInjectedProperties(this.damage.base.damageType);if(!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.failValidation("Unrecognized damage type");const dice=(()=>{const resolvedDice=Number(this.resolveValue(this.damage.base.dice));return Math.clamped(Math.trunc(resolvedDice),0,8)})();if(Number.isNaN(dice))return this.failValidation("dice does not resolve to a number");if(predicatePassed){const weapon=this.#constructWeapon(damageType,dice),slug=weapon.slug??sluggify(weapon.name);this.actor.synthetics.strikes.set(slug,weapon)}}afterPrepareData(){if(!(this.ignored||!this.actor.isOfType("character")))if(this.replaceAll){const systemData=this.actor.system;systemData.actions=systemData.actions.filter(a=>a.item.id===this.item.id&&a.item.name===this.label&&a.item.group===this.group)}else this.replaceBasicUnarmed&&this.actor.system.actions.findSplice(a=>a.item?.slug==="basic-unarmed")}#constructWeapon(damageType,dice){const actorIsNPC=this.actor.isOfType("npc"),source=foundry.utils.deepClone({_id:this.item.id,name:this.label,type:"weapon",img:this.img,flags:{pf2e:{battleForm:this.battleForm,fixedAttack:actorIsNPC?this.attackModifier??null:null}},system:{slug:this.slug,description:{value:""},category:this.category,group:this.group,baseItem:this.baseType,attribute:this.ability,bonus:{value:actorIsNPC?this.attackModifier??0:0},damage:{...this.damage.base,dice,damageType},range:this.range?.increment??null,maxRange:this.range?.max??null,traits:{value:this.traits,otherTags:this.otherTags,rarity:"common",toggles:{modular:{selection:this.traitToggles.modular},versatile:{selection:this.traitToggles.versatile}}},options:{value:this.options},usage:{value:"held-in-one-hand"},equipped:{carryType:"held",handsHeld:1},graspingAppendage:this.graspingAppendage}});return new WeaponPF2e(source,{parent:this.actor})}async toggleTrait({trait,selection}){const ruleSources=foundry.utils.deepClone(this.item._source.system.rules),rule=ruleSources.at(this.sourceIndex??NaN);rule?.key==="Strike"&&(rule.traitToggles={...this.traitToggles,[trait]:selection},await this.item.update({"system.rules":ruleSources}))}}class TempHPRuleElement extends RuleElementPF2e{static{__name(this,"TempHPRuleElement")}static{__name2(this,"TempHPRuleElement")}static validActorTypes=["character","npc","familiar"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),events:new StrictSchemaField({onCreate:new fields2.BooleanField({required:!1,nullable:!1}),onTurnStart:new fields2.BooleanField({required:!1,nullable:!1})},{required:!0,nullable:!1,initial:{onCreate:!0,onTurnStart:!1}})}}onCreate(actorUpdates){if(this.ignored||!this.events.onCreate)return;const updatedActorData=foundry.utils.mergeObject(this.actor._source,actorUpdates,{inplace:!1}),value=Math.trunc(Number(this.resolveValue(this.value))),rollOptions=Array.from(new Set([...this.actor.getRollOptions(),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;if(Number.isNaN(value)||value<0)return this.failValidation("value: must resolve to a positive number");const currentTempHP=Number(foundry.utils.getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(foundry.utils.mergeObject(actorUpdates,{"system.attributes.hp.temp":value,"system.attributes.hp.tempsource":this.item.id}),this.broadcast(value,currentTempHP))}onTurnStart(actorUpdates){if(this.ignored||!this.events.onTurnStart)return;const rollOptions=Array.from(new Set([...this.actor.getRollOptions(["all"]),...this.actor.itemTypes.weapon.flatMap(w=>w.isEquipped?w.getRollOptions("self:weapon"):[])]));if(!this.test(rollOptions))return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("value: must resolve to a number");const updatedActorData=foundry.utils.mergeObject(this.actor._source,actorUpdates,{inplace:!1}),currentTempHP=Number(foundry.utils.getProperty(updatedActorData,"system.attributes.hp.temp"))||0;value>currentTempHP&&(actorUpdates["system.attributes.hp.temp"]=value,this.broadcast(value,currentTempHP))}onDelete(actorUpdates){const updatedActorData=foundry.utils.mergeObject(this.actor._source,actorUpdates,{inplace:!1});if(foundry.utils.getProperty(updatedActorData,"system.attributes.hp.tempsource")===this.item.id){foundry.utils.mergeObject(actorUpdates,{"system.attributes.hp.temp":0});const hpData=foundry.utils.getProperty(actorUpdates,"system.attributes.hp");isObject(hpData)&&(hpData["-=tempsource"]=null)}}broadcast(newQuantity,oldQuantity){const singularOrPlural=newQuantity===1?"PF2E.Encounter.Broadcast.TempHP.SingleNew":"PF2E.Encounter.Broadcast.TempHP.PluralNew",wasAt=oldQuantity>0?game.i18n.format("PF2E.Encounter.Broadcast.TempHP.WasAt",{oldQuantity}):"",[actor,item]=[this.actor.name,this.item.name],content=game.i18n.format(singularOrPlural,{actor,newQuantity,wasAt,item}),recipients=game.users.filter(u=>this.actor.testUserPermission(u,"OWNER")).map(u=>u.id),speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({content,speaker,whisper:recipients})}}class BattleFormRuleElement extends RuleElementPF2e{static{__name(this,"BattleFormRuleElement")}static{__name2(this,"BattleFormRuleElement")}modifierLabel;static validActorTypes=["character"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!1,initial:void 0}),overrides:new fields2.SchemaField({traits:new fields2.ArrayField(new fields2.StringField),armorClass:new fields2.SchemaField({modifier:new ResolvableValueField({required:!1,nullable:!1,initial:0}),ignoreCheckPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0}),ignoreSpeedPenalty:new fields2.BooleanField({required:!1,nullable:!1,initial:!0})},{required:!1,initial:void 0}),tempHP:new ResolvableValueField({required:!1,nullable:!0,initial:null}),senses:new RecordField(new fields2.StringField({required:!0,blank:!1,choices:[...SENSE_TYPES]}),new fields2.SchemaField({acuity:new fields2.StringField({choices:SENSE_ACUITIES,required:!1,blank:!1,initial:void 0}),range:new fields2.NumberField({required:!1,nullable:!0,initial:void 0})}),{required:!1,initial:void 0}),size:new fields2.StringField({required:!1,blank:!1,initial:void 0}),speeds:new fields2.ObjectField({required:!1,initial:void 0}),skills:new fields2.ObjectField({required:!1,initial:void 0}),strikes:new fields2.ObjectField({required:!1}),immunities:new fields2.ArrayField(new fields2.ObjectField),weaknesses:new fields2.ArrayField(new fields2.ObjectField),resistances:new fields2.ArrayField(new fields2.ObjectField)},{required:!0,nullable:!1}),ownUnarmed:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canCast:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),canSpeak:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),hasHands:new fields2.BooleanField({required:!1,nullable:!1,initial:!1})}}constructor(data,options){super(data,options),this.overrides=this.resolveValue(this.value,this.overrides),this.modifierLabel=this.getReducedLabel()}static#defaultIcons=["antler","beak","body","bone-shard","branch","claw","cube-face","fangs","fire-mote","fist","foot","foreleg","gust","horn","jaws","lighting-lash","mandibles","piercing-hymn","pincer","pseudopod","rock","spikes","stinger","tail","talon","tendril","tentacle","tongue","trunk","tusk","vine","water-spout","wave","wing"].reduce((accumulated,slug)=>{const path=slug==="fist"?"icons/skills/melee/unarmed-punch-fist.webp":`systems/pf2e/icons/unarmed-attacks/${slug}.webp`;return{...accumulated,[slug]:path}},{});async preCreate({itemSource,ruleSource}){if(!this.test()){ruleSource.ignored=!0;return}const rules=itemSource.system?.rules??[];for(const rule of rules)if(["DamageDice","FlatModifier","Note"].includes(String(rule.key))){const predicate=rule.predicate??=[];Array.isArray(predicate)&&predicate.push("battle-form")}await this.#resolveStrikeQueries(ruleSource)}onCreate(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onCreate(actorUpdates)}beforePrepareData(){if(this.ignored)return;const{actor}=this,{attributes}=actor;if(attributes.polymorphed){actor.synthetics.preparationWarnings.add("PF2e System | You are already under a polymorph effect"),this.ignored=!0;return}attributes.polymorphed=!0,attributes.battleForm=!0,this.#setRollOptions(),this.#prepareSenses();for(const trait of this.overrides.traits){const currentTraits=actor.system.traits;currentTraits.value.includes(trait)||currentTraits.value.push(trait)}if(this.overrides.armorClass?.ignoreSpeedPenalty){const speedRollOptions=actor.rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}}afterPrepareData(){if(this.ignored)return;this.#prepareAC(),this.#prepareSize(),this.#prepareSkills(),this.#prepareSpeeds(),this.#prepareStrikes(),this.#prepareIWR();const initiativeSkill=this.actor.system.attributes.initiative?.statistic||"perception";this.actor.initiative=new ActorInitiative(this.actor,{statistic:initiativeSkill}),this.actor.system.attributes.initiative=this.actor.initiative.getTraceData()}onDelete(actorUpdates){if(this.ignored)return;const tempHP=this.overrides.tempHP;tempHP&&new TempHPRuleElement({key:"TempHP",label:this.label,value:tempHP},{parent:this.item}).onDelete(actorUpdates)}#setRollOptions(){const{attributes,rollOptions}=this.actor;if(rollOptions.all.polymorph=!0,rollOptions.all["battle-form"]=!0,this.overrides.armorClass&&(rollOptions.all["armor:ignore-check-penalty"]=this.overrides.armorClass.ignoreCheckPenalty,rollOptions.all["armor:ignore-speed-penalty"]=this.overrides.armorClass.ignoreSpeedPenalty,this.overrides.armorClass.ignoreSpeedPenalty)){const speedRollOptions=rollOptions.speed??={};speedRollOptions["armor:ignore-speed-penalty"]=!0}if(this.overrides.skills)for(const key of SKILL_ABBREVIATIONS){if(!(key in this.overrides.skills))continue;const longForm=SKILL_DICTIONARY[key];rollOptions.all[`battle-form:${longForm}`]=!0}attributes.handsFree=Math.max(Object.values(this.overrides.strikes??{}).reduce((count,s)=>s.category==="unarmed"?count:count-1,2),0);for(const num of[0,1,2])attributes.handsFree===num?rollOptions.all[`hands-free:${num}`]=!0:delete rollOptions.all[`hands-free:${num}`]}#prepareAC(){const overrides=this.overrides,{actor}=this,{armorClass}=actor;if(!(Number(this.resolveValue(overrides.armorClass?.modifier,armorClass.value))||0))return;this.#suppressModifiers(armorClass);const newModifier=(Number(this.resolveValue(overrides.armorClass?.modifier))||0)-10;armorClass.modifiers.push(new ModifierPF2e(this.modifierLabel,newModifier,"untyped")),this.actor.system.attributes.ac=armorClass.parent.getTraceData()}#prepareSenses(){for(const senseType of SENSE_TYPES){const newSense=this.overrides.senses?.[senseType];if(!newSense)continue;newSense.acuity??="precise";const ruleData={key:"Sense",selector:senseType,force:!0,...newSense};new SenseRuleElement(ruleData,{parent:this.item}).beforePrepareData()}}#prepareSize(){if(!this.overrides.size)return;const ruleData={key:"CreatureSize",label:this.label,value:this.overrides.size};new CreatureSizeRuleElement(ruleData,{parent:this.item}).beforePrepareData()}#prepareSpeeds(){const{attributes}=this.actor,currentSpeeds=attributes.speed;for(const movementType of MOVEMENT_TYPES){const speedOverride=this.overrides.speeds?.[movementType];if(typeof speedOverride=="number")if(movementType==="land")this.#suppressModifiers(attributes.speed),attributes.speed.value=speedOverride;else{const{otherSpeeds}=currentSpeeds,label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]);otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push({type:movementType,label,value:speedOverride});const newSpeed=this.actor.prepareSpeed(movementType);if(!newSpeed)throw ErrorPF2e("Unexpected failure retrieving movement type");this.#suppressModifiers(newSpeed),otherSpeeds.findSplice(s=>s.type===movementType),otherSpeeds.push(newSpeed)}}}#prepareSkills(){for(const[skillShort,newSkill]of Object.entries(this.overrides.skills??{})){if(!setHasElement(SKILL_ABBREVIATIONS,skillShort))return this.failValidation(`Unrecognized skill abbreviation: ${skillShort}`);newSkill.ownIfHigher??=!0;const key=SKILL_DICTIONARY[skillShort],currentSkill=this.actor.skills[key],newModifier=Number(this.resolveValue(newSkill.modifier))||0;if(currentSkill.mod>newModifier&&newSkill.ownIfHigher)continue;const baseMod=new ModifierPF2e({label:this.modifierLabel,slug:"battle-form",modifier:newModifier,type:"untyped"});this.actor.skills[key]=currentSkill.extend({modifiers:[baseMod],filter:this.#filterModifier}),this.actor.system.skills[skillShort]=foundry.utils.mergeObject(this.actor.system.skills[skillShort],this.actor.skills[key].getTraceData())}}#prepareStrikes(){const{synthetics}=this.actor,strikes=this.overrides.strikes??{};for(const strike of Object.values(strikes))strike.ownIfHigher??=!0;const ruleData=Object.entries(strikes).map(([slug,strikeData])=>({key:"Strike",label:game.i18n.localize(strikeData.label)??`PF2E.BattleForm.Attack.${sluggify(slug,{camel:"bactrian"})}`,slug,predicate:strikeData.predicate??[],img:strikeData.img??BattleFormRuleElement.#defaultIcons[slug]??this.item.img,category:strikeData.category,group:strikeData.group,baseItem:strikeData.baseType,options:[slug],damage:{base:strikeData.damage},range:{increment:strikeData.range??null,max:strikeData.maxRange??null},traits:strikeData.traits??[],ability:strikeData.ability,battleForm:!0}));if(this.ownUnarmed){for(const[slug,weapon]of synthetics.strikes.entries())weapon.category!=="unarmed"&&synthetics.strikes.delete(slug);this.actor.rollOptions.all["battle-form:own-attack-modifier"]=!0}else{for(const[slug,strike]of synthetics.strikes.entries())strike.flags.pf2e.battleForm||synthetics.strikes.delete(slug);for(const striking of Object.values(synthetics.striking).flat())(striking.predicate??=new PredicatePF2e).push({not:"battle-form"});for(const datum of ruleData)datum.traits.includes("magical")||datum.traits.push("magical"),new StrikeRuleElement(datum,{parent:this.item}).beforePrepareData()}this.actor.system.actions=this.actor.prepareStrikes({includeBasicUnarmed:this.ownUnarmed}).filter(a=>a.slug&&a.slug in strikes||this.ownUnarmed&&a.item.category==="unarmed");const strikeActions=this.actor.system.actions.flatMap(s=>[s,...s.altUsages]);for(const action2 of strikeActions){const strike=strikes[action2.slug??""]??null;if(!this.ownUnarmed&&strike&&(Number(this.resolveValue(strike.modifier))>=action2.totalModifier||!strike.ownIfHigher)){this.#suppressModifiers(action2),this.#suppressNotes(Object.entries(synthetics.rollNotes).flatMap(([key,note])=>/\bdamage\b/.test(key)?note:[]));const baseModifier=Number(this.resolveValue(strike.modifier))||0;action2.unshift(new ModifierPF2e(this.modifierLabel,baseModifier,"untyped"))}else{const options=this.actor.rollOptions["strike-attack-roll"]??={};options["battle-form:own-attack-modifier"]=!0,action2.calculateTotal(new Set(this.actor.getRollOptions(action2.domains)))}}}#prepareIWR(){for(const immunity of this.overrides.immunities)new ImmunityRuleElement({key:"Immunity",...immunity},{parent:this.item}).afterPrepareData();for(const weakness of this.overrides.weaknesses){const args={key:"Weakness",...weakness,override:!0};new WeaknessRuleElement(args,{parent:this.item}).afterPrepareData()}for(const resistance of this.overrides.resistances){const args={key:"Resistance",...resistance,override:!0};new ResistanceRuleElement(args,{parent:this.item}).afterPrepareData()}}#suppressModifiers(statistic){for(const modifier of statistic.modifiers)this.#filterModifier(modifier)||(modifier.adjustments.push({slug:null,test:()=>!0,suppress:!0}),modifier.ignored=!0,modifier.enabled=!1);statistic instanceof StatisticModifier&&statistic.calculateTotal()}#filterModifier(modifier){return modifier.slug==="battle-form"?!0:modifier.type==="ability"?!1:["status","circumstance"].includes(modifier.type)||modifier.modifier<0}#suppressNotes(notes){for(const note of notes)note.predicate.includes("battle-form")||(note.predicate=note.predicate instanceof PredicatePF2e?note.predicate:new PredicatePF2e(note.predicate),note.predicate.push({not:"battle-form"}))}applyDamageExclusion(weapon,modifiers){if(!this.ownUnarmed)for(const modifier of modifiers){if(modifier.predicate.some(s=>s instanceof Object&&"not"in s&&s.not==="battle-form"))continue;const isNumericBonus=modifier instanceof ModifierPF2e&&modifier.modifier>=0,isAbilityModifier=modifier instanceof ModifierPF2e&&modifier.type==="ability",isExtraDice=modifier instanceof DamageDicePF2e,isStatusOrCircumstance=isNumericBonus&&["status","circumstance"].includes(modifier.type),isDamageTrait=isExtraDice&&/^(?:deadly|fatal)-\d?d\d{1,2}$/.test(modifier.slug)&&tupleHasValue(this.overrides?.strikes?.[weapon.slug??""]?.traits??[],modifier.slug),isBattleFormModifier=!!(modifier.predicate.includes("battle-form")||modifier.predicate.some(s=>s instanceof Object&&"or"in s&&s.or.includes("battle-form"))||isDamageTrait);(isNumericBonus||isAbilityModifier||isExtraDice)&&!isStatusOrCircumstance&&!isBattleFormModifier&&(modifier.enabled=!1,modifier.ignored=!0,modifier.predicate.push({not:"battle-form"}))}}async#resolveStrikeQueries(ruleSource){const value=ruleSource.overrides?ruleSource.overrides:ruleSource.value??={};if(!__name2(v=>isObject(v)&&isObject(v.strikes),"hasStrikes")(value))return;const isStrikeQuery=__name2(maybeQuery=>isObject(maybeQuery)?typeof maybeQuery.query=="string"&&typeof maybeQuery.modifier=="number":!1,"isStrikeQuery");for(const[slug,strike]of Object.entries(value.strikes)){if(!isStrikeQuery(strike))continue;strike.pack=String(strike.pack??"pf2e.equipment-srd"),strike.ownIfHigher=!!(strike.ownIfHigher??!0);const queryObject=(()=>{try{const parsed=JSON.parse(String(this.resolveInjectedProperties(strike.query)));if(!isObject(parsed)||Array.isArray(parsed))throw Error("A strike query must be an NeDB query object");return parsed}catch(error){return error instanceof Error&&this.failValidation(error.message),ruleSource.ignored=!0,null}})();if(!queryObject){this.failValidation("Malformed query object");break}const weapon=(await game.packs.get(strike.pack)?.getDocuments(queryObject))?.[0];if(!(weapon instanceof WeaponPF2e)){this.failValidation("Failed to retrieve queried weapon");break}const resolved={label:weapon.name,img:weapon.img,ability:weapon.isRanged||weapon.traits.has("finesse")?"dex":"str",category:weapon.category,group:weapon.group,baseType:weapon.baseType,traits:foundry.utils.deepClone(weapon.system.traits.value),modifier:strike.modifier,damage:foundry.utils.deepClone(weapon.system.damage),ownIfHigher:strike.ownIfHigher};value.strikes[slug]=resolved}}}class PickAThingPrompt extends Application{static{__name(this,"PickAThingPrompt")}static{__name2(this,"PickAThingPrompt")}item;#resolve;selection=null;choices=[];selectMenu;predicate;allowNoSelection;constructor(data){super(),this.item=data.item,this.predicate=data.predicate??new PredicatePF2e,this.options.title=data.title??this.item.name,this.allowNoSelection=data.allowNoSelection??!1}get actor(){return this.item.actor}static get defaultOptions(){return{...super.defaultOptions,classes:["pick-a-thing-prompt"],resizable:!1,height:"auto",width:"auto"}}getChoices(){return this.choices.filter(choice=>this.predicate.test(choice.domain??[]))??[]}getSelection(event2){if(!(event2.currentTarget instanceof HTMLElement))throw ErrorPF2e("Unexpected error retrieving form data");const selectedIndex=(event2.currentTarget.closest(".choice")?.querySelector("button[data-action=pick]")??event2.currentTarget.closest(".content")?.querySelector("tag")??event2.currentTarget).getAttribute("value");return["",null].includes(selectedIndex)||!Number.isInteger(Number(selectedIndex))?null:this.choices.at(Number(selectedIndex))??null}async resolveSelection(){return this.choices=this.getChoices(),this.render(!0),new Promise(resolve=>{this.#resolve=resolve})}async getData(options={}){const slug=this.item.slug??sluggify(this.item.name);return options.id=`pick-a-${slug}`,{selectMenu:this.choices.length>9,choices:this.choices.map((c,index)=>({...c,value:index}))}}activateListeners($html){const html=$html[0];for(const element of htmlQueryAll(html,"a[data-choice], button[data-action=pick]"))element.addEventListener("click",event2=>{this.selection=this.getSelection(event2)??null,this.close()});const select=htmlQuery(html,"input[data-tagify-select]");select&&(this.selectMenu=new Tagify(select,{enforceWhitelist:!0,keepInvalidTags:!1,mode:"select",tagTextProp:"label",dropdown:{closeOnSelect:!0,enabled:1,highlightFirst:!0,mapValueTo:"label",maxItems:this.choices.length,searchKeys:["label"]},whitelist:this.choices.map((c,index)=>({value:index.toString(),label:c.label}))}),this.selectMenu.DOM.input.spellcheck=!1)}async close(options){for(const element of htmlQueryAll(this.element[0],"button, select"))element.style.pointerEvents="none";return this.choices.length===0?ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoValidOptions",{actor:this.actor.name,item:this.item.name})):!this.selection&&!this.allowNoSelection&&ui.notifications.warn(game.i18n.format("PF2E.UI.RuleElements.Prompt.NoSelectionMade",{item:this.item.name})),this.#resolve?.(this.selection),super.close(options)}}class ChoiceSetPrompt extends PickAThingPrompt{static{__name(this,"ChoiceSetPrompt")}static{__name2(this,"ChoiceSetPrompt")}prompt;containsItems;allowedDrops;constructor(data){super(data),this.prompt=data.prompt,this.choices=data.choices??[],this.containsItems=data.containsItems,this.allowedDrops=this.containsItems?data.allowedDrops:null}static get defaultOptions(){return{...super.defaultOptions,classes:["choice-set-prompt"],dragDrop:[{dropSelector:".drop-zone"}],template:"systems/pf2e/templates/system/rules-elements/choice-set-prompt.hbs"}}async getData(options={}){return{...await super.getData(options),choices:this.choices.map((c,index)=>({...c,value:index,hasUUID:UUIDUtils.isItemUUID(c.value)})),prompt:this.prompt,includeDropZone:!!this.allowedDrops,allowNoSelection:this.allowNoSelection,selectMenu:this.choices.length>9,containsItems:this.containsItems}}getChoices(){return this.choices}setChoices(choices){this.choices=choices}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=close]")?.addEventListener("click",()=>{this.close()});const renderItemSheet=__name2(async choice=>{if(!choice||!UUIDUtils.isItemUUID(choice.value))return;(await fromUuid(choice.value))?.sheet.render(!0)},"renderItemSheet");if(this.containsItems)if(this.selectMenu){const itemInfoAnchor=htmlQuery(html,"a.item-info");if(!itemInfoAnchor)return;const updateAnchor=__name2((disable,value="")=>{itemInfoAnchor.dataset.value=value,itemInfoAnchor.classList.toggle("disabled",disable),itemInfoAnchor.dataset.tooltip=game.i18n.localize(disable?"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Disabled":"PF2E.UI.RuleElements.ChoiceSet.ViewItem.Tooltip")},"updateAnchor");itemInfoAnchor.addEventListener("click",event2=>{renderItemSheet(this.getSelection(event2))}),this.selectMenu.on("change",event2=>{const data=event2.detail.tagify.value.at(0);if(!data)return updateAnchor(!0);const index=Number(data.value);if(!isNaN(index)){const choice=this.choices.at(index);UUIDUtils.isItemUUID(choice?.value)?updateAnchor(!1,data.value):updateAnchor(!0)}})}else for(const anchor of htmlQueryAll(html,"a.item-info"))anchor.addEventListener("click",event2=>{renderItemSheet(this.getSelection(event2))})}async resolveSelection(){const firstChoice=this.choices.at(0);return!this.allowedDrops&&firstChoice&&this.choices.length===1?this.selection=firstChoice:this.choices.length===0&&!this.allowedDrops?(this.close({force:!0}),null):super.resolveSelection()}async _onDrop(event2){event2.preventDefault();const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");if(dropData?.type!=="Item"){ui.notifications.error("Only an item can be dropped here.");return}const droppedItem=await ItemPF2e.fromDropData(dropData);if(!droppedItem)throw ErrorPF2e("Unexpected error resolving drop");const isAllowedDrop=!!this.allowedDrops?.predicate.test(droppedItem.getRollOptions("item"));if(this.allowedDrops&&!isAllowedDrop){ui.notifications.error(game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:droppedItem.name,goodType:game.i18n.localize(this.allowedDrops.label??"")}));return}const newChoice={value:this.containsItems&&this.choices.length>0&&this.choices.every(c=>!UUIDUtils.isItemUUID(c.value))?droppedItem.slug??sluggify(droppedItem.id):droppedItem.uuid,label:droppedItem.name},choicesLength=this.choices.push(newChoice),prompt=document.querySelector(`#${this.id}`),dropZone=prompt?.querySelector(".drop-zone");if(!prompt)throw ErrorPF2e("Unexpected error retrieving ChoiceSet dialog");if(prompt.style.height="unset",this.selectMenu){const{whitelist}=this.selectMenu.settings,menuChoice={value:String(choicesLength-1),label:newChoice.label};whitelist?.push(menuChoice.value),this.selectMenu.setPersistedData(whitelist,"whitelist"),this.selectMenu.addTags([menuChoice],!0,!0),this.selectMenu.setReadonly(!0),dropZone?.remove()}else{const img=document.createElement("img");img.src=droppedItem.img;const newButton=createHTMLElement("button",{classes:["with-image"],children:[img,createHTMLElement("span",{children:[droppedItem.name]})]});newButton.type="button",newButton.value=String(choicesLength-1),newButton.addEventListener("click",event22=>{this.selection=this.getSelection(event22)??null,this.close()}),dropZone?.replaceWith(newButton)}}_canDragDrop(){return this.actor.isOwner}}class ChoiceSetRuleElement extends RuleElementPF2e{static{__name(this,"ChoiceSetRuleElement")}static{__name2(this,"ChoiceSetRuleElement")}containsItems=!1;selection;constructor(data,options){if(super(data,options),this.allowedDrops??=null,this.allowNoSelection??=!1,this.rollOption??=this.slug,this.flag=this.#setDefaultFlag(this),this.selection=typeof data.selection=="string"||typeof data.selection=="number"||isObject$1(data.selection)?data.selection:null,isObject$1(this.choices)&&!Array.isArray(this.choices)&&!("filter"in this.choices)&&(this.choices.predicate=new PredicatePF2e(this.choices.predicate??[]),this.choices.unarmedAttacks&&this.choices.predicate.push("item:category:unarmed")),this.item.flags.pf2e.rulesSelections[this.flag]=this.selection,this.selection!==null)this.#setRollOption(this.selection);else if(!this.allowNoSelection&&this.test()){this.ignored=!0;for(const ruleData of this.item.system.rules)ruleData.ignored=!0}}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),choices:new DataUnionField([new StrictArrayField(new StrictObjectField({required:!0,nullable:!1,initial:void 0}),{required:!0,nullable:!1,initial:void 0}),new StrictObjectField({required:!0,nullable:!1,initial:void 0}),new StrictStringField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:void 0}),prompt:new fields2.StringField({required:!1,blank:!1,nullable:!1,initial:"PF2E.UI.RuleElements.ChoiceSet.Prompt"}),adjustName:new DataUnionField([new StrictBooleanField({required:!0,nullable:!1,initial:void 0}),new StrictStringField({required:!0,nullable:!1,initial:void 0})],{required:!0,nullable:!1,initial:!0}),allowedDrops:new fields2.SchemaField({label:new fields2.StringField({required:!0,blank:!1,nullable:!0,initial:null}),predicate:new PredicateField},{required:!1,nullable:!0,initial:void 0}),flag:new fields2.StringField({required:!1,blank:!1,nullable:!1,initial:void 0}),rollOption:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),allowNoSelection:new StrictBooleanField({required:!1,nullable:!1,initial:void 0})}}async preCreate({itemSource,ruleSource,tempItems}){if(this.selection===null&&isObject$1(this.choices)&&"query"in this.choices){this.failValidation("As of FVTT version 11, choice set queries are no longer supported.");for(const ruleData of this.item.system.rules)ruleData.ignored=!0;return}const rollOptions=new Set([this.actor.getRollOptions(),this.item.getRollOptions("parent")].flat());if(!this.resolveInjectedProperties(this.predicate).test(rollOptions))return;if(isObject$1(this.choices)){const{choices}=this;if("ownedItems"in choices&&choices.ownedItems&&!choices.types?.length){console.warn("PF2E System | Failure during ChoiceSet preCreate: `types` is required if `ownedItems` is set"),ruleSource.ignored=!0;return}}this.#setDefaultFlag(ruleSource);const inflatedChoices=await this.inflateChoices(rollOptions,tempItems),selection=this.#getPreselection()??await new ChoiceSetPrompt({prompt:this.prompt,item:this.item,title:this.label,choices:inflatedChoices,containsItems:this.containsItems,allowedDrops:this.allowedDrops,allowNoSelection:this.allowNoSelection}).resolveSelection();if(selection){if(ruleSource.selection=selection.value,this.adjustName){const itemName=itemSource.name,label=game.i18n.localize(selection.label);if(this.adjustName===!0){const newName=`${itemName} (${label})`,pattern=(()=>{const escaped=RegExp.escape(label);return new RegExp(`\\(${escaped}\\) \\(${escaped}\\)$`)})();itemSource.name=newName.replace(pattern,`(${label})`)}else itemSource.name=game.i18n.format(this.adjustName,{[this.flag]:game.i18n.localize(selection.label)})}if(this.item.flags.pf2e.rulesSelections[this.flag]=selection.value,typeof ruleSource.rollOption=="string"&&UUIDUtils.isItemUUID(selection.value)){const item=await fromUuid(selection.value);if(item instanceof ItemPF2e){const slug=item.slug??sluggify(item.name);this.rollOption=ruleSource.rollOption=`${ruleSource.rollOption}:${slug}`}}this.#setRollOption(ruleSource.selection);for(const rule of this.item.rules)rule.ignored=!1}else ruleSource.ignored=!0}#setDefaultFlag(source){return source.flag=typeof source.flag=="string"&&source.flag.length>0?source.flag.replace(/[^-a-z0-9]/gi,""):sluggify(this.slug??this.item.slug??this.item.name,{camel:"dromedary"})}async inflateChoices(rollOptions,tempItems){const choices=Array.isArray(this.choices)?this.#choicesFromArray(this.choices,rollOptions):isObject$1(this.choices)?this.choices.ownedItems?this.#choicesFromOwnedItems(this.choices,rollOptions,tempItems):this.choices.attacks||this.choices.unarmedAttacks?this.#choicesFromAttacks(new PredicatePF2e(this.resolveInjectedProperties(this.choices.predicate)),rollOptions):"filter"in this.choices&&Array.isArray(this.choices.filter)?await this.queryCompendium(this.choices,rollOptions,tempItems):[]:typeof this.choices=="string"?this.#choicesFromPath(this.choices):[],choicesAreUUIDs=choices.every(c=>UUIDUtils.isItemUUID(c.value));if(choicesAreUUIDs){const itemChoices=await UUIDUtils.fromUUIDs(choices.map(c=>c.value));for(let i=0;i<choices.length;i++){const item=itemChoices[i];item instanceof ItemPF2e&&(choices[i].label??=item.name,choices[i].img??=item.img)}}(choicesAreUUIDs||isObject$1(this.choices)&&"query"in this.choices)&&(this.containsItems=!0);try{const choiceData=choices.map(c=>({value:c.value,label:game.i18n.localize(c.label),img:c.img}));return Array.isArray(this.choices)||choiceData.sort((a,b)=>a.label.localeCompare(b.label)),choiceData}catch{return[]}}#choicesFromArray(choices,actorRollOptions){return choices.filter(c=>this.resolveInjectedProperties(new PredicatePF2e(c.predicate??[])).test(actorRollOptions))}#choicesFromPath(path){const choiceObject=foundry.utils.getProperty(CONFIG.PF2E,path)??foundry.utils.getProperty(this.actor,path)??{};return Array.isArray(choiceObject)&&choiceObject.every(c=>isObject$1(c)&&typeof c.value=="string")?choiceObject:isObject$1(choiceObject)&&Object.values(choiceObject).every(c=>typeof c=="string")?Object.entries(choiceObject).map(([value,label])=>({value,label:String(label)})):[]}#choicesFromOwnedItems(options,actorRollOptions,tempItems){const{includeHandwraps,types}=options,predicate=new PredicatePF2e(this.resolveInjectedProperties(options.predicate)),choices=this.actor.items.filter(i=>i.isOfType(...types)&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).filter(i=>!i.isOfType("weapon")||i.category!=="unarmed").map(i=>({img:i.img,label:i.name,value:i.id}));return includeHandwraps&&choices.push(...this.actor.itemTypes.weapon.filter(i=>i.slug==="handwraps-of-mighty-blows"&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).map(h=>({img:h.img,label:h.name,value:"unarmed"}))),choices.push(...tempItems.filter(i=>i.isOfType(...types)&&predicate.test([...actorRollOptions,...i.getRollOptions("item")])).filter(i=>!i.isOfType("weapon")||i.category!=="unarmed").map(i=>({img:i.img,label:i.name,value:i.id}))),choices}#choicesFromAttacks(predicate,actorRollOptions){return this.actor.isOfType("character","npc")?this.actor.system.actions.filter(a=>a.item.isOfType("melee","weapon")&&predicate.test([...actorRollOptions,...a.item.getRollOptions("item")])).map(a=>({img:a.item.img,label:a.item.name,value:a.item.slug??sluggify(a.item.name)})):[]}async queryCompendium(choices,actorRollOptions,tempItems){const filter2=Array.isArray(choices.filter)?new PredicatePF2e(this.resolveInjectedProperties(choices.filter)):new PredicatePF2e;if(!filter2.isValid||filter2.length===0)return this.failValidation("`filter` must be an array with at least one statement"),[];const itemType=objectHasKey(CONFIG.PF2E.Item.documentClasses,choices.itemType)?choices.itemType:"feat",packs=typeof choices.pack=="string"?compact([game.packs.get(choices.pack)]):game.packs.filter(p=>p.metadata.type==="Item"&&p.index.some(e=>e.type===itemType)),progress=new Progress({max:packs.length}),localize=localizer("PF2E.ProgressBar"),indexData=[];for(const pack of packs)progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),indexData.push(await pack.getIndex({fields:["flags","system.ancestry","system.baseItem","system.category","system.group","system.level","system.maxTakable","system.potencyRune","system.sanctification","system.slug","system.traits"]}));progress.close({label:localize("LoadingComplete")});const filteredItems=indexData.flatMap(d=>d.contents).filter(s=>s.type===itemType).map(source=>{const parsedUUID=foundry.utils.parseUuid(source.uuid),pack=parsedUUID.collection instanceof CompendiumCollection?parsedUUID.collection.metadata.id:null;return new ItemProxyPF2e(foundry.utils.deepClone(source),{pack})}).concat(game.items.filter(i=>i.type===itemType)).filter(i=>filter2.test([...i.getRollOptions("item"),...actorRollOptions])),existing=new Map;for(const feat of this.actor.itemTypes.feat){const slug=feat.slug??sluggify(feat.name);existing.set(slug,(existing.get(slug)??0)+1)}for(const feat of tempItems.filter(i=>i.type==="feat")){const slug=feat.slug??sluggify(feat.name);existing.set(slug,(existing.get(slug)??0)+1)}return filteredItems.filter(i=>i.isOfType("feat")?(existing.get(i.slug??sluggify(i.name))??0)<i.maxTakable:!0).map(f=>({value:choices.slugsAsValues?f.slug??sluggify(f.name):f.uuid,label:f.name,img:f.img}))}#getPreselection(){return(Array.isArray(this.choices)?this.choices.find(c=>equals(c.value,this.selection)):null)??null}#setRollOption(selection){if(!(this.rollOption&&(typeof selection=="string"||typeof selection=="number")))return;const suffix=UUIDUtils.isItemUUID(selection)?"":`:${selection}`;this.actor.rollOptions.all[`${this.rollOption}${suffix}`]=!0}}class CraftingEntryRuleElement extends RuleElementPF2e{static{__name(this,"CraftingEntryRuleElement")}static{__name2(this,"CraftingEntryRuleElement")}static validActorTypes=["character"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),isAlchemical:new fields2.BooleanField({required:!1,initial:void 0}),isDailyPrep:new fields2.BooleanField({required:!1,initial:void 0}),isPrepared:new fields2.BooleanField({required:!1,initial:void 0}),maxItemLevel:new ResolvableValueField({required:!1,nullable:!1,initial:1}),maxSlots:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),craftableItems:new PredicateField,preparedFormulas:new fields2.ArrayField(new fields2.SchemaField({itemUUID:new fields2.StringField({required:!0,blank:!1}),quantity:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),sort:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),expended:new fields2.BooleanField({required:!1,initial:void 0}),isSignatureItem:new fields2.BooleanField({required:!1,initial:void 0})},{required:!0,nullable:!1}),{initial:[]})}}constructor(data,options){super({priority:19,...data},options)}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),craftableItems=this.craftableItems??[];this.actor.system.crafting.entries[this.selector]={selector,name:this.label,isAlchemical:this.isAlchemical,isDailyPrep:this.isDailyPrep,isPrepared:this.isPrepared,craftableItems,maxItemLevel:Number(this.resolveValue(this.maxItemLevel))||1,maxSlots:this.maxSlots,parentItem:this.item.id,preparedFormulaData:this.preparedFormulas};const option=sluggify(this.selector);this.actor.rollOptions.all[`crafting:entry:${option}`]=!0}}class CraftingFormulaRuleElement extends RuleElementPF2e{static{__name(this,"CraftingFormulaRuleElement")}static{__name2(this,"CraftingFormulaRuleElement")}static validActorTypes=["character"];constructor(data,options){if(super(data,options),!(typeof data.uuid=="string"&&/^(?:Compendium|Item)\..*[a-z0-9]{16}$/i.test(data.uuid))){const{item}=this;this.failValidation(`Crafting formula rule element on ${item.name} (${item.uuid}) has a malformed UUID`)}}beforePrepareData(){this.ignored||this.actor.system.crafting.formulas.find(f=>f.uuid===this.data.uuid)||this.actor.system.crafting.formulas.push({uuid:this.data.uuid})}}class CritSpecRuleElement extends RuleElementPF2e{static{__name(this,"CritSpecRuleElement")}static{__name2(this,"CritSpecRuleElement")}static validActorTypes=["character","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),alternate:new fields2.BooleanField,text:new fields2.StringField({blank:!1,nullable:!0,initial:null}),damageDice:new fields2.SchemaField({number:new ResolvableValueField({required:!0,nullable:!1,initial:void 0}),faces:new fields2.NumberField({required:!0,nullable:!1,choices:[4,6,8,10,12],initial:void 0}),damageType:new fields2.StringField({required:!1,nullable:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:null}),category:new fields2.StringField({required:!1,nullable:!0,choices:Array.from(DAMAGE_CATEGORIES_UNIQUE),initial:null})},{required:!1,nullable:!0,initial:null}),modifier:new fields2.SchemaField({type:new fields2.StringField({required:!0,nullable:!1,choices:Array.from(MODIFIER_TYPES),initial:"untyped"}),damageType:new fields2.StringField({required:!1,nullable:!0,choices:()=>CONFIG.PF2E.damageTypes,initial:null}),category:new fields2.StringField({required:!1,nullable:!0,choices:Array.from(DAMAGE_CATEGORIES_UNIQUE),initial:null}),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0})},{required:!1,nullable:!0,initial:null})}}static validateJoint(data){if(super.validateJoint(data),data.alternate&&!data.text&&!data.damageDice&&!data.modifier)throw Error("alternate: must also include at least one of text, damage dice, or modifier");if(!data.alternate&&(data.text||data.damageDice||data.modifier)){const badProperty=["text","damageDice","modifier"].find(k=>data[k]);throw Error(`${badProperty}: may only be used if alternate is true`)}}beforePrepareData(){if(this.ignored)return;const synthetic=__name2((weapon,options)=>this.resolveInjectedProperties(this.predicate).test(options)?this.#getEffect(weapon):null,"synthetic");this.ignored||this.actor.synthetics.criticalSpecalizations[this.alternate?"alternate":"standard"].push(synthetic)}#getEffect(weapon){const text=this.text?this.resolveInjectedProperties(this.text.trim()):null,slug="critical-specialization",label="PF2E.Actor.Creature.CriticalSpecialization",note=__name2(()=>this.alternate&&!this.text?null:new RollNotePF2e({selector:"strike-damage",title:label,text:text??`PF2E.Item.Weapon.CriticalSpecialization.${weapon.group}`,outcome:["criticalSuccess"]}),"note"),resolveInteger=__name2((value,fallback)=>{const resolved=this.resolveValue(value,0,{resolvables:{weapon}});return Math.clamped(Math.trunc(Math.abs(Number(resolved))),1,10)||fallback},"resolveInteger"),damageDice=__name2(()=>this.alternate&&this.damageDice?new DamageDicePF2e({slug,label,selector:"strike-damage",diceNumber:resolveInteger(this.damageDice.number,1),dieSize:`d${this.damageDice.faces}`,damageType:this.damageDice.damageType,category:this.damageDice.category,critical:!0}):null,"damageDice"),modifier=__name2(()=>this.alternate&&this.modifier?new ModifierPF2e({slug,label,type:this.modifier.type,modifier:resolveInteger(this.modifier.value,0),damageType:this.modifier.damageType,damageCategory:this.modifier.category,critical:!0}):null,"modifier");if(this.alternate)return compact([note(),damageDice(),modifier()]);switch(weapon.group){case"crossbow":case"dart":case"knife":{const dice=new DamageDicePF2e({slug,selector:"strike-damage",label,damageType:"bleed",diceNumber:1,dieSize:weapon.group==="crossbow"?"d8":"d6",critical:!0}),bonusValue=weapon.isOfType("melee")?weapon.linkedWeapon?.system.runes.potency??0:weapon.flags.pf2e.attackItemBonus,bonus=bonusValue>0?new ModifierPF2e({slug,label,type:"item",damageType:"bleed",modifier:bonusValue,critical:!0}):null;return[dice,bonus??[]].flat()}case"pick":return weapon.baseDamage.die?[new ModifierPF2e({slug,label,type:"untyped",modifier:2*weapon.baseDamage.dice,critical:!0})]:[];default:return weapon.group?compact([note()]):[]}}}class DamageDiceRuleElement extends RuleElementPF2e{static{__name(this,"DamageDiceRuleElement")}static{__name2(this,"DamageDiceRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),diceNumber:new ResolvableValueField({required:!1,initial:void 0}),dieSize:new fields2.StringField({required:!1,blank:!1,nullable:!0,initial:null}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:void 0}),category:new fields2.StringField({choices:["persistent","precision","splash"],required:!1,blank:!1,initial:void 0}),brackets:new ResolvableValueField({required:!1,nullable:!0,initial:void 0}),override:new fields2.ObjectField({required:!1,nullable:!0,initial:void 0})}}constructor(data,options){super(data,options),this.brackets=this.isBracketedValue(data.value)?data.value:null,data.override&&!this.#isValidOverride(data.override)&&(this.failValidation("The override property must be an object with one property of 'upgrade' (boolean),","'downgrade (boolean)', 'diceNumber' (integer between 0 and 10), 'dieSize' (d6-d12), or 'damageType'","(recognized damage type)"),this.override=null)}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const deferredDice=__name2((params={})=>{const label=this.getReducedLabel(),testPassed=this.predicate.length===0||this.resolveInjectedProperties(this.predicate).test([...params.test??this.actor.getRollOptions(["damage"]),...this.item.getRollOptions("parent")]),resolveOptions={...params,warn:testPassed},diceNumber=Number(this.resolveValue(this.diceNumber,0,resolveOptions))||0;if(this.ignored)return null;const resolvedBrackets=this.resolveValue(this.brackets,{},resolveOptions);if(!this.#resolvedBracketsIsValid(resolvedBrackets))return testPassed&&this.failValidation("Brackets failed to validate"),null;const damageType=this.resolveInjectedProperties(this.damageType,resolveOptions);if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return testPassed&&this.failValidation(`Unrecognized damage type: ${damageType}`),null;if(this.override){if(this.override.damageType&&=this.resolveInjectedProperties(this.override.damageType,resolveOptions),"damageType"in this.override&&!objectHasKey(CONFIG.PF2E.damageTypes,this.override.damageType))return testPassed&&this.failValidation("Unrecognized damage type in override"),null;if(this.override.diceNumber&&=Math.floor(Number(this.resolveValue(this.override.diceNumber,resolveOptions))),typeof this.override.diceNumber=="number"&&this.override.diceNumber<0)return testPassed&&this.failValidation("A dice number must resolve to at least zero"),null;if(this.override.dieSize&&=this.resolveInjectedProperties(this.override.dieSize,resolveOptions),"dieSize"in this.override&&!setHasElement(DAMAGE_DIE_FACES,this.override.dieSize))return testPassed&&this.failValidation("Unrecognized die size in override"),null}const dieSize=this.resolveInjectedProperties(this.dieSize,resolveOptions);return dieSize!==null&&!setHasElement(DAMAGE_DIE_FACES,dieSize)?(testPassed&&this.failValidation("Die size must be a recognized damage die size, null, or omitted"),null):new DamageDicePF2e({selector,slug:this.slug??sluggify(this.item.name),label,diceNumber,dieSize,critical:this.critical,category:this.category,damageType,predicate:this.predicate,override:foundry.utils.deepClone(this.override),enabled:testPassed,...resolvedBrackets})},"deferredDice");(this.actor.synthetics.damageDice[selector]??=[]).push(deferredDice)}}#isValidOverride(override){return override===void 0?!0:isObject(override)&&(typeof override.upgrade=="boolean"&&!("downgrade"in override)||typeof override.downgrade=="boolean"&&!("upgrade"in override)||typeof override.damageType=="string"||typeof override.dieSize=="string"||typeof override.diceNumber=="string"||typeof override.diceNumber=="number"&&Number.isInteger(override.diceNumber)&&override.diceNumber>=0&&override.diceNumber<=256)}#resolvedBracketsIsValid(value){if(!isObject(value))return!1;const keysAreValid=Object.keys(value).every(k=>["diceNumber","dieSize","override"].includes(k)),diceNumberIsValid=!("diceNumber"in value)||typeof value.diceNumber=="number",dieSizeIsValid=!("dieSize"in value)||setHasElement(DAMAGE_DIE_FACES,value.dieSize),overrideIsValid=!("override"in value)||this.#isValidOverride(value.override);return keysAreValid&&diceNumberIsValid&&dieSizeIsValid&&overrideIsValid}}class DexterityModifierCapRuleElement extends RuleElementPF2e{static{__name(this,"DexterityModifierCapRuleElement")}static{__name2(this,"DexterityModifierCapRuleElement")}static validActorTypes=["character","npc"];static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1})}}beforePrepareData(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number")return this.failValidation("value must be a number");this.actor.synthetics.dexterityModifierCaps.push({value,source:this.label})}}class EphemeralEffectRuleElement extends RuleElementPF2e{static{__name(this,"EphemeralEffectRuleElement")}static{__name2(this,"EphemeralEffectRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),affects:new fields2.StringField({required:!0,choices:["target","origin"],initial:"target"}),selectors:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0})),uuid:new fields2.StringField({required:!0,blank:!1,nullable:!1,initial:void 0}),adjustName:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),alterations:new fields2.ArrayField(new fields2.EmbeddedDataField(ItemAlteration),{required:!1,nullable:!1,initial:[]})}}static validateJoint(data){if(super.validateJoint(data),data.selectors.length===0)throw Error("must have at least one selector")}afterPrepareData(){for(const selector of this.resolveInjectedProperties(this.selectors)){const deferredEffect=this.#createDeferredEffect();(this.actor.synthetics.ephemeralEffects[selector]??={target:[],origin:[]})[this.affects].push(deferredEffect)}}#createDeferredEffect(){return async(params={})=>{if(!this.test(params.test??this.actor.getRollOptions()))return null;const uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(`"${uuid}" does not look like a UUID`),null;const effect=game.pf2e.ConditionManager.conditions.get(uuid)??await fromUuid(uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("condition","effect")))return this.failValidation(`unable to find effect or condition item with uuid "${uuid}"`),null;const source=effect.toObject();if(source.system.rules.some(r=>typeof r.key=="string"&&(r.key==="ChoiceSet"||r.key==="GrantItem"&&!("inMemoryOnly"in r&&r.inMemoryOnly===!0)))&&this.failValidation("an ephemeral effect may not include a choice set or grant"),this.adjustName){const label=this.getReducedLabel();source.name=`${source.name} (${label})`}try{for(const alteration of this.alterations)alteration.applyTo(source)}catch(error){return error instanceof Error&&this.failValidation(error.message),null}return source}}}class FastHealingRuleElement extends RuleElementPF2e{static{__name(this,"FastHealingRuleElement")}static{__name2(this,"FastHealingRuleElement")}static validActorTypes=["army","character","npc","familiar"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1}),type:new fields2.StringField({required:!1,nullable:!1,choices:["fast-healing","regeneration"],initial:"fast-healing"}),details:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),deactivatedBy:new fields2.ArrayField(new fields2.StringField({required:!0,nullable:!1,blank:!1}),{required:!1,initial:void 0})}}static validateJoint(data){if(super.validateJoint(data),data.type==="fast-healing"){if(data.deactivatedBy)throw data.ignored=!0,Error("deactivatedBy is only valid for type regeneration");data.details&&(data.details=game.i18n.localize(data.details))}else if(data.type==="regeneration"){if(data.details)throw data.ignored=!0,Error("details is only valid for type fast-healing");if(data.deactivatedBy?.length){const typesArr=data.deactivatedBy.map(type=>objectHasKey(CONFIG.PF2E.weaknessTypes,type)?game.i18n.localize(CONFIG.PF2E.weaknessTypes[type]):type),types=localizeList(typesArr);data.details=game.i18n.format("PF2E.Encounter.Broadcast.FastHealing.DeactivatedBy",{types})}}}async onTurnStart(){if(!this.test())return;const value=this.resolveValue(this.value);if(typeof value!="number"&&typeof value!="string")return this.failValidation("value must be a number or a roll formula");const receivedMessage=game.i18n.localize(`PF2E.Encounter.Broadcast.FastHealing.${this.type}.ReceivedMessage`),postFlavor=`<div data-visibility="owner">${this.details??this.getReducedLabel()}</div>`,flavor=`<div>${receivedMessage}</div>${postFlavor}`,roll=(await new DamageRoll(`{(${value})[healing]}`).evaluate({async:!0})).toJSON(),rollMode=this.actor.hasPlayerOwner?"publicroll":"gmroll",speaker=ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.token});ChatMessagePF2e.create({flavor,speaker,type:CONST.CHAT_MESSAGE_TYPES.ROLL,rolls:[roll]},{rollMode})}}class FixedProficiencyRuleElement extends RuleElementPF2e{static{__name(this,"FixedProficiencyRuleElement")}static{__name2(this,"FixedProficiencyRuleElement")}static validActorTypes=["character"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!0,initial:void 0}),ability:new fields2.StringField({required:!0,choices:[...ATTRIBUTE_ABBREVIATIONS]})}}static validateJoint(data){data.selector==="ac"&&(data.ability="dex")}beforePrepareData(){const selector=this.resolveInjectedProperties(this.selector),proficiencyBonus=Number(this.resolveValue(this.value))||0,abilityModifier=this.ability?this.actor.system.abilities[this.ability].mod:0,modifier=new ModifierPF2e({type:"proficiency",slug:this.slug??sluggify(this.label),label:this.label,modifier:proficiencyBonus+abilityModifier});(this.actor.synthetics.modifiers[selector]??=[]).push(()=>modifier)}afterPrepareData(){const selector=this.resolveInjectedProperties(this.selector),systemData=this.actor.system,proficiency=SKILL_EXPANDED[selector]?.shortForm??selector,statistic=setHasElement(SKILL_ABBREVIATIONS,proficiency)?this.actor.skills[proficiency]:proficiency==="ac"?systemData.attributes.ac:null;if(statistic){const toIgnore=statistic.modifiers.filter(m=>m.type==="proficiency"&&m.slug!==this.slug);for(const modifier of toIgnore)modifier.predicate=new PredicatePF2e(`overridden-by-${this.slug}`)}}}class FlatModifierRuleElement extends RuleElementPF2e{static{__name(this,"FlatModifierRuleElement")}static{__name2(this,"FlatModifierRuleElement")}constructor(source,options){super(source,options),!this.item.isOfType("physical")&&this.type!=="item"&&(this.fromEquipment=!1),this.type==="ability"&&this.ability&&(this.slug=this.ability,this.label=CONFIG.PF2E.abilities[this.ability],this.value=`@actor.abilities.${source.ability}.mod`),this.critical=typeof source.critical=="boolean"&&this.selectors.some(s=>s.includes("damage"))?source.critical:null,this.force&&this.type==="untyped"&&this.failValidation("type: may not be undefined"),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation("removeAfterRoll: may only be used with effects")}static validateJoint(data){if(super.validateJoint(data),data.selector.length===0)throw Error("selector: must have at least 1");if(data.type==="ability"&&!data.ability)throw Error("ability: must be defined");if(data.type!=="ability"&&data.value===void 0)throw Error("value: may not be undefined")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0})),type:new fields2.StringField({required:!0,choices:Array.from(MODIFIER_TYPES),initial:"untyped"}),ability:new fields2.StringField({required:!1,choices:CONFIG.PF2E.abilities,initial:void 0}),min:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),max:new fields2.NumberField({required:!1,nullable:!1,initial:void 0}),force:new fields2.BooleanField,hideIfDisabled:new fields2.BooleanField,fromEquipment:new fields2.BooleanField({required:!0,nullable:!1,initial:!0}),damageType:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:void 0}),damageCategory:new fields2.StringField({required:!1,blank:!1,choices:damageCategoriesUnique,initial:void 0}),critical:new fields2.BooleanField({required:!1,nullable:!0,initial:null}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}get selectors(){return this.selector}beforePrepareData(){if(this.ignored)return;const label=this.getReducedLabel(),slug=this.slug??sluggify(label),selectors=this.selectors.map(s=>this.resolveInjectedProperties(s)).filter(s=>!!s);for(const selector of selectors){if(selector==="null")continue;const construct=__name2((options={})=>{const resolvedValue=Number(this.resolveValue(this.value,0,options))||0;if(this.ignored)return null;const finalValue=Math.clamped(resolvedValue,this.min??resolvedValue,this.max??resolvedValue);if(game.pf2e.variantRules.AutomaticBonusProgression.suppressRuleElement(this,finalValue))return null;const damageType=this.damageType&&this.resolveInjectedProperties(this.damageType,{warn:!1})||null;if(damageType!==null&&!objectHasKey(CONFIG.PF2E.damageTypes,damageType))return this.test(options.test??[])&&this.failValidation(`damageType: "${damageType}" is unrecognized`),null;const modifier=new ModifierPF2e({slug,label,modifier:finalValue,type:this.type,ability:this.type==="ability"?this.ability:null,predicate:this.resolveInjectedProperties(this.predicate),rule:this,force:this.force,damageType,damageCategory:this.damageCategory,critical:this.critical,hideIfDisabled:this.hideIfDisabled,source:this.item.uuid});return options.test&&modifier.test(options.test),modifier},"construct");(this.actor.synthetics.modifiers[selector]??=[]).push(construct)}}async afterRoll({check,rollOptions}){if(this.ignored||!this.removeAfterRoll||!this.item.isOfType("effect"))return;(this.removeAfterRoll===!0||this.removeAfterRoll==="if-enabled"&&check.modifiers.some(m=>m.rule===this&&m.enabled)||Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(rollOptions))&&await this.item.delete()}}class GrantItemRuleElement extends RuleElementPF2e{static{__name(this,"GrantItemRuleElement")}static{__name2(this,"GrantItemRuleElement")}static validActorTypes=["army","character","npc","familiar"];grantedId;preselectChoices;onDeleteActions;constructor(data,options){data.inMemoryOnly&&(data.priority??=99),super(data,options),this.inMemoryOnly?(this.reevaluateOnUpdate=!0,this.allowDuplicate=!0):(this.reevaluateOnUpdate&&(this.allowDuplicate=!1),this.item.isOfType("physical")&&this.failValidation("parent item must not be physical")),this.onDeleteActions=this.#getOnDeleteActions(data);const isValidPreselect=__name2(p=>Object.values(p).every(v=>["string","number"].includes(typeof v)),"isValidPreselect");if(this.preselectChoices=isObject$1(data.preselectChoices)&&isValidPreselect(data.preselectChoices)?foundry.utils.deepClone(data.preselectChoices):{},this.grantedId=this.item.flags.pf2e.itemGrants[this.flag??""]?.id??null,this.track){const grantedItem=this.actor.inventory.get(this.grantedId??"")??null;this.#trackItem(grantedItem)}}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),uuid:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0,label:"PF2E.UUID.Label"}),flag:new SlugField({required:!0,nullable:!0,initial:null,camel:"dromedary"}),reevaluateOnUpdate:new fields2.BooleanField({label:"PF2E.RuleEditor.GrantItem.ReevaluateOnUpdate"}),inMemoryOnly:new fields2.BooleanField,allowDuplicate:new fields2.BooleanField({initial:!0,label:"PF2E.RuleEditor.GrantItem.AllowDuplicate"}),alterations:new StrictArrayField(new fields2.EmbeddedDataField(ItemAlteration)),track:new fields2.BooleanField}}static ON_DELETE_ACTIONS=["cascade","detach","restrict"];static validateJoint(data){if(super.validateJoint(data),data.track&&!data.flag)throw Error("must have explicit flag set if granted item is tracked");if(data.reevaluateOnUpdate&&data.predicate.length===0)throw Error("reevaluateOnUpdate: must have non-empty predicate")}async preCreate(args){if(this.inMemoryOnly)return;const{itemSource,pendingItems,context}=args,ruleSource=args.ruleSource,uuid=this.resolveInjectedProperties(this.uuid),grantedItem=await(async()=>{try{return(await fromUuid(uuid))?.clone()??null}catch(error){return console.error(error),null}})();if(!(grantedItem instanceof ItemPF2e)||(ruleSource.flag=typeof ruleSource.flag=="string"&&ruleSource.flag.length>0?sluggify(ruleSource.flag,{camel:"dromedary"}):(()=>{const defaultFlag=sluggify(grantedItem.slug??grantedItem.name,{camel:"dromedary"}),flagPattern=new RegExp(`^${defaultFlag}\\d*$`),itemGrants=itemSource.flags?.pf2e?.itemGrants??{},nthGrant=Object.keys(itemGrants).filter(g=>flagPattern.test(g)).length;return nthGrant>0?`${defaultFlag}${nthGrant+1}`:defaultFlag})(),this.flag=String(ruleSource.flag),!this.test()))return;const existingItem=this.actor.items.find(i=>i.sourceId===uuid);if(!this.allowDuplicate&&existingItem){this.#setGrantFlags(itemSource,existingItem),ui.notifications.info(game.i18n.format("PF2E.UI.RuleElements.GrantItem.AlreadyHasItem",{actor:this.actor.name,item:grantedItem.name}));return}itemSource._id??=foundry.utils.randomID();const grantedSource=grantedItem.toObject();grantedSource._id=foundry.utils.randomID(),itemSource.type==="effect"&&grantedSource.type==="effect"&&(grantedSource.system.level.value=itemSource.system?.level?.value??grantedSource.system.level.value),grantedSource.flags=foundry.utils.mergeObject(grantedSource.flags,{core:{sourceId:uuid}});try{for(const alteration of this.alterations)alteration.applyTo(grantedSource)}catch(error){error instanceof Error&&this.failValidation(error.message)}const tempGranted=new ItemProxyPF2e(foundry.utils.deepClone(grantedSource),{parent:this.actor});if(tempGranted.isOfType("affliction","condition","effect")&&this.actor.isImmuneTo(tempGranted)){ruleSource.ignored=!0;return}tempGranted.prepareActorData?.();for(const rule of tempGranted.prepareRuleElements({suppressWarnings:!0}))rule.onApplyActiveEffects?.();if(this.#applyChoicePreselections(tempGranted),!this.ignored){args.tempItems.push(tempGranted);for(const item of[this.item,tempGranted])if(item.isOfType("class","feat")){const prefix=item.isOfType("class")||!item.isFeature?item.type:"feature",slug=item.slug??sluggify(item.name);this.actor.rollOptions.all[`self:${prefix}:${slug}`]=!0}this.grantedId=grantedSource._id,context.keepId=!0,this.#setGrantFlags(itemSource,grantedSource),this.#trackItem(tempGranted),args.reevaluation||await this.#runGrantedItemPreCreates(args,tempGranted,grantedSource,context),pendingItems.push(grantedSource)}}async preUpdateActor(){const noAction={create:[],delete:[]};if(!this.reevaluateOnUpdate||this.inMemoryOnly)return noAction;if(this.grantedId&&this.actor.items.has(this.grantedId))return this.test()?noAction:{create:[],delete:[this.grantedId]};const itemSource=this.item.toObject(),ruleSource=itemSource.system.rules[this.sourceIndex??-1];if(!ruleSource)return noAction;const pendingItems=[],context={parent:this.actor,render:!1};if(await this.preCreate({itemSource,pendingItems,ruleSource,tempItems:[],context,reevaluation:!0}),pendingItems.length>0){const updatedGrants=itemSource.flags.pf2e?.itemGrants??{};return await this.item.update({"flags.pf2e.itemGrants":updatedGrants},{render:!1}),{create:pendingItems,delete:[]}}return noAction}onApplyActiveEffects(){this.#createInMemoryCondition()}#getOnDeleteActions(data){const actions=data.onDeleteActions;if(isObject(actions)){const ACTIONS=GrantItemRuleElement.ON_DELETE_ACTIONS;return tupleHasValue(ACTIONS,actions.granter)||tupleHasValue(ACTIONS,actions.grantee)?pick(actions,[actions.granter?"granter":[],actions.grantee?"grantee":[]].flat()):null}return null}#applyChoicePreselections(grantedItem){const source=grantedItem._source;for(const[flag,selection]of Object.entries(this.preselectChoices??{})){const rule=grantedItem.rules.find(rule2=>rule2 instanceof ChoiceSetRuleElement&&rule2.flag===flag);if(rule){const ruleSource=source.system.rules[grantedItem.rules.indexOf(rule)],resolvedSelection=this.resolveInjectedProperties(selection);rule.selection=ruleSource.selection=resolvedSelection}}}#setGrantFlags(granter,grantee){const flags=foundry.utils.mergeObject(granter.flags??{},{pf2e:{itemGrants:{}}});if(!this.flag)throw ErrorPF2e("Unexpected failure looking up RE flag key");flags.pf2e.itemGrants[this.flag]={id:grantee instanceof ItemPF2e?grantee.id:grantee._id,onDelete:this.onDeleteActions?.grantee??"detach"};const grantedBy={id:granter._id,onDelete:this.onDeleteActions?.granter??(setHasElement(PHYSICAL_ITEM_TYPES,grantee.type)?"detach":"cascade")};grantee instanceof ItemPF2e?grantee.update({"flags.pf2e.grantedBy":grantedBy},{render:!1}):grantee.flags=foundry.utils.mergeObject(grantee.flags??{},{pf2e:{grantedBy}})}async#runGrantedItemPreCreates(originalArgs,grantedItem,grantedSource,context){for(const rule of grantedItem.rules){const ruleSource=grantedSource.system.rules[grantedItem.rules.indexOf(rule)];await rule.preCreate?.({...originalArgs,itemSource:grantedSource,ruleSource,context})}}#createInMemoryCondition(){if(!this.inMemoryOnly||!this.test())return;const validationFailure="an in-memory-only grant must be a condition",uuid=this.resolveInjectedProperties(this.uuid);if(!UUIDUtils.isItemUUID(uuid))return this.failValidation(validationFailure);const conditionSource=game.pf2e.ConditionManager.conditions.get(uuid)?.toObject();if(!conditionSource)return this.failValidation(validationFailure);const{actor}=this;if(actor.isImmuneTo(conditionSource.system.slug))return;for(const alteration of this.alterations)alteration.applyTo(conditionSource);const flags={pf2e:{grantedBy:{id:this.item.id,onDelete:"cascade"}}};conditionSource.flags.pf2e?.grantedBy;const condition=new ConditionPF2e(foundry.utils.mergeObject(conditionSource,{_id:foundry.utils.randomID(),flags,system:{references:{parent:{id:this.item.id}}}}),{parent:this.actor});actor.conditions.set(condition.id,condition),condition.prepareSiblingData(),condition.prepareActorData(),condition.rules=condition.prepareRuleElements();for(const rule of condition.rules)rule.onApplyActiveEffects?.(),rule.beforePrepareData?.(),actor.rules.push(rule)}#trackItem(grantedItem){if(!(this.track&&this.flag&&this.grantedId&&grantedItem?.isOfType("physical")))return;this.actor.flags.pf2e.trackedItems[this.flag]=this.grantedId;const slug=sluggify(this.flag),rollOptionsAll=this.actor.rollOptions.all;for(const statement of grantedItem.getRollOptions(slug))rollOptionsAll[statement]=!0}}class ItemAlterationRuleElement extends RuleElementPF2e{static{__name(this,"ItemAlterationRuleElement")}static{__name2(this,"ItemAlterationRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema(),PRIORITIES=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES;return baseSchema.priority.initial=d=>(PRIORITIES[String(d.mode)]??50)+100,{...baseSchema,itemId:new fields2.StringField({required:!1,nullable:!1,blank:!1,initial:void 0}),itemType:new fields2.StringField({required:!1,nullable:!1,choices:mapValues$1(CONFIG.PF2E.Item.documentClasses,key=>`TYPES.Item.${key}`),initial:void 0}),...ItemAlteration.defineSchema()}}static validateJoint(data){if(super.validateJoint(data),!data.itemId&&!data.itemType)throw Error("one of itemId and itemType must be defined")}onApplyActiveEffects(){this.#applyAlteration()}async preCreate({tempItems}){if(this.ignored||(this.itemType==="feat"&&this.#applyAlteration(tempItems),this.property!=="hp-max"))return;const itemsOfType=this.itemType?this.actor.itemTypes[this.itemType]:[],actorRollOptions=this.actor.getRollOptions(),parentRollOptions=this.parent.getRollOptions("parent"),predicate=this.resolveInjectedProperties(this.predicate),updates=itemsOfType.filter(i=>predicate.test([actorRollOptions,parentRollOptions,i.getRollOptions("item")].flat())).flatMap(item=>{const source=item.toObject(),alteration=new ItemAlteration(pick(this,["mode","property","value"]),{parent:this});alteration.applyTo(source),alteration.applyTo(item);const newHP=source.system.hp,oldHP=item._source.system.hp,newHPValue=Math.floor(oldHP.value*(newHP.max/oldHP.max));return newHPValue===oldHP.value?[]:{_id:item.id,"system.hp.value":newHPValue}});updates.length>0&&await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}#applyAlteration(additionalItems=[]){if(this.ignored)return;const predicate=this.resolveInjectedProperties(this.predicate),actorRollOptions=predicate.length>0?this.actor.getRollOptions():[],parentRollOptions=this.parent.getRollOptions("parent");try{const items=this.itemId?compact([this.actor.items.get(this.resolveInjectedProperties(this.itemId))]):this.itemType==="condition"?this.actor.conditions.contents:this.actor.itemTypes[this.itemType];items.push(...additionalItems.filter(i=>this.itemId&&i.id===this.itemId||this.itemType===i.type));for(const item of items){const itemRollOptions=predicate.length>0?item.getRollOptions("item"):[],rollOptions=[actorRollOptions,parentRollOptions,itemRollOptions].flat();if(predicate.test(rollOptions)){const data=pick(this,["mode","property","value"]);new ItemAlteration(data,{parent:this}).applyTo(item)}}}catch(error){error instanceof Error&&this.failValidation(error.message)}}}class LoseHitPointsRuleElement extends RuleElementPF2e{static{__name(this,"LoseHitPointsRuleElement")}static{__name2(this,"LoseHitPointsRuleElement")}static validActorTypes=["character","familiar","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,initial:void 0}),reevaluateOnUpdate:new fields2.BooleanField({required:!1,initial:!1}),recoverable:new fields2.BooleanField({required:!1,initial:!0})}}onCreate(actorUpdates){if(this.ignored)return;const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),currentHP=this.actor._source.system.attributes.hp.value;actorUpdates["system.attributes.hp.value"]=Math.max(currentHP-value,0)}beforePrepareData(){if(this.ignored)return;const{actor}=this;if(!this.recoverable){const value=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0));actor.system.attributes.hp.unrecoverable+=value}}async preUpdate(changes){if(!this.reevaluateOnUpdate||this.ignored)return;const previousValue=Math.trunc(Math.abs(Number(this.resolveValue(this.value))||0)),newItem=this.item.clone(changes),rule=newItem.system.rules.find(r=>r.key===this.key),valueChange=Math.trunc(Math.abs(Number(this.resolveValue(String(rule?.value),0,{resolvables:{item:newItem}}))))-previousValue;if(valueChange>0){const currentHP=this.actor._source.system.attributes.hp.value;await this.actor.update({"system.attributes.hp.value":Math.max(currentHP-valueChange,0)},{render:!1})}}}const ARMOR_CATEGORIES=new Set(["unarmored","light","medium","heavy","light-barding","heavy-barding"]),ARMOR_PROPERTY_RUNE_TYPES=new Set(["acidResistant","advancing","aimAiding","antimagic","assisting","bitter","coldResistant","deathless","electricityResistant","energyAdaptive","ethereal","fireResistant","fortification","glamered","gliding","greaterAcidResistant","greaterAdvancing","greaterColdResistant","greaterDread","greaterElectricityResistant","greaterFireResistant","greaterFortification","greaterInvisibility","greaterQuenching","greaterReady","greaterShadow","greaterSlick","greaterStanching","greaterSwallowSpike","greaterWinged","immovable","implacable","invisibility","lesserDread","magnetizing","majorQuenching","majorShadow","majorSlick","majorStanching","majorSwallowSpike","malleable","misleading","moderateDread","portable","quenching","raiment","ready","rockBraced","shadow","sinisterKnight","slick","soaring","stanching","swallowSpike","trueQuenching","trueStanching","winged"]);class MartialProficiencyRuleElement extends RuleElementPF2e{static{__name(this,"MartialProficiencyRuleElement")}static{__name2(this,"MartialProficiencyRuleElement")}static validActorTypes=["character"];static defineSchema(){return{...super.defineSchema(),kind:new StrictStringField({required:!0,nullable:!1,choices:["attack","defense"],initial:"attack"}),definition:new PredicateField({required:!0,nullable:!1}),sameAs:new StrictStringField({required:!1,nullable:!1,choices:[...WEAPON_CATEGORIES,...ARMOR_CATEGORIES]}),maxRank:new StrictStringField({required:!1,nullable:!1,choices:["trained","expert","master","legendary"]}),value:new ResolvableValueField({required:!1,initial:void 0})}}constructor(data,options){super({priority:9,...data},options),this.slug??=sluggify(this.label)}onApplyActiveEffects(){if(!this.test())return;const rank=Math.clamped(Number(this.resolveValue(this.value))||1,1,4),key=this.kind==="attack"?"attacks":"defenses";this.actor.system.proficiencies[key][this.slug]={definition:this.resolveInjectedProperties(this.definition),immutable:!0,label:this.label,sameAs:this.sameAs,rank,maxRank:this.maxRank,value:0,breakdown:""}}}class MultipleAttackPenaltyRuleElement extends RuleElementPF2e{static{__name(this,"MultipleAttackPenaltyRuleElement")}static{__name2(this,"MultipleAttackPenaltyRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,label:"PF2E.RuleEditor.General.Selector"}),value:new ResolvableValueField({required:!0,initial:void 0,label:"PF2E.RuleEditor.General.Value"})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector);this.ignored||selector.length;const value=Number(this.resolveValue(this.value))||0;if(value<0){const map2={label:game.i18n.format("PF2E.UI.RuleElements.MultipleAttackPenalty.Breakdown",{label:this.label}),penalty:value,predicate:this.predicate};(this.actor.synthetics.multipleAttackPenalties[selector]??=[]).push(map2)}else value!==0&&this.failValidation("value: must resolve to less than or equal to zero")}}class RollNoteRuleElement extends RuleElementPF2e{static{__name(this,"RollNoteRuleElement")}static{__name2(this,"RollNoteRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,initial:void 0}),{required:!0,nullable:!1}),title:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),visibility:new fields2.StringField({required:!0,nullable:!0,choices:["gm","owner"],initial:null}),outcome:new fields2.ArrayField(new fields2.StringField({required:!0,blank:!1,choices:DEGREE_OF_SUCCESS_STRINGS}),{required:!1,nullable:!1,initial:void 0}),text:new DataUnionField([new StrictStringField({required:!0,blank:!1}),new ResolvableValueField],{required:!0,nullable:!1})}}beforePrepareData(){if(!this.ignored)for(const selector of this.resolveInjectedProperties(this.selector)){if(selector==="null")continue;const title=this.resolveInjectedProperties(this.title)?.trim()??null,text=this.resolveInjectedProperties(String(this.resolveValue(this.text,"",{evaluate:!1}))).trim();if(!text)return this.failValidation("text field resolved empty");const note=new RollNotePF2e({selector,title:title?this.getReducedLabel(title):null,text,predicate:this.resolveInjectedProperties(this.predicate),outcome:this.outcome,visibility:this.visibility,rule:this});(this.actor.synthetics.rollNotes[selector]??=[]).push(note)}}}class RollOptionRuleElement extends RuleElementPF2e{static{__name(this,"RollOptionRuleElement")}static{__name2(this,"RollOptionRuleElement")}constructor(source,options){super(source,options),source.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation("removeAfterRoll may only be used on rule elements from effect items"),this.toggleable==="totm"&&!game.pf2e.settings.totm&&(this.ignored=!0);const firstSuboption=this.suboptions.at(0);firstSuboption&&this.suboptions.every(s=>!s.selected)&&(firstSuboption.selected=!0)}static defineSchema(){const{fields:fields2}=foundry.data,baseSchema=super.defineSchema();return baseSchema.priority.initial=AELikeRuleElement.CHANGE_MODE_DEFAULT_PRIORITIES.override,{...baseSchema,domain:new fields2.StringField({required:!0,nullable:!1,initial:"all",blank:!1}),option:new fields2.StringField({required:!0,nullable:!1,blank:!1}),phase:new fields2.StringField({required:!1,nullable:!1,choices:foundry.utils.deepClone(AELikeRuleElement.PHASES),initial:"applyAEs"}),suboptions:new fields2.ArrayField(new fields2.SchemaField({label:new fields2.StringField({required:!0,nullable:!1,blank:!1,initial:void 0}),value:new StrictStringField({required:!0,nullable:!1,blank:!1,initial:void 0}),predicate:new PredicateField,selected:new fields2.BooleanField}),{required:!1,nullable:!1,initial:[],validate:v=>Array.isArray(v)&&v.length!==1,validationError:"must have zero or 2+ suboptions"}),value:new ResolvableValueField({required:!1,initial:d=>!d.toggleable,validate:v=>["boolean","string"].includes(typeof v),validationError:"must be a boolean, string, or otherwise omitted"}),toggleable:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["totm"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:!1})],{required:!1,nullable:!1,initial:void 0}),placement:new fields2.StringField({required:!1,nullable:!1,initial:void 0}),disabledIf:new PredicateField({required:!1,initial:void 0}),disabledValue:new fields2.BooleanField({required:!1,initial:void 0}),alwaysActive:new fields2.BooleanField({required:!1,initial:void 0}),count:new fields2.BooleanField({required:!1,initial:void 0}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}static validateJoint(source){if(super.validateJoint(source),source.suboptions.length>0&&!source.toggleable)throw Error(" suboptions: must be omitted if not toggleable");if(source.disabledIf&&!source.toggleable)throw Error(" disabledIf: must be false if not toggleable");if(source.count&&source.toggleable)throw Error(" count: must be false if toggleable");if(typeof source.disabledValue=="boolean"&&(!source.toggleable||!source.disabledIf))throw Error(" disabledValue: may only be included if toggeable and there is a disabledIf predicate.");if(source.alwaysActive&&(!source.toggleable||source.suboptions.length===0))throw Error(" alwaysActive: must be false unless toggleable and containing suboptions");if(source.placement&&!source.toggleable)throw Error(" placement: may only be present if toggleable")}async preCreate(){this.phase==="applyAEs"&&this.#setRollOption()}onApplyActiveEffects(){this.phase==="applyAEs"&&this.#setRollOption()}beforePrepareData(){this.phase==="beforeDerived"&&this.#setRollOption()}afterPrepareData(){this.phase==="afterDerived"&&this.#setRollOption()}#resolveOption({appendSuboption=!0}={}){const baseOption=this.resolveInjectedProperties(this.option).replace(/[^-:\w]/g,"").replace(/:+/g,":").replace(/-+/g,"-").trim();if(appendSuboption){const selectedSuboption=this.suboptions.find(o=>o.selected);return selectedSuboption?`${baseOption}:${selectedSuboption.value}`:baseOption}else return baseOption}#setFlag(value){const suboption=this.suboptions.find(o=>o.selected)??this.suboptions.at(0);if(suboption){const flagKey=sluggify(this.#resolveOption({appendSuboption:!1}),{camel:"dromedary"});if(value){const flagValue=/^\d+$/.test(suboption.value)?Number(suboption.value):suboption.value;this.item.flags.pf2e.rulesSelections[flagKey]=flagValue}else this.item.flags.pf2e.rulesSelections[flagKey]=null}}#setRollOption(){this.domain=this.resolveInjectedProperties(this.domain);const isStandardDomain=/^[-a-z0-9]+$/.test(this.domain)&&/[a-z]/.test(this.domain),isIdDomain=/^[a-zA-Z0-9]{16}-[-a-z0-9]+[a-z0-9]$/.test(this.domain);if(!isStandardDomain&&!isIdDomain)return this.failValidation("domain must be a string consisting of only lowercase letters, numbers, and hyphens.");const optionSet=new Set([this.actor.getRollOptions([this.domain]),this.parent.getRollOptions("parent")].flat());if(!this.test(optionSet))return this.#setFlag(!1);const{rollOptions}=this.actor,domainRecord=rollOptions[this.domain]??={},baseOption=this.option=this.#resolveOption({appendSuboption:!1});if(!baseOption){this.failValidation('The "option" property must be a string consisting of only letters, numbers, colons, and hyphens');return}if(this.count){const existing=Object.keys(domainRecord).flatMap(key=>({key,count:Number(new RegExp(`^${baseOption}:(\\d+)$`).exec(key)?.[1])})).find(keyAndCount=>!!keyAndCount.count);existing?(delete domainRecord[existing.key],domainRecord[`${baseOption}:${existing.count+1}`]=!0):domainRecord[`${baseOption}:1`]=!0}else{const suboptions=this.suboptions.filter(s=>s.predicate.test(optionSet));if(suboptions.length>0&&!suboptions.some(s=>s.selected)){suboptions[0].selected=!0;for(const otherSuboption of this.suboptions)otherSuboption!==suboptions[0]&&(otherSuboption.selected=!1)}else if(this.suboptions.length>0&&suboptions.length===0)return;const fullOption=this.#resolveOption(),value=this.resolveValue();if(value&&(domainRecord[fullOption]=value,domainRecord[baseOption]=value),this.toggleable){const toggle={itemId:this.item.id,label:this.getReducedLabel(),placement:this.placement??"actions-tab",domain:this.domain,option:baseOption,suboptions,alwaysActive:!!this.alwaysActive,checked:value,enabled:!0};if(this.disabledIf){const rollOptions2=this.actor.getRollOptions([this.domain]);toggle.enabled=!this.disabledIf.test(rollOptions2),!toggle.enabled&&!this.alwaysActive&&typeof this.disabledValue=="boolean"&&(toggle.checked=this.disabledValue,this.disabledValue||delete domainRecord[fullOption])}this.actor.synthetics.toggles.push(toggle)}this.#setFlag(value)}}resolveValue(){return this.toggleable==="totm"&&!game.settings.get("pf2e","totmToggles")?!1:this.alwaysActive?!0:!!super.resolveValue(this.value)}async toggle(newValue=!this.resolveValue(),newSuboption=null){if(!this.toggleable)throw ErrorPF2e("Attempted to toggle non-toggleable roll option");const rulesSource=this.item.toObject().system.rules,thisSource=typeof this.sourceIndex=="number"?rulesSource.at(this.sourceIndex):null;if(!thisSource)return null;if(thisSource.value=newValue,newSuboption&&Array.isArray(thisSource.suboptions)&&thisSource.suboptions.every(o=>isObject(o)))for(const suboption of thisSource.suboptions)suboption.selected=suboption.value===newSuboption;return(await this.actor.updateEmbeddedDocuments("Item",[{_id:this.item.id,"system.rules":rulesSource}])).length===1?newValue:null}beforeRoll(domains,rollOptions){if(!(this.test(rollOptions)&&domains.includes(this.domain)))return;this.value=this.resolveValue();const option=this.#resolveOption();this.value?rollOptions.add(option):rollOptions.delete(option)}async afterRoll({domains,rollOptions}){const option=this.#resolveOption();!this.ignored&&this.removeAfterRoll&&this.value&&this.actor.items.has(this.item.id)&&domains.includes(this.domain)&&rollOptions.has(option)&&(game.settings.get("pf2e","automation.removeExpiredEffects")?await this.item.delete():game.settings.get("pf2e","automation.effectExpiration")&&await this.item.update({"system.duration.value":-1,"system.expired":!0}))}}class RollTwiceRuleElement extends RuleElementPF2e{static{__name(this,"RollTwiceRuleElement")}static{__name2(this,"RollTwiceRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),keep:new fields2.StringField({required:!0,choices:["lower","higher"]}),removeAfterRoll:new fields2.BooleanField({required:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const synthetic={keep:this.keep};this.predicate&&(synthetic.predicate=this.predicate),(this.actor.synthetics.rollTwice[this.selector]??=[]).push(synthetic)}async afterRoll({domains,roll,rollOptions}){if(!this.actor.items.has(this.item.id))return;const expireEffects=game.settings.get("pf2e","automation.effectExpiration"),removeExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),removeAfterRoll=this.removeAfterRoll??((expireEffects||removeExpired)&&this.item.isOfType("effect"));if((roll?.dice.some(d=>["kh","kl"].some(m=>d.modifiers.includes(m)))??!1)&&removeAfterRoll&&domains.includes(this.selector)&&this.test(rollOptions)){for(const rule of this.item.rules)rule.ignored=!0;removeExpired?await this.item.delete():expireEffects&&await this.item.update({"system.duration.value":-1,"system.expired":!0})}}}class SpecialStatisticRuleElement extends RuleElementPF2e{static{__name(this,"SpecialStatisticRuleElement")}static{__name2(this,"SpecialStatisticRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0,validate:v=>typeof v=="string"&&!(v in CONFIG.PF2E.magicTraditions||v in CONFIG.PF2E.classTraits||setHasElement(SKILL_LONG_FORMS,v)||tupleHasValue(SAVE_TYPES,v)||["perception","initiative"].includes(v))}),type:new fields2.StringField({required:!0,choices:["simple","check","attack-roll"],initial:"check"}),extends:new fields2.StringField({required:!0,nullable:!0,initial:null}),attribute:new fields2.StringField({required:!1,choices:Array.from(ATTRIBUTE_ABBREVIATIONS),nullable:!0,initial:null})}}afterPrepareData(){if(this.type==="simple")return;const checkDomains=this.type==="check"?[`${this.slug}-check`]:[`${this.slug}-attack-roll`],extendedFrom=this.extends?this.actor.getStatistic(this.extends):null,data={slug:this.slug,label:this.label,attribute:this.attribute??extendedFrom?.attribute??null,domains:[this.slug],check:{type:this.type==="check"?"check":"attack-roll",domains:checkDomains},dc:{domains:[`${this.slug}-dc`]}},statistic=extendedFrom?.extend(data)??new Statistic(this.actor,data);statistic?this.actor.synthetics.statistics.set(this.slug,statistic):this.failValidation(`Unable to find statistic ${this.extends} to extend from`)}}class StrikingRuleElement extends RuleElementPF2e{static{__name(this,"StrikingRuleElement")}static{__name2(this,"StrikingRuleElement")}static validActorTypes=["character","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1}),value:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})}}beforePrepareData(){if(this.ignored)return;const selector=this.resolveInjectedProperties(this.selector),strikingValue=this.value??(this.item.isOfType("weapon")?this.item.system.runes.striking:0),value=this.resolveValue(strikingValue);if(selector&&typeof value=="number"){const striking={label:this.getReducedLabel(),bonus:value,predicate:this.predicate};(this.actor.synthetics.striking[selector]??=[]).push(striking)}else this.failValidation("Striking requires at least a selector field and a non-empty resolved value")}}class SubstituteRollRuleElement extends RuleElementPF2e{static{__name(this,"SubstituteRollRuleElement")}static{__name2(this,"SubstituteRollRuleElement")}constructor(source,options){super(source,options),this.removeAfterRoll&&!this.item.isOfType("effect")&&this.failValidation("removeAfterRoll: may only be used with effects")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,blank:!1,initial:"check"}),value:new ResolvableValueField({required:!0,nullable:!1}),required:new fields2.BooleanField({required:!1,nullable:!1,initial:!1}),effectType:new fields2.StringField({required:!0,nullable:!1,choices:["fortune","misfortune"],initial:"fortune"}),removeAfterRoll:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["if-enabled"],initial:void 0}),new StrictBooleanField({required:!1,nullable:!1,initial:void 0}),new PredicateField({required:!1,nullable:!1,initial:void 0})],{required:!1,nullable:!1,initial:!1})}}beforePrepareData(){const value=Math.clamped(Math.trunc(Number(this.resolveValue(this.value))),1,20);if(Number.isNaN(value))return this.failValidation("value must resolve to a number");const selector=this.resolveInjectedProperties(this.selector);(this.actor.synthetics.rollSubstitutions[selector]??=[]).push({slug:this.slug??sluggify(this.item.name),label:this.label,value,predicate:this.predicate,required:this.required,selected:this.required,effectType:this.effectType})}async afterRoll(params){if(!this.removeAfterRoll||this.ignored)return;if(this.removeAfterRoll===!0){await this.item.delete();return}if(Array.isArray(this.removeAfterRoll)&&this.removeAfterRoll.test(params.rollOptions)){await this.item.delete();return}const rollSubstituted=params.roll.dice.length===0,substitutionIncluded=!!params.context.substitutions?.some(s=>s.slug===this.slug&&s.selected);this.removeAfterRoll==="if-enabled"&&rollSubstituted&&substitutionIncluded&&await this.item.delete()}}class TokenEffect{static{__name(this,"TokenEffect")}static{__name2(this,"TokenEffect")}#effect;tint=null;isTemporary=!0;constructor(effect){this.#effect=effect}get id(){return this.#effect.id}get _id(){return this.#effect.id}get parent(){return this.#effect.parent}get name(){return this.#effect.name}get icon(){return this.#effect.img}get changes(){return[]}get description(){return this.#effect.description}get flags(){return this.#effect.flags}get statuses(){return new Set([this.#effect.slug??sluggify(this.#effect.name)])}get disabled(){return this.#effect.isOfType("effect")&&this.#effect.isExpired}get duration(){const effect=this.#effect,isEffect=effect.isOfType("effect");return{type:"none",seconds:null,rounds:null,turns:null,combat:null,startTime:isEffect?effect.system.start.value:null,startRound:null,startTurn:isEffect?effect.system.start.initiative:null,label:isEffect?effect.system.remaining:""}}get transfer(){return!1}get origin(){return this.#effect.uuid}getFlag(scope,flag){return this.#effect.getFlag(scope,flag)}}class TokenEffectIconRuleElement extends RuleElementPF2e{static{__name(this,"TokenEffectIconRuleElement")}static{__name2(this,"TokenEffectIconRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.StringField({required:!1,blank:!1,initial:void 0})}}afterPrepareData(){if(!this.test())return;const path=this.value?this.resolveInjectedProperties(this.value).trim():this.item.img;if(!isImageFilePath(path))return this.failValidation("value: must resolve to an image file path");this.actor.synthetics.tokenEffectIcons.push(new TokenEffect(new EffectPF2e({type:"effect",name:this.label,img:path})))}}class TokenImageRuleElement extends RuleElementPF2e{static{__name(this,"TokenImageRuleElement")}static{__name2(this,"TokenImageRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new ResolvableValueField({required:!0,nullable:!1,initial:void 0,label:"TOKEN.ImagePath"}),scale:new fields2.NumberField({required:!1,nullable:!0,positive:!0,initial:null,label:"Scale"}),tint:new fields2.ColorField({label:"TOKEN.TintColor"}),alpha:new fields2.AlphaField({label:"PF2E.RuleEditor.General.Opacity",required:!1,nullable:!0,initial:null})}}constructor(data,options){super(data,options),typeof this.value=="string"||this.isBracketedValue(this.value)||this.failValidation("value must be a string or a bracketed value")}afterPrepareData(){const src=this.resolveValue(this.value);if(!this.#srcIsValid(src))return this.failValidation("Missing or invalid value field");if(!this.test())return;const texture={src};this.scale&&(texture.scaleX=this.scale,texture.scaleY=this.scale),this.tint&&(texture.tint=this.tint),this.alpha&&(this.actor.synthetics.tokenOverrides.alpha=this.alpha),this.actor.synthetics.tokenOverrides.texture=texture}#srcIsValid(src){if(typeof src!="string")return!1;const extension=/(?<=\.)[a-z0-9]{3,4}$/i.exec(src)?.at(0);return!!extension&&(extension in CONST.IMAGE_FILE_EXTENSIONS||extension in CONST.VIDEO_FILE_EXTENSIONS)}}class TokenLightRuleElement extends RuleElementPF2e{static{__name(this,"TokenLightRuleElement")}static{__name2(this,"TokenLightRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),value:new fields2.SchemaField({...foundry.data.LightData.defineSchema(),bright:new ResolvableValueField({required:!1,nullable:!1,initial:void 0}),color:new fields2.StringField({required:!1,nullable:!0,blank:!1,initial:null}),dim:new ResolvableValueField({required:!1,nullable:!1,initial:void 0})})}}getLightData(){const light=this.value;light.color&&=this.resolveInjectedProperties(light.color);for(const key of["bright","dim"])if(light[key]!==void 0){const resolvedValue=this.resolveValue(light[key]);if(typeof resolvedValue=="number")light[key]=resolvedValue;else return this.failValidation(`${key}: must resolve to a number`),null}try{return new foundry.data.LightData(light).toObject()}catch(error){return error instanceof Error&&this.failValidation(error.message),null}}afterPrepareData(){if(!this.test())return;const data=this.getLightData();data&&(this.actor.synthetics.tokenOverrides.light=data)}}class MarkTargetPrompt{static{__name(this,"MarkTargetPrompt")}static{__name2(this,"MarkTargetPrompt")}prompt;requirements;#target;#resolve;constructor(params){this.prompt=params.prompt??"PF2E.UI.RuleElements.TokenMark.TargetToken",this.requirements=params.requirements}async resolveTarget(){return game.user.targets.clear(),this.activateListeners(),ui.notifications.info(this.prompt,{localize:!0}),new Promise(resolve=>{this.#resolve=resolve})}activateListeners(){document.activeElement instanceof HTMLElement&&document.activeElement.blur();const hookParams=["targetToken",(_user,token,targeted)=>{this.#target=targeted&&token instanceof TokenPF2e?token.document:null,this.#resolve?.(this.#target)}];Hooks.once(...hookParams);const cancelHandler=this.#cancelHandler(hookParams);document.addEventListener("keyup",cancelHandler),window.setTimeout(()=>{Hooks.off(...hookParams),document.removeEventListener("keyup",cancelHandler),this.#target===void 0&&this.#resolve?.(null)},15e3)}#cancelHandler(hookParams){const handler=__name2(event2=>{event2.key==="Escape"&&(event2.stopPropagation(),ui.notifications.info("PF2E.UI.RuleElements.TokenMark.Timeout",{localize:!0}),Hooks.off(...hookParams),document.removeEventListener("keyup",handler))},"handler");return handler}}class TokenMarkRuleElement extends RuleElementPF2e{static{__name(this,"TokenMarkRuleElement")}static{__name2(this,"TokenMarkRuleElement")}static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),slug:new SlugField({required:!0,nullable:!1,initial:void 0}),uuid:new fields2.StringField({required:!1,nullable:!0,initial:null})}}async preCreate({ruleSource,itemSource,pendingItems}){if(this.ignored)return;if(this.uuid&&=this.resolveInjectedProperties(this.uuid),this.actor.getActiveTokens().length===0){this.ignored=ruleSource.ignored=!0;return}const token=fromUuidSync(this.uuid??"")??(game.user.targets.size===1?Array.from(game.user.targets)[0].document:await new MarkTargetPrompt({prompt:null,requirements:null}).resolveTarget());if(!(token instanceof TokenDocumentPF2e)){pendingItems.splice(pendingItems.indexOf(itemSource),1);return}this.#checkRuleSource(ruleSource),this.uuid=ruleSource.uuid=token.uuid}beforePrepareData(){UUIDUtils.isTokenUUID(this.uuid)&&this.test()&&this.actor.synthetics.tokenMarks.set(this.uuid,this.slug)}#checkRuleSource(source){if(!(source.key==="TokenMark"&&source.slug===this.slug))throw ErrorPF2e("Unexpected rule element passed")}}class TokenNameRuleElement extends RuleElementPF2e{static{__name(this,"TokenNameRuleElement")}static{__name2(this,"TokenNameRuleElement")}static defineSchema(){return{...super.defineSchema(),value:new ResolvableValueField({required:!0})}}afterPrepareData(){const name2=this.resolveValue(this.value);if(typeof name2!="string")return this.failValidation("value must resolve to a string");this.test()&&(this.actor.synthetics.tokenOverrides.name=name2)}}class WeaponPotencyRuleElement extends RuleElementPF2e{static{__name(this,"WeaponPotencyRuleElement")}static{__name2(this,"WeaponPotencyRuleElement")}static validActorTypes=["character","npc"];static defineSchema(){const{fields:fields2}=foundry.data;return{...super.defineSchema(),selector:new fields2.StringField({required:!0,nullable:!1,blank:!1}),value:new ResolvableValueField({required:!0})}}beforePrepareData(){if(this.ignored)return;const{weaponPotency}=this.actor.synthetics,selector=this.resolveInjectedProperties(this.selector),{item}=this,potencyValue=this.value??(item.isOfType("weapon")?item.system.runes.potency:0),value=this.resolveValue(potencyValue);if(selector&&typeof value=="number"){const bonusType=AutomaticBonusProgression.isEnabled(this.actor)?"potency":"item",potency={label:this.getReducedLabel(),bonus:value,type:bonusType,predicate:this.predicate};(weaponPotency[selector]??=[]).push(potency)}else this.failValidation("Weapon potency requires at least a selector field and a non-empty value field")}}class RuleElements{static{__name(this,"RuleElements")}static{__name2(this,"RuleElements")}static builtin={ActiveEffectLike:AELikeRuleElement,ActorTraits:ActorTraitsRuleElement,AdjustDegreeOfSuccess:AdjustDegreeOfSuccessRuleElement,AdjustModifier:AdjustModifierRuleElement,AdjustStrike:AdjustStrikeRuleElement,Aura:AuraRuleElement,BaseSpeed:BaseSpeedRuleElement,BattleForm:BattleFormRuleElement,ChoiceSet:ChoiceSetRuleElement,CraftingEntry:CraftingEntryRuleElement,CraftingFormula:CraftingFormulaRuleElement,CreatureSize:CreatureSizeRuleElement,CriticalSpecialization:CritSpecRuleElement,DamageDice:DamageDiceRuleElement,DexterityModifierCap:DexterityModifierCapRuleElement,EphemeralEffect:EphemeralEffectRuleElement,FastHealing:FastHealingRuleElement,FixedProficiency:FixedProficiencyRuleElement,FlatModifier:FlatModifierRuleElement,GrantItem:GrantItemRuleElement,Immunity:ImmunityRuleElement,ItemAlteration:ItemAlterationRuleElement,LoseHitPoints:LoseHitPointsRuleElement,MartialProficiency:MartialProficiencyRuleElement,MultipleAttackPenalty:MultipleAttackPenaltyRuleElement,Note:RollNoteRuleElement,Resistance:ResistanceRuleElement,RollOption:RollOptionRuleElement,RollTwice:RollTwiceRuleElement,Sense:SenseRuleElement,SpecialStatistic:SpecialStatisticRuleElement,Strike:StrikeRuleElement,Striking:StrikingRuleElement,SubstituteRoll:SubstituteRollRuleElement,TempHP:TempHPRuleElement,TokenEffectIcon:TokenEffectIconRuleElement,TokenImage:TokenImageRuleElement,TokenLight:TokenLightRuleElement,TokenMark:TokenMarkRuleElement,TokenName:TokenNameRuleElement,Weakness:WeaknessRuleElement,WeaponPotency:WeaponPotencyRuleElement};static custom={};static get all(){return{...this.builtin,...this.custom}}static fromOwnedItem(options){const rules=[],item=options.parent;for(const[sourceIndex,source]of item.system.rules.entries()){if(typeof source.key!="string"){console.error(`PF2e System | Missing key in rule element ${source.key} on item ${item.name} (${item.uuid})`);continue}const REConstructor=this.custom[source.key]??this.custom[source.key]??this.builtin[source.key];if(REConstructor){const rule=(()=>{try{return new REConstructor(source,{...options,sourceIndex})}catch(error){return options?.suppressWarnings||(console.warn(`PF2e System | Failed to construct rule element ${source.key} on item ${item.name}`,`(${item.uuid})`),console.warn(error)),null}})();rule&&rules.push(rule)}else{const{name:name2,uuid}=item;console.warn(`PF2e System | Unrecognized rule element ${source.key} on item ${name2} (${uuid})`)}}return rules}}const CodeMirror={EditorView,basicSetup,json,jsonLinter:()=>linter(jsonParseLinter()),keybindings:keymap.of([indentWithTab]),ruleElementExtensions:options=>[json(),CodeMirror.jsonLinter(),autocompletion({override:[ruleElementAutocomplete(options)]})]};function ruleElementAutocomplete(options){const validKeysByPath=(()=>options.schema?{"":Object.keys(options.schema)}:{"":["key"]})();return context=>{const node=syntaxTree(context.state).resolveInner(context.pos,-1),isProperty=node.name==="Object"||node.type.name==="PropertyName",isValue=!isProperty&&(node.name==="Property"||node.parent?.name==="Property");if(isProperty){const basePath=resolveNodePath(context,node),keys2=basePath!==null?validKeysByPath[basePath]:[];return keys2?.length?{from:node.from,to:node.to,options:keys2.map(o=>({label:`"${o}"`}))}:null}else if(isValue&&resolveNodePath(context,node)==="key"){const options2=Object.keys(RuleElements.all);return{from:node.from,to:node.to,options:options2.map(o=>({label:`"${o}"`}))}}return null}}__name(ruleElementAutocomplete,"ruleElementAutocomplete"),__name2(ruleElementAutocomplete,"ruleElementAutocomplete");function resolveNodePath(context,node){node=node.type.name==="PropertyName"&&node.parent?node.parent:node;const parent=node.parent;if(!parent||parent.type.name==="JsonText")return"";const parentType=parent.type.name;if(parentType==="\u26A0")return null;const name2=(()=>parentType==="Object"?!parent.parent||parent.parent.type.name==="JsonText"?"":".":parentType==="Property"?context.state.sliceDoc(parent.from,parent.to).match(/^"([^"]*)"/)?.[1]:parentType==="Array"?"[]":null)();if(name2===null)return null;const basePath=resolveNodePath(context,parent);return basePath===null?null:basePath+name2}__name(resolveNodePath,"resolveNodePath"),__name2(resolveNodePath,"resolveNodePath");class RuleElementForm{static{__name(this,"RuleElementForm")}static{__name2(this,"RuleElementForm")}template="systems/pf2e/templates/items/rules/default.hbs";tabs=null;#activeTab=null;get basePath(){return`system.rules.${this.index}`}constructor(options){this.initialize(options)}initialize(options){this.sheet=options.sheet,this.index=options.index,this.rule=options.rule,this.object=options.object??(()=>{const RuleElementClass=RuleElements.all[String(this.rule.key)];if(!RuleElementClass)return null;const actor=new ActorProxyPF2e({_id:foundry.utils.randomID(),name:"temp",type:"character"}),item=new ItemProxyPF2e(this.item.toObject(),{parent:actor});return new RuleElementClass(foundry.utils.deepClone(this.rule),{parent:item,strict:!1,suppressWarnings:!0})})(),this.schema=this.object?.schema??RuleElements.all[String(this.rule.key)]?.schema??null}get item(){return this.sheet.item}get fieldIdPrefix(){return`field-${this.sheet.appId}-${this.index}-`}getInitialValue(){if(this.constructor.name==="RuleElementForm")return{};const initial=this.schema?.getInitialValue();if(!initial)return{};for(const property of["ignored","priority","slug"])delete initial[property];const removeArrays=__name2(object=>{for(const[key,value]of Object.entries(object))Array.isArray(value)?delete object[key]:isObject(value)&&removeArrays(value)},"removeArrays");return removeArrays(initial),initial}async getData(){const[label,recognized]=(()=>{const locPath=`PF2E.RuleElement.${this.rule.key}`,localized=game.i18n.localize(locPath);return localized===locPath?[game.i18n.localize("PF2E.RuleElement.Unrecognized"),!1]:[localized,!0]})(),mergedRule=foundry.utils.mergeObject(this.getInitialValue(),this.rule),validationFailures=(()=>{const fieldFailures=this.object?.validationFailures.fields?.asError().getAllFailures()??{},jointFailures=this.object?.validationFailures.joint?{joint:this.object.validationFailures.joint}:{};return Object.entries({...fieldFailures,...jointFailures}).map(([key,failure])=>key==="joint"?failure.message.replace(/^.*Joint Validation Error:\s*/,""):`${key}: ${failure.message}`)})();return{...pick(this,["index","rule","object"]),item:this.item,label,fieldIdPrefix:this.fieldIdPrefix,recognized,basePath:this.basePath,rule:mergedRule,fields:this.schema?.fields,form:await this.#getFormHelpers(mergedRule),validationFailures}}async#getFormHelpers(rule){const valueTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-value.hbs"),bracketsTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/resolvable-brackets.hbs"),dropZoneTemplate=await getTemplate("systems/pf2e/templates/items/rules/partials/drop-zone.hbs"),getResolvableData=__name2(property=>{const value=foundry.utils.getProperty(rule,property),mode=isBracketedValue(value)?"brackets":isObject(value)?"object":"primitive";return{value,mode,property,path:`${this.basePath}.${property}`}},"getResolvableData");return{resolvableValue:(property,options={})=>valueTemplate({...getResolvableData(property),inputId:`${this.fieldIdPrefix}${property}`,fileInput:options.hash?.fileInput??!1}),resolvableAddBracket:property=>getResolvableData(property).mode!=="brackets"?"":createHTMLElement("a",{children:[fontAwesomeIcon("plus",{fixedWidth:!0})],dataset:{action:"add-bracket",property}}).outerHTML,resolvableBrackets:property=>bracketsTemplate(getResolvableData(property)),dropZone:(dropId,dropText,dropTooltip)=>dropZoneTemplate({dropId,dropText,dropTooltip})}}async render(){const data=await this.getData();return renderTemplate("systems/pf2e/templates/items/rules/partials/outer.hbs",{...data,template:await renderTemplate(this.template,data)})}async updateItem(updates){const rules=this.item.toObject().system.rules,result=foundry.utils.mergeObject(this.rule,updates,{performDeletions:!0});this.schema&&cleanDataUsingSchema(this.schema.fields,result),rules[this.index]=result,await this.item.update({"system.rules":rules})}activateListeners(html){this.element=html;const selectorElement=htmlQuery(html,".selector-list");tagify(selectorElement);const priorityInput=htmlQuery(html,".rule-element-header .priority input");priorityInput?.addEventListener("change",event2=>{event2.stopPropagation();const value=priorityInput.value;value===""||Number.isNaN(Number(value))?this.updateItem({"-=priority":null}):this.updateItem({priority:Number(value)})});for(const button of htmlQueryAll(html,"[data-action=toggle-brackets]"))button.addEventListener("click",()=>{const property=button.dataset.property??"value",value=foundry.utils.getProperty(this.rule,property);isBracketedValue(value)?this.updateItem({[property]:""}):this.updateItem({[property]:{brackets:[{value:""}]}})});for(const button of htmlQueryAll(html,"[data-action=add-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=foundry.utils.getProperty(this.rule,property);isBracketedValue(value)&&(value.brackets.push({value:""}),this.updateItem({[property]:value}))})}for(const button of htmlQueryAll(html,"[data-action=delete-bracket]")){const property=button.dataset.property??"value";button.addEventListener("click",()=>{const value=foundry.utils.getProperty(this.rule,property),idx=Number(htmlClosest(button,"[data-idx]")?.dataset.idx);isBracketedValue(value)&&(value.brackets.splice(idx,1),this.updateItem({[property]:value}))})}if(this.tabs){for(const anchor of htmlQueryAll(html,"a[data-rule-tab]"))anchor.addEventListener("click",()=>{this.activateTab(html,anchor.dataset.ruleTab)});this.activateTab(html,this.#activeTab)}for(const dropZone of htmlQueryAll(html,"div.rules-drop-zone"))dropZone.addEventListener("drop",event2=>{this.onDrop(event2,dropZone)})}async onDrop(event2,_element){const data=event2.dataTransfer?.getData("text/plain");return data?await ItemPF2e.fromDropData(JSON.parse(data))??null:null}activateTab(html,tabName){if(!this.tabs)return;const activeTab=tabName??this.tabs.names.at(0);if(!(!activeTab||!this.tabs.names.includes(activeTab))){this.#activeTab=activeTab;for(const element of htmlQueryAll(html,"[data-rule-tab]"))element.dataset.ruleTab===activeTab?(element.classList.add("active"),element.tagName!=="A"&&(element.style.display=this.tabs.displayStyle)):(element.classList.remove("active"),element.tagName!=="A"&&(element.style.display="none"))}}updateObject(source){if(typeof source=="string"){try{this.rule=JSON.parse(source)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,source),error}return}source=foundry.utils.mergeObject(foundry.utils.duplicate(this.rule),source);for(const slider of htmlQueryAll(this.element,"input[type=range"))slider.style.pointerEvents="none";cleanPredicate(source),this.schema&&cleanDataUsingSchema(this.schema.fields,source),this.rule=source}}function cleanDataUsingSchema(schema,data){const{fields:fields2}=foundry.data,deleteIfInitial=__name2((key,field)=>{if(data[key]===void 0)return!0;const initialValue=typeof field.initial=="function"?field.initial(data):field.initial,valueRaw=data[key],value=isObject$1(valueRaw)&&isObject$1(initialValue)?{...initialValue,...valueRaw}:valueRaw;return equals(initialValue,value)&&delete data[key],!(key in data)},"deleteIfInitial");for(const[key,field]of Object.entries(schema))if(!deleteIfInitial(key,field)){if(field instanceof ResolvableValueField){data[key]=field.clean(data[key]),deleteIfInitial(key,field);continue}if("fields"in field){const value=data[key];if(isObject$1(value)){cleanDataUsingSchema(field.fields,value),deleteIfInitial(key,field);continue}}if(field instanceof fields2.ArrayField&&field.element instanceof fields2.SchemaField){const value=data[key];if(Array.isArray(value)){for(const data2 of value)isObject$1(data2)&&(data2.predicate&&cleanPredicate(data2),cleanDataUsingSchema(field.element.fields,data2));continue}}field instanceof fields2.StringField&&(data[key]=field.clean(data[key],{}),deleteIfInitial(key,field))}}__name(cleanDataUsingSchema,"cleanDataUsingSchema"),__name2(cleanDataUsingSchema,"cleanDataUsingSchema");function cleanPredicate(source){const predicateValue=source.predicate;if(typeof predicateValue=="string")if(predicateValue.trim()==="")delete source.predicate;else try{source.predicate=JSON.parse(predicateValue)}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),error}}__name(cleanPredicate,"cleanPredicate"),__name2(cleanPredicate,"cleanPredicate");class AuraForm extends RuleElementForm{static{__name(this,"AuraForm")}static{__name2(this,"AuraForm")}template="systems/pf2e/templates/items/rules/aura.hbs";tabs={names:["basic","effects","appearance"],displayStyle:"grid"};#effectsMap=new Map;get effectsArray(){return[...this.#effectsMap.values()]}getInitialValue(){return this.#effectsMap.clear(),this.#effectsMap=new Map(this.object.effects.map((e,index)=>[index,foundry.utils.deepClone(e)])),super.getInitialValue()}activateListeners(html){super.activateListeners(html);const traitsElement=htmlQuery(html,".tagify-traits");if(traitsElement){const whitelist={...CONFIG.PF2E.spellTraits,...CONFIG.PF2E.actionTraits};tagify(traitsElement,{whitelist,enforceWhitelist:!1})}for(const eventsElement of htmlQueryAll(html,".tagify-events")){const whitelist=[["enter",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.Enter")],["turn-start",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnStart")],["turn-end",game.i18n.localize("PF2E.RuleEditor.Aura.Effects.EventsOptions.TurnEnd")]].sort((a,b)=>a[1].localeCompare(b[1],game.i18n.lang));tagify(eventsElement,{whitelist:mapToObj(whitelist,w=>[w[0],w[1]]),enforceWhitelist:!0})}for(const element of htmlQueryAll(html,"a[data-action=remove-effect]"))element.addEventListener("click",()=>{this.#deleteEffect(element.dataset.effectId)});for(const button of htmlQueryAll(html,"div[data-rule-tab=effects] button[data-action=toggle-brackets]")){const fieldset=htmlClosest(button,"fieldset"),select=htmlQuery(fieldset,"select"),input=htmlQuery(fieldset,"input");select&&input&&!select.value&&(button.disabled=!0,input.disabled=!0)}for(const key of["border","highlight"]){const inputName=`system.rules.${this.index}.appearance.${key}.color`,textInput=htmlQuery(html,`input[type=text][name="${inputName}"]`),colorInput=htmlQuery(html,`input[type=color][data-edit="${inputName}"]`),checkbox=htmlQuery(html,`input[type=checkbox][name="${inputName}"]`);textInput&&colorInput&&checkbox&&(this.object.appearance[key]?.color==="user-color"?(textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0):checkbox.removeAttribute("name"),checkbox.addEventListener("change",()=>{checkbox.checked?(checkbox.name=textInput.name,textInput.removeAttribute("name"),textInput.disabled=!0,colorInput.disabled=!0,textInput.value=colorInput.value=userColorForActor(this.object.actor)):(textInput.name=checkbox.name,checkbox.removeAttribute("name"),textInput.disabled=!1,colorInput.disabled=!1,textInput.value=colorInput.value="#000000")}))}const translationX=htmlQuery(html,"input[data-translation=x]"),translationY=htmlQuery(html,"input[data-translation=y]");translationX&&translationY&&(translationX.addEventListener("change",()=>{translationX.value!==""&&translationY.value===""&&(translationY.value=translationX.value)}),translationY.addEventListener("change",()=>{translationY.value!==""&&translationX.value===""&&(translationX.value=translationY.value)}))}async getData(){const{border,highlight}=this.object.appearance,userColor=userColorForActor(this.object.actor);return{...await super.getData(),affectsOptions:{all:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.All",allies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Allies",enemies:"PF2E.RuleEditor.Aura.Effects.AffectsOptions.Enemies"},effects:this.effectsArray.map(e=>({...e,item:fromUuidSync(e.uuid)})),borderColor:border?.color==="user-color"?userColor:border?.color??null,highlightColor:highlight.color==="user-color"?userColor:highlight?.color,saveTypes:CONFIG.PF2E.saves,isImageFile:isImageFilePath(this.rule.appearance?.texture?.src)}}async onDrop(event2,element){const{id}=element.dataset;if(id!=="aura-effect-drop")return null;const item=await super.onDrop(event2,element);return!item?.isOfType("effect")||!this.schema?null:(this.#addEffect(item.uuid),item)}async updateItem(updates){const expanded=foundry.utils.expandObject(updates);return expanded.effects&&(expanded.effects=this.#updateEffectsMap(expanded)),super.updateItem(expanded)}updateObject(source){source.effects=this.#updateEffectsMap(source);for(const key of["level","radius"]){if(key in source&&!source[key]){delete source[key];continue}const stringValue=source[key],maybeIntegerValue=typeof stringValue=="string"&&/^\d+$/.test(stringValue)?Number(stringValue):NaN;Number.isInteger(maybeIntegerValue)&&(source[key]=maybeIntegerValue)}const appearance=source.appearance;appearance?.border?.color===null&&(appearance.border.color="#000000"),appearance?.highlight?.color===null&&(appearance.highlight.color="#000000");const texture=appearance?.texture;if(texture){if(texture.translation){const{x,y}=texture.translation;!x&&!y&&(texture.translation=null)}texture.src?isImageFilePath(texture.src)&&(texture.loop=!0,texture.playbackRate=1):appearance.texture=null}super.updateObject(source)}#addEffect(uuid){const index=this.#effectsMap.size+1;this.#effectsMap.set(index,{uuid}),this.updateItem({effects:this.effectsArray})}#updateEffectsMap(source){return this.#effectsMap=new Map(Object.values(source.effects??{}).map((data,index)=>{const updatedData=foundry.utils.deepClone(data),deletions={};if(updatedData.save&&(updatedData.save.type??data.save?.type?updatedData.save.dc||=null:deletions["-=save"]=null),updatedData.affects!=="enemies"&&updatedData.includesSelf&&(deletions["-=includesSelf"]=null),updatedData.removeOnExit&&(deletions["-=removeOnExit"]=null),updatedData.predicate)try{const parsed=JSON.parse(String(updatedData.predicate));updatedData.predicate=Array.isArray(parsed)?parsed:[]}catch{deletions["-=predicate"]=null}else deletions["-=predicate"]=null;return[index,foundry.utils.mergeObject(updatedData,deletions,{performDeletions:!0})]})),this.effectsArray}#deleteEffect(id){const index=Number(id);Number.isNaN(index)||this.#effectsMap.delete(index)&&this.updateItem({effects:this.effectsArray})}}class FastHealingForm extends RuleElementForm{static{__name(this,"FastHealingForm")}static{__name2(this,"FastHealingForm")}template="systems/pf2e/templates/items/rules/fast-healing.hbs";activateListeners(html){super.activateListeners(html);const selectorElement=htmlQuery(html,".deactivated-by");if(selectorElement){const whitelist=CONFIG.PF2E.weaknessTypes;tagify(selectorElement,{whitelist,enforceWhitelist:!1})}}async getData(){return{...await super.getData(),types:{"fast-healing":"PF2E.Encounter.Broadcast.FastHealing.fast-healing.Name",regeneration:"PF2E.Encounter.Broadcast.FastHealing.regeneration.Name"}}}updateObject(source){delete source[source.type==="regeneration"?"details":"deactivatedBy"],super.updateObject(source)}}class FlatModifierForm extends RuleElementForm{static{__name(this,"FlatModifierForm")}static{__name2(this,"FlatModifierForm")}template="systems/pf2e/templates/items/rules/flat-modifier.hbs";get isDamage(){return[this.rule.selector??[]].flat().some(s=>s==="damage"||String(s).endsWith("-damage"))}activateListeners(html){super.activateListeners(html),htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})})}async getData(){const data=await super.getData(),types=(()=>{const abpEnabled=AutomaticBonusProgression.isEnabled(null),entries=Array.from(MODIFIER_TYPES).filter(t=>abpEnabled||t!=="potency").map(t=>[t,game.i18n.localize(`PF2E.ModifierType.${t}`)]).sort((a,b)=>a[0]==="untyped"?-1:b[0]==="untyped"?1:a[1].localeCompare(b[1]));return fromPairs(entries)})();return{...data,selectorIsArray:Array.isArray(this.rule.selector),abilities:CONFIG.PF2E.abilities,types,damageCategories:pick(CONFIG.PF2E.damageCategories,Array.from(DAMAGE_CATEGORIES_UNIQUE)),isDamage:this.isDamage}}updateObject(formData){delete formData[formData.type==="ability"?"value":"ability"],formData.critical=tupleHasValue([!1,"false"],formData.critical)?!1:!!formData.critical||null,this.isDamage||(delete formData.damageCategory,delete formData.damageType,delete formData.critical),super.updateObject(formData)}}class GrantItemForm extends RuleElementForm{static{__name(this,"GrantItemForm")}static{__name2(this,"GrantItemForm")}template="systems/pf2e/templates/items/rules/grant-item.hbs";async getData(){const data=await super.getData(),uuid=this.rule.uuid?String(this.rule.uuid):null,granted=uuid?await fromUuid(uuid):null;return{...data,granted}}updateObject(ruleData){super.updateObject(ruleData),typeof ruleData.uuid=="string"&&(ruleData.uuid=ruleData.uuid.trim())}}class MultipleAttackPenaltyForm extends RuleElementForm{static{__name(this,"MultipleAttackPenaltyForm")}static{__name2(this,"MultipleAttackPenaltyForm")}template="systems/pf2e/templates/items/rules/multiple-attack-penalty.hbs"}class RollNoteForm extends RuleElementForm{static{__name(this,"RollNoteForm")}static{__name2(this,"RollNoteForm")}template="systems/pf2e/templates/items/rules/note.hbs";async getData(){return{...await super.getData(),selectorIsArray:Array.isArray(this.rule.selector)}}activateListeners(html){super.activateListeners(html),htmlQuery(html,"[data-action=toggle-selector]")?.addEventListener("click",()=>{const selector=this.rule.selector,newValue=Array.isArray(selector)?selector.at(0)??"":[selector??""].filter(s=>!!s);this.updateItem({selector:newValue})});const optionsEl=htmlQuery(html,".outcomes");tagify(optionsEl,{whitelist:[...DEGREE_OF_SUCCESS_STRINGS],maxTags:3})}updateObject(ruleData){const shouldBeHidden=htmlQuery(this.element,".hidden-value")?.checked,isHidden=["gm","owner"].includes(String(this.rule.visibility));shouldBeHidden!==isHidden&&(shouldBeHidden?ruleData.visibility="owner":ruleData.visibility=null),Array.isArray(ruleData.outcome)&&ruleData.outcome.length===0&&delete ruleData.outcome,typeof ruleData.title=="string"&&(ruleData.title=ruleData.title.trim()),super.updateObject(ruleData)}}class TokenImageForm extends RuleElementForm{static{__name(this,"TokenImageForm")}static{__name2(this,"TokenImageForm")}template="systems/pf2e/templates/items/rules/token-image.hbs";async getData(){return{...await super.getData(),scaleEnabled:this.object.scale!==null}}activateListeners(html){super.activateListeners(html);const tintInput=htmlQuery(html,`input[name="system.rules.${this.index}.tint"]`),scaleCheckbox=htmlQuery(html,"input[data-action=toggle-scale]"),scaleInput=htmlQuery(html,`input[name="system.rules.${this.index}.scale"]`);tintInput&&scaleCheckbox&&scaleInput&&(tintInput.id=`${this.fieldIdPrefix}-tint`,scaleInput.id=`${this.fieldIdPrefix}-scale`,scaleInput.disabled=this.object.scale===null,scaleCheckbox.addEventListener("change",event2=>{event2.stopPropagation();const newValue=this.object.scale===null?1:null;this.updateItem({scale:newValue})}))}}class TokenLightForm extends RuleElementForm{static{__name(this,"TokenLightForm")}static{__name2(this,"TokenLightForm")}template="systems/pf2e/templates/items/rules/token-light.hbs";tabs={names:["basic","animation","advanced"],displayStyle:"grid"};async getData(){const data=await super.getData();return{...data,colorationTechniques:AdaptiveLightingShader.SHADER_TECHNIQUES,light:data.rule.value,lightAnimations:mapValues$1(CONFIG.Canvas.lightAnimations,value=>value.label)}}}const RULE_ELEMENT_FORMS={Aura:AuraForm,FastHealing:FastHealingForm,FlatModifier:FlatModifierForm,GrantItem:GrantItemForm,MultipleAttackPenalty:MultipleAttackPenaltyForm,Note:RollNoteForm,TokenImage:TokenImageForm,TokenLight:TokenLightForm};class ItemSheetPF2e extends ItemSheet{static{__name(this,"ItemSheetPF2e")}static{__name2(this,"ItemSheetPF2e")}constructor(item,options={}){super(item,options),this.options.classes.push(this.item.type)}static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("pf2e","item"),{...options,width:695,height:460,template:"systems/pf2e/templates/items/sheet.hbs",scrollY:[".tab.active",".inventory-details","div[data-rule-tab]"],tabs:[{navSelector:".tabs",contentSelector:".sheet-body",initial:"description"},{navSelector:".mystify-nav",contentSelector:".mystify-sheet",initial:"unidentified"}],hasSidebar:!1}}#selectedRuleElementType=Object.keys(RuleElements.all).at(0)??null;#editingRuleElementIndex=null;#rulesLastScrollTop=null;#ruleElementForms=[];get editingRuleElement(){return this.#editingRuleElementIndex===null?null:this.item.toObject().system.rules[this.#editingRuleElementIndex]??null}get validTraits(){return objectHasKey(CONFIG.PF2E.Item.traits,this.item.type)?CONFIG.PF2E.Item.traits[this.item.type]:null}async getData(options={}){options.id=this.id,options.editable=this.isEditable,options.sheetConfig&&=Object.values(CONFIG.Item.sheetClasses[this.item.type]).filter(c=>c.canConfigure).length>1;const{item}=this;this.#createRuleElementForms();const enrichedContent={},rollData={...this.item.getRollData(),...this.actor?.getRollData()};enrichedContent.description=await TextEditor.enrichHTML(item._source.system.description.value,{rollData,secrets:item.isOwner,async:!0}),enrichedContent.gmNotes=await TextEditor.enrichHTML(item.system.description.gm.trim(),{rollData,async:!0});const validTraits=this.validTraits,hasRarity=!item.isOfType("action","condition","deity","effect","lore","melee"),itemTraits=item.system.traits?.value??[],sourceTraits=item._source.system.traits?.value??[],traits=validTraits?createSheetTags(validTraits,itemTraits):null,traitTagifyData=validTraits?createTagifyTraits(itemTraits,{sourceTraits,record:validTraits}):null;return{itemType:null,showTraits:this.validTraits!==null,sidebarTitle:game.i18n.format("PF2E.Item.SidebarSummary",{type:game.i18n.localize(`TYPES.Item.${this.item.type}`)}),sidebarTemplate:options.hasSidebar?`systems/pf2e/templates/items/${sluggify(item.type)}-sidebar.hbs`:null,detailsTemplate:`systems/pf2e/templates/items/${sluggify(item.type)}-details.hbs`,cssClass:this.isEditable?"editable":"locked",editable:this.isEditable,document:item,item,isPhysical:!1,data:item.system,fieldIdPrefix:`field-${this.appId}-`,enrichedContent,limited:this.item.limited,options:this.options,owner:this.item.isOwner,title:this.title,user:{isGM:game.user.isGM},rarity:hasRarity?this.item.system.traits?.rarity??"common":null,rarities:CONFIG.PF2E.rarityTraits,traits,traitTagifyData,enabledRulesUI:game.user.isGM||game.settings.get("pf2e","enabledRulesUI"),ruleEditing:!!this.editingRuleElement,rules:{selection:{selected:this.#selectedRuleElementType,types:sortStringRecord(Object.keys(RuleElements.all).reduce((result,key)=>foundry.utils.mergeObject(result,{[key]:`PF2E.RuleElement.${key}`}),{}))},elements:await Promise.all(this.#ruleElementForms.map(async form=>({template:await form.render()})))},proficiencies:CONFIG.PF2E.proficiencyLevels}}#createRuleElementForms(){const rules=this.item.toObject().system.rules,previousForms=[...this.#ruleElementForms],processedRules=rules.map((rule,index)=>{const options={sheet:this,index,rule,object:this.item.rules.find(r=>r.sourceIndex===index)??null},FormClass=RULE_ELEMENT_FORMS[String(rule.key)]??RuleElementForm,existing=previousForms.find(f=>equals(f.rule,rule)&&f.constructor.name===FormClass.name)??null;return existing&&previousForms.splice(previousForms.indexOf(existing),1),{options,FormClass,existing}});for(const rule of processedRules.filter(r=>!r.existing)){const existing=this.#ruleElementForms.at(rule.options.index),alreadyMatched=processedRules.some(r=>r.existing===existing);existing?.constructor.name===rule.FormClass.name&&!alreadyMatched&&(rule.existing=existing)}this.#ruleElementForms=processedRules.map(processed=>processed.existing?(processed.existing.initialize(processed.options),processed.existing):new processed.FormClass(processed.options))}onTagSelector(anchor){if((anchor.dataset.tagSelector??"")!=="basic")throw ErrorPF2e("Item sheets can only use the basic tag selector");const propertyIsFlat=anchor.dataset.flat==="true",objectProperty=anchor.dataset.property??"",title=anchor.dataset.title,configTypes=(anchor.dataset.configTypes??"").split(",").map(type=>type.trim()).filter(tag=>tupleHasValue(SELECTABLE_TAG_FIELDS,tag)),selectorOptions={objectProperty,configTypes,title,flat:propertyIsFlat};anchor.dataset.noCustom==="true"?selectorOptions.allowCustom=!1:this.actor&&configTypes.includes("attackEffects")&&(selectorOptions.customChoices=this.getAttackEffectOptions()),new TagSelectorBasic(this.item,selectorOptions).render(!0)}getAttackEffectOptions(){return(this.actor?.items.contents??[]).filter(i=>i.isOfType("action","consumable")).reduce((options,item)=>{const key=item.slug??sluggify(item.name);return{...options,[key]:item.name}},foundry.utils.deepClone(CONFIG.PF2E.attackEffects))}async activateEditor(name2,options={},initialContent=""){const sourceContent=name2==="system.description.value"?this.item._source.system.description.value:initialContent,mutuallyExclusive=["system.description.gm","system.description.value"];if(mutuallyExclusive.includes(name2)){const html=this.element[0];for(const elementName of mutuallyExclusive.filter(n=>n!==name2)){const element=htmlQuery(html,`[data-edit="${elementName}"]`),section=htmlClosest(element,".editor-container");section&&(section.style.display="none")}htmlQuery(html,".tab.description")?.classList.add("editing")}const instance=await super.activateEditor(name2,options,sourceContent);return"startContent"in instance&&sourceContent.trim()===""&&instance.resetContent(sourceContent),instance}async close(options){return this.#editingRuleElementIndex=null,super.close(options)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const anchor of htmlQueryAll(html,"a.tag-selector"))anchor.addEventListener("click",()=>this.onTagSelector(anchor));const rulesPanel=htmlQuery(html,".tab[data-tab=rules]"),slugInput=htmlQuery(rulesPanel,'input[name="system.slug"]');slugInput&&(slugInput.addEventListener("change",()=>{slugInput.value=sluggify(slugInput.value)}),htmlQuery(rulesPanel,"a[data-action=regenerate-slug]")?.addEventListener("click",()=>{if(this._submitting)return;slugInput.value=sluggify(this.item.name);const event2=new Event("change");slugInput.dispatchEvent(event2)}));const ruleElementSelect=htmlQuery(rulesPanel,"select[data-action=select-rule-element]");ruleElementSelect?.addEventListener("change",()=>{this.#selectedRuleElementType=ruleElementSelect.value});for(const anchor of htmlQueryAll(rulesPanel,"a.add-rule-element"))anchor.addEventListener("click",async event2=>{await this._onSubmit(event2);const rulesData=this.item.toObject().system.rules,key=this.#selectedRuleElementType??"NewRuleElement";this.item.update({"system.rules":rulesData.concat({key})})});for(const anchor of htmlQueryAll(rulesPanel,"a.edit-rule-element"))anchor.addEventListener("click",async()=>{if(this._submitting)return;const index=Number(anchor.dataset.ruleIndex??"NaN")??null;this.#editingRuleElementIndex=index,this.#rulesLastScrollTop=rulesPanel?.scrollTop??null,this.render()});for(const anchor of htmlQueryAll(rulesPanel,".rules a.remove-rule-element"))anchor.addEventListener("click",async event2=>{await this._onSubmit(event2);const rules2=this.item.toObject().system.rules,index=Number(anchor.dataset.ruleIndex??"NaN");rules2&&Number.isInteger(index)&&rules2.length>index&&(rules2.splice(index,1),this.item.update({"system.rules":rules2}))});for(const anchor of htmlQueryAll(rulesPanel,"a[data-clipboard]"))anchor.addEventListener("click",()=>{const clipText=anchor.dataset.clipboard;clipText&&(game.clipboard.copyPlainText(clipText),ui.notifications.info(game.i18n.format("PF2E.ClipboardNotification",{clipText})))});const editingRuleElement=this.editingRuleElement;if(editingRuleElement){const ruleText=JSON.stringify(editingRuleElement,null,2),schema=RuleElements.all[String(editingRuleElement.key)]?.schema.fields,view=new CodeMirror.EditorView({doc:ruleText,extensions:[CodeMirror.basicSetup,CodeMirror.keybindings,...CodeMirror.ruleElementExtensions({schema})]});html.querySelector(".rule-editing .editor-placeholder")?.replaceWith(view.dom);const closeBtn=html.querySelector(".rule-editing button[data-action=close]");closeBtn?.addEventListener("click",()=>{this.#editingRuleElementIndex=null,this.render()}),closeBtn?.removeAttribute("disabled"),html.querySelector(".rule-editing button[data-action=apply]")?.addEventListener("click",()=>{const value=view.state.doc.toString();if(this.#editingRuleElementIndex===null){this.#editingRuleElementIndex=null,this.render();return}try{const rules2=this.item.toObject().system.rules;rules2[this.#editingRuleElementIndex]=JSON.parse(value),this.#editingRuleElementIndex=null,this.item.update({"system.rules":rules2})}catch(error){if(error instanceof Error)throw ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.RuleElementSyntax",{message:error.message})),console.warn("Syntax error in rule element definition.",error.message,value),error}})}const ruleSections=html.querySelectorAll(".rules .rule-form");for(const ruleSection of Array.from(ruleSections)){const idx=ruleSection.dataset.idx?Number(ruleSection.dataset.idx):NaN;this.#ruleElementForms.at(idx)?.activateListeners(ruleSection)}InlineRollLinks.listen(html,this.item);const{validTraits}=this,tagElement=htmlQuery(this.form,":scope > header .tags"),traitsPrepend=html.querySelector(".traits-extra");if(validTraits!==null&&tagElement instanceof HTMLInputElement){const tags=tagify(tagElement,{whitelist:validTraits});traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}else tagElement&&traitsPrepend&&tagElement.append(traitsPrepend.content);tagify(htmlQuery(html,'input[type=text][name="system.traits.otherTags"]'),{maxTags:6});const modifiedPropertyFields=htmlQueryAll(html,"[data-property]");for(const input of modifiedPropertyFields){const propertyPath=input.dataset.property??"",baseValue=input.dataset.valueBase??String(foundry.utils.getProperty(this.item._source,propertyPath)??"").trim();input.addEventListener("focus",()=>{input.dataset.value=input.value,input.value=baseValue,input.name=propertyPath}),input.addEventListener("blur",()=>{input.removeAttribute("name"),input.value===baseValue&&(input.value=input.dataset.value??"")})}htmlQuery(html,".add-skill-variant")?.addEventListener("click",()=>{if(!this.item.isOfType("lore"))return;const variants=this.item.system.variants??{},index=Object.keys(variants).length;this.item.update({[`system.variants.${index}`]:{label:"+X in terrain",options:""}})});for(const button of htmlQueryAll(html,".skill-variants .remove-skill-variant"))button.addEventListener("click",event2=>{if(!(event2.currentTarget instanceof HTMLElement))return;const index=event2.currentTarget.dataset.skillVariantIndex;this.item.update({[`system.variants.-=${index}`]:null})});if(this.isEditable&&game.user.isGM&&!this.item.system.description.gm&&!(this.item.isOfType("spell")&&this.item.isVariant)){const descriptionEditors=htmlQuery(html,".tab[data-tab=description]"),mainEditor=htmlQuery(descriptionEditors,".main .editor");if(!mainEditor)throw ErrorPF2e("Unexpected error retrieving description editor");const addGMNotesLink=document.createElement("a");addGMNotesLink.className=addGMNotesLink.dataset.action="add-gm-notes",addGMNotesLink.innerHTML=fontAwesomeIcon("fa-note-medical",{style:"regular"}).outerHTML,addGMNotesLink.dataset.tooltip="PF2E.Item.GMNotes.Add",mainEditor.prepend(addGMNotesLink),addGMNotesLink.addEventListener("click",()=>{htmlQuery(descriptionEditors,".gm-notes")?.classList.add("has-content"),this.activateEditor("system.description.gm")})}const rules=htmlQuery(html,".rule-element-forms");rules&&Sortable.create(rules,{...SORTABLE_BASE_OPTIONS,handle:".drag-handle",onEnd:async event2=>{const currentIndex=event2.oldDraggableIndex,newIndex=event2.newDraggableIndex;if(currentIndex===void 0||newIndex===void 0){this.render();return}const rules2=this.item.toObject().system.rules,movingRule=rules2.at(currentIndex);movingRule&&newIndex<=rules2.length?(rules2.splice(currentIndex,1),rules2.splice(newIndex,0,movingRule),await this.item.update({"system.rules":rules2})||this.render()):this.render()}});const refreshAnchor=htmlQuery(html.closest("div.item.sheet"),"a.refresh-from-compendium");refreshAnchor&&(this.item.system.rules.some(r=>typeof r.key=="string"&&["ChoiceSet","GrantItem"].includes(r.key))?(refreshAnchor.classList.add("disabled"),refreshAnchor.dataset.tooltip="PF2E.Item.RefreshFromCompendium.Tooltip.Disabled"):refreshAnchor.dataset.tooltip="PF2E.Item.RefreshFromCompendium.Tooltip.Enabled")}_getSubmitData(updateData=null){const fd=new FormDataExtended(this.form,{editors:this.editors}),data=updateData?foundry.utils.mergeObject(fd.object,updateData):foundry.utils.expandObject(fd.object),flattenedData=foundry.utils.flattenObject(data);return processTagifyInSubmitData(this.form,flattenedData),flattenedData}_getHeaderButtons(){const buttons=super._getHeaderButtons();return this.isEditable&&this.item.sourceId?.startsWith("Compendium.")&&(this.actor||!this.item.uuid.startsWith("Compendium."))&&buttons.unshift({label:"PF2E.Item.RefreshFromCompendium.Label",class:"refresh-from-compendium",icon:"fa-solid fa-sync-alt",onclick:()=>{!this.item.system.rules.some(r=>typeof r.key=="string"&&["ChoiceSet","GrantItem"].includes(r.key))&&this.item.refreshFromCompendium()}}),buttons}_canDragDrop(_selector){return this.item.isOwner}async _onSubmit(event2,{updateData=null,preventClose=!1,preventRender=!1}={}){for(const input of htmlQueryAll(this.form,"tags ~ input"))input.value===""&&(input.value="[]");return super._onSubmit(event2,{updateData,preventClose,preventRender})}async _updateObject(event2,formData){const expanded=foundry.utils.expandObject(formData),form=htmlClosest(event2.target,".rule-form[data-idx]");if(form){const idx=Number(form.dataset.idx),ruleForm=this.#ruleElementForms[idx],itemRules=this.item.toObject().system.rules;if(idx>=itemRules.length||!ruleForm)throw ErrorPF2e(`Invalid rule form update, no rule form available at index ${idx}`);const incomingData=expanded.system?.rules?.[idx];incomingData&&(ruleForm.updateObject(incomingData),itemRules[idx]=ruleForm.rule,this.item.update({"system.rules":itemRules}))}return delete expanded.system?.rules,super._updateObject(event2,foundry.utils.flattenObject(expanded))}async _render(force,options){if(await maintainFocusInRender(this,()=>super._render(force,options)),this.#editingRuleElementIndex===null&&this.#rulesLastScrollTop){const html=this.element[0],rulesTab=htmlQuery(html,".tab[data-tab=rules]");rulesTab&&(rulesTab.scrollTop=this.#rulesLastScrollTop),this.#rulesLastScrollTop=null}}}class SettingsMenuPF2e extends FormApplication{static{__name(this,"SettingsMenuPF2e")}static{__name2(this,"SettingsMenuPF2e")}static namespace;cache={};static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("settings-menu","sheet"),foundry.utils.mergeObject(options,{title:`PF2E.SETTINGS.${this.namespace.titleCase()}.Name`,id:`${this.namespace}-settings`,template:"systems/pf2e/templates/system/settings/menu.hbs",width:550,height:"auto",tabs:[{navSelector:".sheet-tabs",contentSelector:"form"}],closeOnSubmit:!1,submitOnChange:!0})}static get prefix(){return`${this.namespace}.`}get namespace(){return this.constructor.namespace}get prefix(){return this.constructor.prefix}static SETTINGS;static get settings(){return{}}static registerSettings(){const settings=this.settings;for(const setting of this.SETTINGS)game.settings.register("pf2e",`${this.prefix}${setting}`,{...settings[setting],scope:"world",config:!1})}async getData(){const settings=this.constructor.settings,templateData=settingsToSheetData(settings,this.cache,this.prefix);return foundry.utils.mergeObject(await super.getData(),{settings:templateData,instructions:`PF2E.SETTINGS.${this.namespace.titleCase()}.Hint`})}activateListeners($html){super.activateListeners($html);const html=$html[0],{highlightSetting}=this.options;if(highlightSetting){const formGroup=htmlClosest(htmlQuery(html,`label[for="${highlightSetting}"]`),".form-group");formGroup&&(formGroup.style.animation="glow 0.75s infinite alternate")}}async _updateObject(event2,data){for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`,value=data[key];this.cache[key]=value,event2.type==="submit"&&await game.settings.set("pf2e",settingKey,value)}event2.type==="submit"?this.close():this.render()}_injectHTML($html){super._injectHTML($html);for(const key of this.constructor.SETTINGS){const settingKey=`${this.prefix}${key}`;this.cache[key]=game.settings.get("pf2e",settingKey)}}}function settingsToSheetData(settings,cache,prefix=""){return Object.entries(settings).reduce((result,[key,setting])=>{const lookupKey=`${prefix}${key}`,value=key in cache?cache[key]:game.settings.get("pf2e",lookupKey);return cache[key]=value,result[key]={...setting,key,value,isSelect:!!setting.choices,isCheckbox:setting.type===Boolean},result},{})}__name(settingsToSheetData,"settingsToSheetData"),__name2(settingsToSheetData,"settingsToSheetData");function isHomebrewFlagCategory(value){return isObject$1(value)&&Object.entries(value).every(([_hbKey,hbLabel])=>typeof hbLabel=="string"||isObject(hbLabel)&&isLabelAndDescription(hbLabel))}__name(isHomebrewFlagCategory,"isHomebrewFlagCategory"),__name2(isHomebrewFlagCategory,"isHomebrewFlagCategory");function isHomebrewCustomDamage(value){return Object.values(value).every(value2=>isObject(value2)&&typeof value2.label=="string"&&(!value2.category||["physical","energy"].includes(value2.category)))}__name(isHomebrewCustomDamage,"isHomebrewCustomDamage"),__name2(isHomebrewCustomDamage,"isHomebrewCustomDamage");function isLabelAndDescription(obj){return typeof obj.label=="string"&&typeof obj.description=="string"}__name(isLabelAndDescription,"isLabelAndDescription"),__name2(isLabelAndDescription,"isLabelAndDescription");function prepareReservedTerms(){const universalReservedTerms=new Set([...Object.keys(CONFIG.PF2E.damageTypes),...Object.keys(CONFIG.PF2E.damageCategories),...Object.keys(CONFIG.PF2E.immunityTypes),...Object.keys(CONFIG.PF2E.resistanceTypes),...Object.keys(CONFIG.PF2E.weaknessTypes),"none","null","undefined"]);return{baseWeapons:new Set([...Object.keys(CONFIG.PF2E.baseWeaponTypes),...universalReservedTerms]),creatureTraits:new Set([...Object.keys(CONFIG.PF2E.creatureTraits),...universalReservedTerms]),damageTypes:universalReservedTerms,equipmentTraits:new Set([...Object.keys(CONFIG.PF2E.equipmentTraits),...universalReservedTerms]),featTraits:new Set([...Object.keys(CONFIG.PF2E.actionTraits),...universalReservedTerms]),languages:new Set([...Object.keys(CONFIG.PF2E.languages),...universalReservedTerms]),spellTraits:new Set([...Object.keys(CONFIG.PF2E.spellTraits),...universalReservedTerms]),weaponCategories:new Set([...Object.keys(CONFIG.PF2E.weaponCategories),...universalReservedTerms]),weaponGroups:new Set([...Object.keys(CONFIG.PF2E.weaponGroups),...universalReservedTerms]),weaponTraits:new Set([...Object.keys(CONFIG.PF2E.weaponTraits),...universalReservedTerms])}}__name(prepareReservedTerms,"prepareReservedTerms"),__name2(prepareReservedTerms,"prepareReservedTerms");function prepareCleanup(listKey,deletions){const Migration=class extends MigrationBase{static{__name(this,"Migration")}static{__name2(this,"Migration")}static version=MigrationRunnerBase.LATEST_SCHEMA_VERSION;async updateActor(source){if(source.type==="character"||source.type==="npc")switch(listKey){case"creatureTraits":{const traits=source.system.traits;traits.value=traits.value.filter(t=>HomebrewElements.reservedTerms.creatureTraits.has(t)||!deletions.includes(t));break}case"languages":{const languages=source.system.traits.languages;languages.value=languages.value.filter(l=>HomebrewElements.reservedTerms.languages.has(l)||!deletions.includes(l));break}case"weaponCategories":{if(source.type==="character"){const attacks=source.system.proficiencies?.attacks??{};for(const category of deletions)attacks[category]&&!HomebrewElements.reservedTerms.weaponCategories.has(category)&&(attacks[`-=${category}`]=null)}break}case"weaponGroups":{if(source.type==="character"){const attacks=source.system.proficiencies?.attacks??{};for(const group of deletions){const key=`weapon-group-${group}`;attacks[key]&&!HomebrewElements.reservedTerms.weaponGroups.has(group)&&(attacks[`-=${key}`]=null)}}break}case"baseWeapons":{if(source.type==="character"){const attacks=source.system.proficiencies?.attacks??{};for(const base of deletions){const key=`weapon-base-${base}`;attacks[key]&&!HomebrewElements.reservedTerms.baseWeapons.has(base)&&(attacks[`-=${key}`]=null)}}break}}}async updateItem(source){switch(listKey){case"creatureTraits":{if(source.system.traits?.value){const traits=source.system.traits;traits.value=traits.value.filter(t=>HomebrewElements.reservedTerms.creatureTraits.has(t)||!deletions.includes(t))}break}case"featTraits":{if(itemIsOfType(source,"action","feat")){const traits=source.system.traits;traits.value=traits.value.filter(t=>HomebrewElements.reservedTerms.featTraits.has(t)||!deletions.includes(t))}break}case"spellTraits":{if(source.type==="spell"){const traits=source.system.traits;traits.value=traits.value.filter(t=>HomebrewElements.reservedTerms.spellTraits.has(t)||!deletions.includes(t))}break}case"languages":{if(source.type==="ancestry"){const{languages}=source.system;languages.value=languages.value.filter(l=>HomebrewElements.reservedTerms.languages.has(l)||!deletions.includes(l))}break}case"weaponCategories":{if(source.type==="weapon"){const systemData=source.system;systemData.category=deletions.includes(systemData.category??"")?"simple":systemData.category}break}case"weaponGroups":{if(source.type==="weapon"){const systemData=source.system;systemData.group=deletions.includes(systemData.group??"")?null:systemData.group}break}case"baseWeapons":{if(source.type==="weapon"){const base=source.system.baseItem;source.system.baseItem=deletions.includes(base??"")?null:base}break}case"weaponTraits":{const traits=itemIsOfType(source,"melee","weapon")?source.system.traits:{value:[]};traits.value=traits.value.filter(t=>HomebrewElements.reservedTerms.weaponTraits.has(t)||!deletions.includes(t));break}}}};return new Migration}__name(prepareCleanup,"prepareCleanup"),__name2(prepareCleanup,"prepareCleanup");class HomebrewElements extends SettingsMenuPF2e{static{__name(this,"HomebrewElements")}static{__name2(this,"HomebrewElements")}static namespace="homebrew";#initialRefresh=!0;static#reservedTerms=null;static get reservedTerms(){return this.#reservedTerms??=prepareReservedTerms()}static get SETTINGS(){return Object.keys(this.settings)}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{template:"systems/pf2e/templates/system/settings/homebrew.hbs"})}static get traitSettings(){return HOMEBREW_TRAIT_KEYS.reduce((result,key)=>(result[key]={name:CONFIG.PF2E.SETTINGS.homebrew[key].name,hint:CONFIG.PF2E.SETTINGS.homebrew[key].hint,default:[],type:Object},result),{})}static get settings(){return{...this.traitSettings,damageTypes:{name:"PF2E.SETTINGS.Homebrew.DamageTypes.Name",default:[],type:Object,onChange:()=>{new DamageTypeManager().updateSettings()}}}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[type=reset]")?.addEventListener("click",()=>{this.render()});for(const key of HOMEBREW_TRAIT_KEYS){const reservedTerms=HomebrewElements.reservedTerms[key],input=htmlQuery(html,`input[name="${key}"]`);if(!input)throw ErrorPF2e("Unexpected error preparing form");const localize=localizer("PF2E.SETTINGS.Homebrew");new Tagify(input,{editTags:1,hooks:{beforeRemoveTag:tags=>{if(tags.some(t=>reservedTerms.has(sluggify(t.data.value))))return Promise.resolve();const response=(async()=>{const content=localize("ConfirmDelete.Message",{element:tags[0].data.value});return await Dialog.confirm({title:localize("ConfirmDelete.Title"),content:`<p>${content}</p>`})})();return(async()=>await response?Promise.resolve():Promise.reject())()}},validate:data=>!reservedTerms.has(sluggify(data.value)),transformTag:data=>{reservedTerms.has(sluggify(data.value))&&ui.notifications.error(localize("ReservedTerm",{term:data.value}))}})}htmlQuery(html,"[data-action=damage-add]")?.addEventListener("click",async()=>{this.cache.damageTypes.push({label:"Ouch",category:null,icon:"fa-question"}),this.render()});for(const element of htmlQueryAll(html,"[data-action=damage-delete]"))element.addEventListener("click",async event2=>{const idx=htmlClosest(event2.target,"[data-idx]")?.dataset.idx;idx&&this.cache.damageTypes.splice(Number(idx),1),this.render()})}async getData(){const data=await super.getData(),traitSettings=settingsToSheetData(this.constructor.traitSettings,this.cache,this.prefix),damageCategories2=pick(CONFIG.PF2E.damageCategories,["physical","energy"]);return{...data,traitSettings,damageCategories:damageCategories2,customDamageTypes:(this.cache.damageTypes??[]).map(customType=>({...customType,slug:sluggify(customType.label)}))}}async _onSubmit(event2,options){event2.preventDefault();for(const input of htmlQueryAll(this.form,"tags ~ input"))input.value===""&&(input.value="[]"),!("__tagify"in input)||input.__tagify instanceof Tagify;return super._onSubmit(event2,options)}_getSubmitData(updateData){const original=super._getSubmitData(updateData),data=foundry.utils.expandObject(original);if("damageTypes"in data&&data.damageTypes&&typeof data.damageTypes=="object"){data.damageTypes=Object.values(data.damageTypes);for(const type of data.damageTypes){type.category||=null;const sanitized=sluggify(type.icon??"");type.icon=sanitized.startsWith("fa-")?sanitized:null}}return data}async _updateObject(event2,data){for(const key of HOMEBREW_TRAIT_KEYS)for(const tag of data[key])tag.id??=sluggify(tag.value);if(event2.type==="submit"){const cleanupTasks=HOMEBREW_TRAIT_KEYS.map(key=>this.#processDeletions(key,data[key])).filter(task=>!!task);new MigrationRunner().runMigrations(cleanupTasks),await super._updateObject(event2,data),this.#refreshSettings()}else return super._updateObject(event2,data)}#processDeletions(listKey,newTagList){const oldTagList=game.settings.get("pf2e",`homebrew.${listKey}`),newIDList=newTagList.map(tag=>tag.id),deletions=oldTagList.flatMap(oldTag=>newIDList.includes(oldTag.id)?[]:oldTag.id),coreElements=listKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[listKey];for(const id of deletions)if(delete coreElements[id],objectHasKey(TRAIT_PROPAGATIONS,listKey))for(const recordKey of TRAIT_PROPAGATIONS[listKey]){const secondaryRecord=CONFIG.PF2E[recordKey];delete secondaryRecord[id]}return game.user.isGM&&deletions.length>0?prepareCleanup(listKey,deletions):null}onInit(){this.#refreshSettings(),this.#registerModuleTags(),new DamageTypeManager().updateSettings()}#refreshSettings(){const reservedTerms=HomebrewElements.reservedTerms;for(const listKey of HOMEBREW_TRAIT_KEYS){const settingsKey=`homebrew.${listKey}`,validElements=game.settings.get("pf2e",settingsKey).filter(e=>!reservedTerms[listKey].has(e.id));this.#updateConfigRecords(validElements,listKey)}if(this.#initialRefresh)this.#initialRefresh=!1;else{const sheets=Object.values(ui.windows).filter(app=>app instanceof ActorSheet||app instanceof ItemSheetPF2e);for(const sheet of sheets)sheet.render(!1)}}#registerModuleTags(){const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(isObject$1(homebrew)){for(const recordKey of Object.keys(homebrew))if(recordKey!=="damageTypes")if(tupleHasValue(HOMEBREW_TRAIT_KEYS,recordKey)){const elements=homebrew[recordKey];if(!isObject(elements)||!isHomebrewFlagCategory(elements)){console.warn(ErrorPF2e(`Homebrew record ${recordKey} is malformed in module ${key}`).message);continue}const elementEntries=Object.entries(elements),tags=elementEntries.map(([id,value])=>({id,value:typeof value=="string"?value:value.label}));this.#updateConfigRecords(tags,recordKey);for(const[key2,value]of elementEntries)if(typeof value=="object"){const hbKey=key2;CONFIG.PF2E.traitsDescriptions[hbKey]=value.description}}else{console.warn(ErrorPF2e(`Invalid homebrew record "${recordKey}" in module ${key}`).message);continue}}}}#getConfigRecord(recordKey){return recordKey==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[recordKey]}#updateConfigRecords(elements,listKey){const coreElements=this.#getConfigRecord(listKey);for(const element of elements)if(coreElements[element.id]=element.value,objectHasKey(TRAIT_PROPAGATIONS,listKey))for(const recordKey of TRAIT_PROPAGATIONS[listKey]){const record=CONFIG.PF2E[recordKey];record[element.id]=element.value}}}class DamageTypeManager{static{__name(this,"DamageTypeManager")}static{__name2(this,"DamageTypeManager")}collections={physical:PHYSICAL_DAMAGE_TYPES,energy:ENERGY_DAMAGE_TYPES,DAMAGE_TYPES,BASE_DAMAGE_TYPES_TO_CATEGORIES,DAMAGE_TYPE_ICONS,damageTypesLocalization:CONFIG.PF2E.damageTypes,damageRollFlavorsLocalization:CONFIG.PF2E.damageRollFlavors,immunityTypes,weaknessTypes,resistanceTypes};addCustomDamage(data,options={}){const collections=this.collections,slug=options.slug??sluggify(data.label);collections.DAMAGE_TYPES.add(slug),tupleHasValue(["physical","energy"],data.category)&&collections[data.category].push(slug),collections.BASE_DAMAGE_TYPES_TO_CATEGORIES[slug]=data.category??null,collections.DAMAGE_TYPE_ICONS[slug]=data.icon?.substring(3)??null,collections.damageTypesLocalization[slug]=data.label;const versatileLabel=game.i18n.format("PF2E.TraitVersatileX",{x:data.label});CONFIG.PF2E.weaponTraits[`versatile-${slug}`]=versatileLabel,CONFIG.PF2E.npcAttackTraits[`versatile-${slug}`]=versatileLabel;const damageFlavor=game.i18n.localize(data.label).toLocaleLowerCase(game.i18n.lang);collections.damageRollFlavorsLocalization[slug]=damageFlavor,collections.immunityTypes[slug]=damageFlavor,collections.weaknessTypes[slug]=damageFlavor,collections.resistanceTypes[slug]=damageFlavor}updateSettings(){const reservedTerms=HomebrewElements.reservedTerms,typesToDelete=DAMAGE_TYPES.filter(t=>!reservedTerms.damageTypes.has(t));for(const collection of Object.values(this.collections))if(collection instanceof Set){const types=[...collection].filter(t=>typesToDelete.has(t));for(const damageType of types)collection.delete(damageType)}else{const types=Object.keys(collection).filter(t=>typesToDelete.has(t));for(const damageType of types)delete collection[damageType]}for(const type of typesToDelete){const weaponTraits2=CONFIG.PF2E.weaponTraits,npcAttackTraits2=CONFIG.PF2E.npcAttackTraits;delete weaponTraits2[`versatile-${type}`],delete npcAttackTraits2[`versatile-${type}`]}const activeModules=[...game.modules.entries()].filter(([_key,foundryModule])=>foundryModule.active);for(const[key,foundryModule]of activeModules){const homebrew=foundryModule.flags?.[key]?.["pf2e-homebrew"];if(!isObject$1(homebrew)||!homebrew.damageTypes)continue;const elements=homebrew.damageTypes;if(!isObject(elements)||!isHomebrewCustomDamage(elements)){console.warn(ErrorPF2e(`Homebrew record damageTypes is malformed in module ${key}`).message);continue}for(const[slug,data]of Object.entries(elements))if(!reservedTerms.damageTypes.has(slug))this.addCustomDamage(data,{slug});else{console.warn(ErrorPF2e(`Homebrew damage type "${slug}" from module ${foundryModule.title} is a reserved term.`).message);continue}}const customTypes=game.settings.get("pf2e","homebrew.damageTypes").filter(t=>!reservedTerms.damageTypes.has(sluggify(t.label)));for(const data of customTypes)this.addCustomDamage(data)}}class Migration674StableHomebrewTagIDs extends MigrationBase{static{__name(this,"Migration674StableHomebrewTagIDs")}static{__name2(this,"Migration674StableHomebrewTagIDs")}static version=.674;#homebrewKeys=foundry.utils.deepClone(HOMEBREW_TRAIT_KEYS);#homebrewTags=this.#homebrewKeys.reduce((settings,key)=>foundry.utils.mergeObject(settings,{[key]:game.settings.get("pf2e",`homebrew.${key}`)}),{});#updateDocumentTags(documentTags=[]){for(const key of this.#homebrewKeys){const homebrewTags=this.#homebrewTags[key];for(const tag of homebrewTags){const index=documentTags.indexOf(tag.id);index!==-1&&documentTags.splice(index,1,`hb_${sluggify(tag.value)}`)}}}async updateActor(source){source.type==="familiar"||!source.system.traits?.traits||(this.#updateDocumentTags(source.system.traits.traits.value),(source.type==="character"||source.type==="npc")&&this.#updateDocumentTags(source.system.traits?.languages.value))}async updateItem(source){this.#updateDocumentTags(source.system.traits?.value)}async migrate(){for(const key of this.#homebrewKeys){const tags=this.#homebrewTags[key];for(const tag of tags){tag.id=`hb_${sluggify(tag.value)}`;const tagMap=key==="baseWeapons"?CONFIG.PF2E.baseWeaponTypes:CONFIG.PF2E[key];tagMap[tag.id]=tag.value,delete tagMap[key]}tags.length>0&&await game.settings.set("pf2e",`homebrew.${key}`,tags)}}}class Migration675FlatModifierAEsToREs extends MigrationBase{static{__name(this,"Migration675FlatModifierAEsToREs")}static{__name2(this,"Migration675FlatModifierAEsToREs")}static version=.675;#isFlatModifier(data){return typeof data=="object"&&data!==null&&__name2(obj=>(typeof obj.modifier=="number"||typeof obj.modifier=="string")&&typeof obj.type=="string","dataIsModifier")(data)}#toRuleElement(aeValue){const aeModifier=(()=>{try{const parsed=JSON.parse(aeValue);return this.#isFlatModifier(parsed)?parsed:null}catch(error){return console.warn(error),null}})();return typeof aeModifier?.modifier=="string"&&aeModifier.modifier.replace("@data.","@"),aeModifier&&{key:"FlatModifier",type:aeModifier.type,value:aeModifier.modifier,selector:"hp"}}async updateActor(actorSource){for(const effect of[...actorSource.effects])effect.changes.some(change=>change.key.endsWith(".modifiers"))&&actorSource.effects.splice(actorSource.effects.indexOf(effect),1)}async updateItem(itemSource){for(const effect of[...itemSource.effects]){for(const change of effect.changes.filter(change2=>change2.key.endsWith(".modifiers"))){const reData=this.#toRuleElement(change.value);reData&&(effect.changes.splice(effect.changes.indexOf(change),1),itemSource.system.rules.push(reData))}effect.changes.length===0&&itemSource.effects.splice(itemSource.effects.indexOf(effect),1)}}}class Migration676ReplaceItemsWithRELikeAEs extends MigrationBase{static{__name(this,"Migration676ReplaceItemsWithRELikeAEs")}static{__name2(this,"Migration676ReplaceItemsWithRELikeAEs")}static version=.676;toughnessPromise=fromUuid("Compendium.pf2e.feats-srd.AmP0qu7c5dlBSath");stoutnessPromise=fromUuid("Compendium.pf2e.feats-srd.COP89tjrNhEucuRW");toughPromise=fromUuid("Compendium.pf2e.familiar-abilities.Le8UWr5BU8rV3iBf");replaceItem({items,type,slug,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const current=items.find(itemSource=>itemSource.type===type&&itemSource.system.slug?.replace(/'/g,"")===slug);if(current){const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}}async updateActor(actorSource){actorSource.type==="familiar"?this.replaceItem({items:actorSource.items,type:"effect",slug:"tough",replacement:await this.toughPromise}):actorSource.type==="character"&&(this.replaceItem({items:actorSource.items,type:"feat",slug:"toughness",replacement:await this.toughnessPromise}),this.replaceItem({items:actorSource.items,type:"feat",slug:"mountains-stoutness",replacement:await this.stoutnessPromise}))}}class Migration677RuleValueDataRefs extends MigrationBase{static{__name(this,"Migration677RuleValueDataRefs")}static{__name2(this,"Migration677RuleValueDataRefs")}static version=.677;async updateItem(itemSource){for(const rule of itemSource.system.rules)typeof rule.value=="string"&&(rule.value=rule.value.replace("@data.","@"))}}class Migration678SeparateNPCAttackTraits extends MigrationBase{static{__name(this,"Migration678SeparateNPCAttackTraits")}static{__name2(this,"Migration678SeparateNPCAttackTraits")}static version=.678;async updateItem(itemSource){if(itemSource.type==="weapon"){const weaponTraits2=itemSource.system.traits.value,rangeTraits2=weaponTraits2.filter(trait=>/^range(?!d)/.test(trait));for(const trait of rangeTraits2)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);const reloadTraits=weaponTraits2.filter(trait=>trait.startsWith("reload"));for(const trait of reloadTraits)weaponTraits2.splice(weaponTraits2.indexOf(trait),1);itemSource.system.traits.value=[...new Set(weaponTraits2)].sort()}if(!itemSource.system.traits)return;const itemTraits=itemSource.system.traits.value??[];for(const trait of itemTraits)tupleHasValue(RARITIES,trait)&&(itemTraits.splice(itemTraits.indexOf(trait),1),trait!=="common"&&isObject(itemSource.system.traits.rarity)&&itemSource.system.traits.rarity.value==="common"&&(itemSource.system.traits.rarity.value=trait))}}class Migration679TowerShieldSpeedPenalty extends MigrationBase{static{__name(this,"Migration679TowerShieldSpeedPenalty")}static{__name2(this,"Migration679TowerShieldSpeedPenalty")}static version=.679;towerShieldSlugs=["darkwood-tower-shield-high-grade","darkwood-tower-shield-standard-grade","tower-shield"];async updateItem(source){if(source.type==="armor"){const systemData=source.system;systemData.speed&&this.towerShieldSlugs.includes(systemData.slug??"")&&(systemData.speed.value=-5),systemData.armor&&(systemData.armor.value=Number(systemData.armor.value)||0),systemData.speed&&(systemData.speed.value=Number(systemData.speed.value)||0);const potencyRune=systemData.potencyRune??{};potencyRune.value=Number(systemData.potencyRune?.value)||0,"resilient"in systemData&&("game"in globalThis?systemData["-=resilient"]=null:delete systemData.resilient)}}}class Migration680SetWeaponHands extends MigrationBase{static{__name(this,"Migration680SetWeaponHands")}static{__name2(this,"Migration680SetWeaponHands")}static version=.68;#oneHandedWeapons=new Set(["repeating-hand-crossbow"]);#onePlusHandedWeapons=new Set(["backpack-ballista","backpack-catapult","composite-longbow","composite-shortbow","hongali-hornbow","longbow","shortbow","sun-sling"]);#shieldAttachments=new Set(["shield-boss","shield-spikes"]);#firearmAttachments=new Set(["bayonette","reinforced-stock"]);#wornGloves=new Set(["handwraps-of-mighty-blows"]);#twoHandedWeapons=new Set(["adze","alchemical-crossbow","arquebus","axe-musket","bladed-diabolo","bladed-scarf","blunderbuss","bo-staff","boarding-pike","butchering-axe","combat-grapnel","crossbow","double-barreled-musket","dueling-spear","dwarven-scattergun","elven-branched-spear","elven-curve-blade","explosive-dogslicer","falchion","fauchard","fire-lance","flingflenser","flintlock-musket","gill-hook","glaive","gnome-amalgam-musket","greataxe","greatclub","greatpick","greatsword","guisarme","gun-sword","halberd","halfling-sling-staff","hammer-gun","harmona-gun","heavy-crossbow","horsechopper","kusarigama","lance","longspear","maul","meteor-hammer","mithral-tree","naginata","ogre-hook","ranseur","repeating-crossbow","repeating-heavy-crossbow","scythe","shauth-lash","spiked-chain","taw-launcher","three-peaked-tree","thundermace","war-flail","whip-claw"]);#isShield(source){return(source.type==="armor"?source.system.armorType?.value||source.system.category:null)==="shield"}async updateItem(source){if(this.#isShield(source)&&isObject$1(source.system.usage))source.system.usage.value="held-in-one-hand";else if(source.type==="weapon"){source.system.usage??={value:"held-in-one-hand"};const{baseItem,slug,traits}=source.system,usage=source.system.usage;if(this.#twoHandedWeapons.has(baseItem||slug||""))usage.value="held-in-two-hands";else if(this.#onePlusHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-plus-hands";else if(this.#oneHandedWeapons.has(baseItem||slug||""))usage.value="held-in-one-hand";else if(this.#shieldAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-shield")}else if(this.#firearmAttachments.has(baseItem||slug||"")){usage.value="held-in-one-hand";const attachedIndex=traits.value.findIndex(trait=>trait==="attached");attachedIndex!==-1&&traits.value.splice(attachedIndex,1,"attached-to-crossbow-or-firearm")}else this.#wornGloves.has(baseItem||slug||"")&&(usage.value="worn-gloves")}}}class Migration681GiantLanguageToJotun extends MigrationBase{static{__name(this,"Migration681GiantLanguageToJotun")}static{__name2(this,"Migration681GiantLanguageToJotun")}static version=.681;replaceGiant({value}){const giantIndex=value.indexOf("giant");giantIndex!==-1&&value.splice(giantIndex,1,"jotun")}async updateActor(actorSource){(actorSource.type==="character"||actorSource.type==="npc")&&this.replaceGiant(actorSource.system.traits.languages)}async updateItem(itemSource){itemSource.type==="ancestry"&&this.replaceGiant(itemSource.system.additionalLanguages)}}class Migration682BiographyFields extends MigrationBase{static{__name(this,"Migration682BiographyFields")}static{__name2(this,"Migration682BiographyFields")}static version=.682;replaceBiographyData(old){old.details.biography.public?(old.details.biography.appearance=old.details.biography.public,old.details.biography["-=public"]=null):old.details.biography.appearance??="",old.details.biography.value?(old.details.biography.campaignNotes=old.details.biography.value,old.details.biography["-=value"]=null):old.details.biography.campaignNotes??="","game"in globalThis||(delete old.details.biography.public,delete old.details.biography.value),old.details.biography.backstory??="",old.details.biography.birthPlace??="",old.details.biography.attitude??="",old.details.biography.beliefs??="",old.details.biography.likes??="",old.details.biography.dislikes??="",old.details.biography.catchphrases??="",old.details.biography.allies??="",old.details.biography.enemies??="",old.details.biography.organaizations??=""}async updateActor(source){source.type==="character"&&this.replaceBiographyData(source.system)}}class Migration683FlavorTextToPublicNotes extends MigrationBase{static{__name(this,"Migration683FlavorTextToPublicNotes")}static{__name2(this,"Migration683FlavorTextToPublicNotes")}static version=.683;replaceFlavorTextData(old){old.details.flavorText?(old.details.publicNotes=old.details.flavorText,old.details["-=flavorText"]=null):old.details.publicNotes??="","game"in globalThis||delete old.details.flavorText,old.details.blurb??="",old.details.privateNotes??=""}async updateActor(actorSource){actorSource.type==="npc"&&this.replaceFlavorTextData(actorSource.system)}}class Migration684RationsToConsumable extends MigrationBase{static{__name(this,"Migration684RationsToConsumable")}static{__name2(this,"Migration684RationsToConsumable")}static version=.684;#rationsSourceId="Compendium.pf2e.equipment-srd.L9ZV076913otGtiB";#rationsPromise=fromUuid(this.#rationsSourceId);#isOldRations(itemSource){return itemSource?.type==="equipment"&&itemSource.flags.core?.sourceId===this.#rationsSourceId}#getRationRefs(itemRefs){return itemRefs.reduce((rationRefs,itemRef)=>(itemRef.isContainer&&itemRef.items?rationRefs.push(...this.#getRationRefs(Object.values(itemRef.items))):itemRef.pack==="pf2e.equipment-srd"&&itemRef.id==="L9ZV076913otGtiB"&&rationRefs.push(itemRef),rationRefs),[])}async updateActor(source){const oldRations=source.items.filter(i=>this.#isOldRations(i)),rations=await this.#rationsPromise;if(!(rations instanceof ConsumablePF2e))throw ErrorPF2e("Unexpected error acquiring compendium item");for(const oldRation of oldRations){const newRation=rations.toObject();newRation.folder=oldRation.folder,newRation.sort=oldRation.sort;const oldContainerId=oldRation.system.containerId??{value:null};oldContainerId instanceof Object&&(newRation.system.containerId=oldContainerId.value);const oldQuantity=oldRation.system.quantity;isObject(oldQuantity)&&(newRation.system.quantity=Math.ceil((oldQuantity.value??1)/7)),source.items.findSplice(item=>item===oldRation,newRation)}}async updateItem(source){if(source.type!=="kit")return;const rationRefs=this.#getRationRefs(Object.values(source.system.items));for(const rationRef of rationRefs)rationRef.quantity=Math.ceil(rationRef.quantity/7)}}class Migration685FixMeleeUsageTraits extends MigrationBase{static{__name(this,"Migration685FixMeleeUsageTraits")}static{__name2(this,"Migration685FixMeleeUsageTraits")}static version=.685;async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.meleeUsage&&!Array.isArray(systemData.meleeUsage.traits)&&(systemData.meleeUsage.traits=systemData.meleeUsage.traits?.value??[])}}}class Migration686HeroPointsToResources extends MigrationBase{static{__name(this,"Migration686HeroPointsToResources")}static{__name2(this,"Migration686HeroPointsToResources")}static version=.686;async updateActor(actorSource){if(actorSource.type!=="character")return;const systemSource=actorSource.system;if(systemSource.attributes.heroPoints){const resources=systemSource.resources;resources.heroPoints={value:systemSource.attributes.heroPoints.rank},systemSource.attributes["-=heroPoints"]=null,"game"in globalThis||delete systemSource.attributes.heroPoints}}}class Migration687FamiliarityAEsToREs extends MigrationBase{static{__name(this,"Migration687FamiliarityAEsToREs")}static{__name2(this,"Migration687FamiliarityAEsToREs")}static version=.687;isFamiliarityAE(data){return typeof data=="object"&&data!==null&&__name2(obj=>typeof obj.trait=="string"&&typeof obj.category=="string","dataIsFamiliarity")(data)}toRuleElement(sameAs,aeValue){const aeData=(()=>{try{const parsed=JSON.parse(aeValue);return this.isFamiliarityAE(parsed)?parsed:null}catch(error){return console.warn(error),null}})();return aeData&&{key:"LinkedProficiency",slug:`${aeData.category}-${aeData.trait}-weapons`,predicate:{all:[`weapon:trait:${aeData.trait}`,`weapon:category:${aeData.category}`]},sameAs}}async updateActor(actorSource){actorSource.effects=[]}async updateItem(itemSource){for(const effect of[...itemSource.effects])for(const change of effect.changes.filter(change2=>change2.key.startsWith("system.martial."))){const linkTo=change.key.replace(/^data\.martial\.|\.familiarity$/g,""),reData=this.toRuleElement(linkTo,change.value);reData&&itemSource.system.rules.push(reData)}itemSource.effects=[]}}class Migration688ClampSpellLevel extends MigrationBase{static{__name(this,"Migration688ClampSpellLevel")}static{__name2(this,"Migration688ClampSpellLevel")}static version=.688;async updateItem(itemSource){itemSource.type==="spell"&&(itemSource.system.level.value=Math.min(Math.max(itemSource.system.level.value,1),10))}}class Migration689EncumberanceActiveEffects extends MigrationBase{static{__name(this,"Migration689EncumberanceActiveEffects")}static{__name2(this,"Migration689EncumberanceActiveEffects")}static version=.689;async updateItem(itemSource){const systemData=itemSource.system,slug=systemData.slug??sluggify(itemSource.name),amountToIncreaseBy=(()=>itemSource.type==="feat"&&slug==="hefty-hauler"?2:itemSource.type==="feat"&&slug==="hardy-traveler"||itemSource.type==="equipment"&&slug==="lifting-belt"?1:0)();if(amountToIncreaseBy===0||systemData.rules.some(r=>r.key==="ActiveEffectLike"))return;const rules=[{key:"ActiveEffectLike",path:"system.attributes.bonusEncumbranceBulk",mode:"add",value:amountToIncreaseBy},{key:"ActiveEffectLike",path:"system.attributes.bonusLimitBulk",mode:"add",value:amountToIncreaseBy}];for(const rule of rules)systemData.rules.push(rule)}}class Migration690InitiativeTiebreakItems extends MigrationBase{static{__name(this,"Migration690InitiativeTiebreakItems")}static{__name2(this,"Migration690InitiativeTiebreakItems")}static version=.69;itemSlugs=["ambush-awareness","elven-instincts","pilgrims-token"];rule={key:"ActiveEffectLike",path:"system.attributes.initiative.tiebreakPriority",mode:"override",value:0};async updateItem(itemSource){this.itemSlugs.includes(itemSource.system.slug??"")&&!itemSource.system.rules.some(rule=>rule.key==="ActiveEffectLike")&&!(itemSource.system.slug==="pilgrims-token"&&itemSource.type!=="equipment")&&itemSource.system.rules.push(this.rule)}}class Migration691WeaponRangeAbilityCategoryGroup extends MigrationBase{static{__name(this,"Migration691WeaponRangeAbilityCategoryGroup")}static{__name2(this,"Migration691WeaponRangeAbilityCategoryGroup")}static version=.691;isOldGroupData(group){return isObject(group)&&(typeof group.value=="string"||group.value===null)}isOldRangeData(range2){return range2 instanceof Object&&"value"in range2&&typeof range2.value=="string"}async updateItem(itemSource){if(itemSource.type==="weapon"){const systemData=itemSource.system;systemData.category=(systemData.weaponType?systemData.weaponType.value:systemData.category)||"simple",systemData.weaponType&&(systemData["-=weaponType"]=null,"game"in globalThis||delete systemData.weaponType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null;const hasOldRangeData=this.isOldRangeData(systemData.range);if(systemData.range=hasOldRangeData?Number(systemData.range.value)||null:systemData.range,hasOldRangeData&&isObject(systemData.ability)&&(systemData.ability.value==="str"&&!setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)&&(systemData.range=null),delete systemData.ability,systemData["-=ability"]=null),setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)){const thrownIndex=systemData.traits.value.findIndex(trait=>/^thrown-\d+/.test(trait));thrownIndex!==-1&&(systemData.traits.value[thrownIndex]="thrown",systemData.reload.value="-")}systemData.baseItem==="falchion"?systemData.group="sword":systemData.baseItem==="orc-knuckle-dagger"&&(systemData.group="knife")}const{rules}=itemSource.system,strikeRules=rules.filter(rule=>/\bStrike$/.test(String(rule.key)));for(const rule of strikeRules)rule.key="Strike",rule.range=Number(rule.range)||null,delete rule.ability}}class Migration692CraftingEntryFeatReplacement extends MigrationBase{static{__name(this,"Migration692CraftingEntryFeatReplacement")}static{__name2(this,"Migration692CraftingEntryFeatReplacement")}static version=.692;requiresFlush=!0;slugToPromise=new Map([["advanced-alchemy",fromUuid("Compendium.pf2e.classfeatures.Pe0zmIqyTBc2Td0I")],["field-discovery-bomber",fromUuid("Compendium.pf2e.classfeatures.8QAFgy9U8PxEa7Dw")],["field-discovery-chirurgeon",fromUuid("Compendium.pf2e.classfeatures.qC0Iz6SlG2i9gv6g")],["field-discovery-mutagenist",fromUuid("Compendium.pf2e.classfeatures.V4Jt7eDnJBLv5bDj")],["field-discovery-toxicologist",fromUuid("Compendium.pf2e.classfeatures.6zo2PJGYoig7nFpR")],["infused-reagents",fromUuid("Compendium.pf2e.classfeatures.wySB9VHOW1v3TX1L")],["alchemist-dedication",fromUuid("Compendium.pf2e.feats-srd.CJMkxlxHiHZQYDCz")],["deeper-dabbler",fromUuid("Compendium.pf2e.feats-srd.PTXZ2C3AV8tZf0iX")],["efficient-alchemy-paragon",fromUuid("Compendium.pf2e.feats-srd.2FBZ0apnmZ7b61ct")],["expert-alchemy",fromUuid("Compendium.pf2e.feats-srd.soHLtpMM9h3AE7PD")],["expert-fireworks-crafter",fromUuid("Compendium.pf2e.feats-srd.dDFQJem5K9Jzxgda")],["expert-herbalism",fromUuid("Compendium.pf2e.feats-srd.owJorCBZmUi5lIV0")],["expert-poisoner",fromUuid("Compendium.pf2e.feats-srd.VruIzuysxw4tY6rk")],["firework-technician-dedication",fromUuid("Compendium.pf2e.feats-srd.MVbNnjqQOK9d8Ki3")],["gadget-specialist",fromUuid("Compendium.pf2e.feats-srd.DQN7YC7s7T0pL6Aa")],["herbalist-dedication",fromUuid("Compendium.pf2e.feats-srd.5CRt5Dy9eLv5LpRF")],["master-alchemy",fromUuid("Compendium.pf2e.feats-srd.f6k9lIrIS4SfnCnG")],["munitions-crafter",fromUuid("Compendium.pf2e.feats-srd.lFVqejlf52cdYrZy")],["munitions-machinist",fromUuid("Compendium.pf2e.feats-srd.lh3STEvbGnP7jVMr")],["plentiful-snares",fromUuid("Compendium.pf2e.feats-srd.wGaxWwJhIXbMJft1")],["poisoner-dedication",fromUuid("Compendium.pf2e.feats-srd.y7DDs03GtDnmhxFp")],["snare-genius",fromUuid("Compendium.pf2e.feats-srd.8DIzXO1YpsU3DpJw")],["snare-specialist",fromUuid("Compendium.pf2e.feats-srd.0haS0qXR9xTYKoTG")],["snarecrafter-dedication",fromUuid("Compendium.pf2e.feats-srd.4MUbwilvb9dI0X59")],["talisman-dabbler-dedication",fromUuid("Compendium.pf2e.feats-srd.1t5479E6bdvFs4E7")],["ubiquitous-gadgets",fromUuid("Compendium.pf2e.feats-srd.ny0nfGTDUE4p8TtO")],["ubiquitous-snares",fromUuid("Compendium.pf2e.feats-srd.bX2WI5k0afqPpCfm")]]);replaceItem({items,current,replacement}){if(!(replacement instanceof ItemPF2e))throw ErrorPF2e("Unexpected error retrieving compendium item");const newSource=replacement.toObject();current.type==="feat"&&newSource.type==="feat"&&(newSource.system.location=current.system.location),items.splice(items.indexOf(current),1,newSource)}async updateActor(actorSource){actorSource.type==="character"&&this.slugToPromise.forEach(async(promise,slug)=>{const current=actorSource.items.find(itemSource=>itemSource.type==="feat"&&itemSource.system.slug===slug);current&&this.replaceItem({items:actorSource.items,current,replacement:await promise})})}}class Migration693ArmorCategoryGroup extends MigrationBase{static{__name(this,"Migration693ArmorCategoryGroup")}static{__name2(this,"Migration693ArmorCategoryGroup")}static version=.693;isOldGroupData(group){return group instanceof Object&&"value"in group&&(typeof group.value=="string"||group.value===null)}async updateItem(itemSource){if(itemSource.type!=="armor")return;const systemData=itemSource.system;systemData.category=(systemData.armorType?systemData.armorType.value:systemData.category)||"simple",systemData.armorType&&(systemData["-=armorType"]=null,"game"in globalThis||delete systemData.armorType),systemData.group=(this.isOldGroupData(systemData.group)?systemData.group.value:systemData.group)||null}}class Migration694RetireSystemTokenSettings extends MigrationBase{static{__name(this,"Migration694RetireSystemTokenSettings")}static{__name2(this,"Migration694RetireSystemTokenSettings")}static version=.694;async migrate(){const systemNameHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsName"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,systemBarHover=Number(game.settings.storage.get("world").getItem("pf2e.defaultTokenSettingsBar"))||CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,coreTokenDefaults=game.settings.get("core","defaultToken");coreTokenDefaults.displayName=systemNameHover,coreTokenDefaults.displayBars=systemBarHover}}class Migration695SummonToSummoned extends MigrationBase{static{__name(this,"Migration695SummonToSummoned")}static{__name2(this,"Migration695SummonToSummoned")}static version=.695;async updateItem(itemSource){const traits=itemSource.system.traits;if(traits?.value)if(itemSource.type==="action")traits.custom??="",traits.custom.toLowerCase()==="summon"&&(traits.custom="",traits.value=Array.from(new Set([...traits.value,"summon"])).sort());else{const index=traits.value.indexOf("summon");index!==-1&&(traits.value[index]="summoned")}}}class Migration696FlatAbilityModifiers extends MigrationBase{static{__name(this,"Migration696FlatAbilityModifiers")}static{__name2(this,"Migration696FlatAbilityModifiers")}static version=.696;abilityModPattern=/@abilities\.([a-z]{3})\.mod\b/;abbreviationMap=new Map(Array.from(ATTRIBUTE_ABBREVIATIONS).map(a=>[`PF2E.Ability${sluggify(a,{camel:"bactrian"})}`,a]));async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)if(typeof rule.key=="string"&&rule.key.endsWith("FlatModifier")&&rule.type==="ability"&&!setHasElement(ATTRIBUTE_ABBREVIATIONS,rule.ability)){const abilityFromValue=this.abilityModPattern.exec(String(rule.value))?.[1]??null;rule.ability=abilityFromValue??this.abbreviationMap.get(String(rule.label??""))??"str",typeof rule.value=="string"&&rule.value.startsWith("@")&&rule.value.endsWith(".mod")&&delete rule.value}itemSource.system.slug==="thief-racket"&&!rules.some(rule=>rule.ability==="dex")&&rules.unshift({ability:"dex",key:"FlatModifier",predicate:{all:["weapon:melee","weapon:trait:finesse"],not:["weapon:category:unarmed"]},selector:"damage",type:"ability"})}}class Migration697WeaponReachTrait extends MigrationBase{static{__name(this,"Migration697WeaponReachTrait")}static{__name2(this,"Migration697WeaponReachTrait")}static version=.697;async updateItem(itemSource){if(itemSource.type==="weapon"){const traits=itemSource.system.traits.value,numericReach=traits.find(t=>/^reach-\d+$/.test(t));numericReach&&traits.splice(traits.indexOf(numericReach),1,"reach")}}}class Migration698RemoveDerivedActorTraits extends MigrationBase{static{__name(this,"Migration698RemoveDerivedActorTraits")}static{__name2(this,"Migration698RemoveDerivedActorTraits")}static version=.698;async updateActor(source){if(!((source.type==="character"||source.type==="npc")&&"traits"in source.system.traits&&isObject(source.system.traits.traits)&&"value"in source.system.traits.traits&&Array.isArray(source.system.traits.traits.value)))return;const traits=source.system.traits.traits.value;for(const trait of["good","evil","lawful","chaotic"]){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}if(source.type==="character"){const ancestry=source.items.find(i=>i.type==="ancestry");if(!ancestry)return;for(const trait of ancestry.system.traits.value){const index=traits.indexOf(trait);index>=0&&traits.splice(index,1)}}}}class Migration699ItemDescriptionEmptyString extends MigrationBase{static{__name(this,"Migration699ItemDescriptionEmptyString")}static{__name2(this,"Migration699ItemDescriptionEmptyString")}static version=.699;async updateItem(itemSource){itemSource.system.description.value??=""}}class Migration700SingleClassFeatures extends MigrationBase{static{__name(this,"Migration700SingleClassFeatures")}static{__name2(this,"Migration700SingleClassFeatures")}static version=.7;itemIds={alertness:["D8CSi8c9XiRpVc5M","OZaJz4exCoz6vuuv","qJ4fwGpoNC36ZQ8I","2o1Cj7hDayDlslqY","TAIOtk5VvPZvv4nu"],"armor-expertise":["x5jaCJxsmD5sx3KB","fRifyINZF5SKDfib"],"armor-mastery":["CGB1TczFhQhdQxml","IPDwS5pTgU3Cq6Nl"],evasion:["MV6XIuAgN9uSA0Da","EZuWfYSv3ASLyKtu","DqWr3LqUpT3Xi2xq"],"expert-spellcaster":["cD3nSupdCvONuHiE","mdzk070ixIDpid7V"],"great-fortitude":["F57Na5VxfBp56kke","25GSAotUcDwInYgG"],"improved-evasion":["L5D0NwFXdLiVSnk5","6XwGONPdr9SFDtDc"],"incredible-senses":["nLwPMPLRne1HnL00","iyb5FU2BpsCCan8Q","kktZhQPJgC5F4hgU"],"iron-will":["wMyDcVNmA7xGK83S","JVCxv4HuLaaFhAf4"],juggernaut:["OMZs5y16jZRW9KQK","sHCFQZM0xHCOYOId","Ba97T4anGhizfaCt","pzTRQxuoNOeWAalC","ojB0UJWpSekQPjT7"],"lightning-reflexes":["TUOeATt52P43r5W0","rz87RgR1crWTd7j5","Xqd0vrxq2bLXxdaB","tfugXJHITCnArN1b","7PzcKaDGy6tIkQh4","EJzjY6AIsTYqW0ee"],"magical-fortitude":["70jqXP2eS4tRZ0Ok","MzyPNlxrNA5OKVd7"],"master-spellcaster":["l1InYvhnQSz6Ucxc","zu9PcxvfoZlqQVk5"],"medium-armor-expertise":["FCEp9jjxxgRJDJV3","tzUaTqB6GHAeffOl"],"medium-armor-mastery":["cGMSYAErbUG5E8X2","NcEpvnIZfKzG1Iou"],resolve:["JQAujUXjczVnYDEI","D2g6sZQAWaTccviQ","vv63fioCtOvDIdF2","9WjZSliQZJlyGvUi"],"vigilant-senses":["0npO4rPscGm0dX13","NTp146fjLreL5zsj"],"weapon-expertise":["9XLUh9iMepZesdmc","F5BHEav90oOJ2LwN","O99eXctsEjEpuBwe"],"weapon-specialization":["9EqIasqfI8YIM3Pt","WiM7X4xmpMx4s6LD","1NGTc0gqEtwaFqUK"]};features=["Alertness","Armor Expertise","Armor Mastery","Evasion","Expert Spellcaster","Great Fortitude","Improved Evasion","Incredible Senses","Iron Will","Juggernaut","Lightning Reflexes","Magical Fortitude","Master Spellcaster","Medium Armor Expertise","Medium Armor Mastery","Resolve","Vigilant Senses","Weapon Expertise","Weapon Specialization"].map(name2=>({slug:sluggify(name2),name:name2}));#migrateClass(itemSource){for(const refId in itemSource.system.items){const itemRef=itemSource.system.items[refId];itemRef.level=Number(itemRef.level)||1;for(const feature of this.features)itemSource.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||this.itemIds[feature.slug].includes(itemRef.id??"")&&(itemRef.id=this.itemIds[feature.slug][0],itemRef.name=feature.name)}}#migrateFeature(source){if(this.#isClassFeature(source))for(const feature of this.features)source.system.slug==="swashbuckler"&&feature.slug==="weapon-expertise"||source.system.slug?.startsWith(`${feature.slug}-level-`)&&(source.system.slug=feature.slug,source.name.startsWith(`${feature.name} `)&&(source.name=feature.name),source.system.traits.value=[])}#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateItem(source){source.type==="class"?this.#migrateClass(source):source.type==="feat"&&this.#migrateFeature(source)}}class Migration701ModifierNameToSlug extends MigrationBase{static{__name(this,"Migration701ModifierNameToSlug")}static{__name2(this,"Migration701ModifierNameToSlug")}static version=.701;async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>["FlatModifier","DamageDice"].includes(String(r.key)));for(const rule of rules)rule.name&&(rule.label?rule.slug=sluggify(rule.name):rule.label=rule.name,delete rule.name),rule.label==="Rage"&&(rule.label="PF2E.TraitRage")}}class Migration702REFormulasAtInstanceLevel extends MigrationBase{static{__name(this,"Migration702REFormulasAtInstanceLevel")}static{__name2(this,"Migration702REFormulasAtInstanceLevel")}static version=.702;raiseToInstanceLevel(value){return value.replace(/@[a-z.]+/gi,match=>["@mod","@castLevel","@heighten","@item.badge.value"].includes(match)||match.indexOf("@spell")>=0?match:match==="@details.level.value"||match==="@actor.details.level.value"?"@actor.level":match==="@item.value.value"?"@item.badge.value":match.startsWith("@abilities.")?match.replace(/\babilities\b/,"actor.abilities"):match.startsWith("@attributes.")?match.replace(/\battributes\b/,"actor.attributes"):match==="@item.level.value"?"@item.level":/^@item\.[a-z]+$/.test(match)?match:match.replace(/@item\.(?!data\b)/,"@item.system.").replace(/@(?!(?:item|actor|[A-Z]\w+))/,"@actor.system."))}async updateItem(itemSource){const rules=itemSource.system.rules;for(const rule of rules)try{if(typeof rule.value=="string")rule.value=this.raiseToInstanceLevel(rule.value);else if(isObject(rule.value)&&"brackets"in rule.value&&Array.isArray(rule.value.brackets))for(const bracket of rule.value.brackets)isObject(bracket)&&typeof bracket.value=="string"&&(bracket.value=this.raiseToInstanceLevel(bracket.value));rule.key==="Note"&&rule.text&&(rule.text=this.raiseToInstanceLevel(rule.text))}catch{continue}}}class Migration703SpellDamageStructure extends MigrationBase{static{__name(this,"Migration703SpellDamageStructure")}static{__name2(this,"Migration703SpellDamageStructure")}static version=.703;async updateItem(source){if(source.type==="spell"){const system=source.system;isObject(system.damage)?(!("value"in system.damage)||!isObject(system.damage.value))&&(system.damage.value={}):system.damage={value:{}}}}}class Migration704MartialProficiencyRE extends MigrationBase{static{__name(this,"Migration704MartialProficiencyRE")}static{__name2(this,"Migration704MartialProficiencyRE")}static version=.704;async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>r.key==="LinkedProficiency");for(const rule of rules)if(rule.key="MartialProficiency",rule.definition=rule.predicate,delete rule.predicate,typeof rule.slug=="string"&&itemSource.system.slug?.endsWith("-weapon-familiarity")&&!rule.label){const key=sluggify(rule.slug,{camel:"bactrian"});rule.label=`PF2E.SpecificRule.MartialProficiency.${key}`}if(itemSource.type==="class"&&itemSource.system.slug==="gunslinger"&&itemSource.system.rules.length===0){const gunslingerRules=[{definition:{all:["weapon:category:simple"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.SimpleFirearmsCrossbows",slug:"simple-firearms-crossbows",value:2},{definition:{all:["weapon:category:martial"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.MartialFirearmsCrossbows",slug:"martial-firearms-crossbows",value:2},{definition:{all:["weapon:category:advanced"],any:["weapon:group:firearm","weapon:tag:crossbow"]},key:"MartialProficiency",label:"PF2E.SpecificRule.MartialProficiency.AdvancedFirearmsCrossbows",slug:"advanced-firearms-crossbows",value:1}];itemSource.system.rules=gunslingerRules}}}class Migration705GunslingerCatchUp extends MigrationBase{static{__name(this,"Migration705GunslingerCatchUp")}static{__name2(this,"Migration705GunslingerCatchUp")}static version=.705;#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateItem(source){if(this.#isClassFeature(source))switch(source.system.slug){case"singular-expertise":{const rules=[{key:"FlatModifier",selector:"firearm-weapon-group-damage",type:"circumstance",value:1},{key:"FlatModifier",predicate:{all:["weapon:tag:crossbow"]},selector:"bow-weapon-group-damage",type:"circumstance",value:1}];source.system.rules=rules;break}case"gunslinger-weapon-mastery":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:2},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:3}];source.system.rules=rules;break}case"gunslinging-legend":{const rules=[{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.unarmed.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.advanced-firearms-crossbows.rank",value:3},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.simple-firearms-crossbows.rank",value:4},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.martial-firearms-crossbows.rank",value:4}];source.system.rules=rules;break}}}}class Migration706FormulasAtInstanceLevelEverythingElse extends Migration702REFormulasAtInstanceLevel{static{__name(this,"Migration706FormulasAtInstanceLevelEverythingElse")}static{__name2(this,"Migration706FormulasAtInstanceLevelEverythingElse")}static version=.706;async updateItem(itemSource){if(itemSource.system.description.value&&(itemSource.system.description.value=this.replaceInlineRolls(itemSource.system.description.value)),itemSource.type==="spell")for(const value of Object.values(itemSource.system.damage.value))value.value=this.raiseToInstanceLevel(value.value);if(itemSource.type==="melee")for(const value of Object.values(itemSource.system.damageRolls))value.damage=this.raiseToInstanceLevel(value.damage)}replaceInlineRolls(value){return value.replace(/\[\[(.*)\]\]/g,match=>this.raiseToInstanceLevel(match))}}class Migration707BracketedFormulasAtInstanceLevel extends Migration702REFormulasAtInstanceLevel{static{__name(this,"Migration707BracketedFormulasAtInstanceLevel")}static{__name2(this,"Migration707BracketedFormulasAtInstanceLevel")}static version=.707}class Migration708SpecificRuleLabel extends MigrationBase{static{__name(this,"Migration708SpecificRuleLabel")}static{__name2(this,"Migration708SpecificRuleLabel")}static version=.708;async updateItem(itemSource){for(const rule of itemSource.system.rules)rule.label&&(rule.label=String(rule.label).replace(/\bSpecificRules\b/,"SpecificRule"))}}class Migration709REFormulasAtInstanceLevelRedux extends Migration702REFormulasAtInstanceLevel{static{__name(this,"Migration709REFormulasAtInstanceLevelRedux")}static{__name2(this,"Migration709REFormulasAtInstanceLevelRedux")}static version=.709;walkObject(obj){if(Array.isArray(obj))for(let i=0;i<obj.length;i++)obj[i]=this.findAndMigrateFormulas(obj[i]);else for(const[key,value]of Object.entries(obj))obj[key]=this.findAndMigrateFormulas(value)}findAndMigrateFormulas(value){return typeof value=="string"&&value.includes("@")?this.raiseToInstanceLevel(value):(isObject(value)&&this.walkObject(value),value)}async updateItem(itemSource){const rules=itemSource.system.rules.filter(r=>r.key==="BattleForm");for(const rule of rules)this.walkObject(rule);itemSource.type==="spell"&&itemSource.system.slug==="wild-shape"&&(itemSource.system.rules=[])}}class Migration710RarityToString extends MigrationBase{static{__name(this,"Migration710RarityToString")}static{__name2(this,"Migration710RarityToString")}static version=.71;updateTraits(traits){typeof traits?.rarity=="object"&&traits.rarity!==null&&(traits.rarity=traits.rarity.value)}async updateActor(actorSource){"traits"in actorSource.system&&this.updateTraits(actorSource.system.traits??null)}async updateItem(itemSource){"traits"in itemSource.system&&this.updateTraits(itemSource.system.traits??null)}}const toDelete=["featType","actionCategory","actions","actionType","level","location"];class Migration711HeritageItems extends MigrationBase{static{__name(this,"Migration711HeritageItems")}static{__name2(this,"Migration711HeritageItems")}static version=.711;#isHeritageFeature(feature){return feature.type==="feat"&&feature.system.featType?.value==="heritage"}#officialAncestries={tengu:{name:"Tengu",uuid:"Compendium.pf2e.ancestries.Item.18xDKYPDBLEv2myX"},kitsune:{name:"Kitsune",uuid:"Compendium.pf2e.ancestries.Item.4BL5wf1VF9feC2rY"},poppet:{name:"Poppet",uuid:"Compendium.pf2e.ancestries.Item.6F2fSFC1Eo1JdpY4"},kobold:{name:"Kobold",uuid:"Compendium.pf2e.ancestries.Item.7oQxL6wgsokD3QXG"},catfolk:{name:"Catfolk",uuid:"Compendium.pf2e.ancestries.Item.972EkpJOPv9KkQIW"},dwarf:{name:"Dwarf",uuid:"Compendium.pf2e.ancestries.Item.BYj5ZvlXZdpaEgA6"},gnome:{name:"Gnome",uuid:"Compendium.pf2e.ancestries.Item.CYlfsYLJcBOgqKtD"},fleshwarp:{name:"Fleshwarp",uuid:"Compendium.pf2e.ancestries.Item.FXlXmNBFiiz9oasi"},strix:{name:"Strix",uuid:"Compendium.pf2e.ancestries.Item.GXcC6oVa5quzgNHD"},android:{name:"Android",uuid:"Compendium.pf2e.ancestries.Item.GfLwE884NoRC7cRi"},halfling:{name:"Halfling",uuid:"Compendium.pf2e.ancestries.Item.GgZAHbrjnzWOZy2v"},lizardfolk:{name:"Lizardfolk",uuid:"Compendium.pf2e.ancestries.Item.HWEgF7Gmoq55VhTL"},human:{name:"Human",uuid:"Compendium.pf2e.ancestries.Item.IiG7DgeLWYrSNXuX"},ratfolk:{name:"Ratfolk",uuid:"Compendium.pf2e.ancestries.Item.P6PcVnCkh4XMdefw"},elf:{name:"Elf",uuid:"Compendium.pf2e.ancestries.Item.PgKmsA2aKdbLU6O0"},anadi:{name:"Anadi",uuid:"Compendium.pf2e.ancestries.Item.TQEqWqc7BYiadUdY"},sprite:{name:"Sprite",uuid:"Compendium.pf2e.ancestries.Item.TRqoeYfGAFjQbviF"},goloma:{name:"Goloma",uuid:"Compendium.pf2e.ancestries.Item.c4secsSNG2AO7I5i"},leshy:{name:"Leshy",uuid:"Compendium.pf2e.ancestries.Item.cdhgByGG1WtuaK73"},fetchling:{name:"Fetchling",uuid:"Compendium.pf2e.ancestries.Item.hIA3qiUsxvLZXrFP"},grippli:{name:"Grippli",uuid:"Compendium.pf2e.ancestries.Item.hXM5jXezIki1cMI2"},automaton:{name:"Automaton",uuid:"Compendium.pf2e.ancestries.Item.kYsBAJ103T44agJF"},orc:{name:"Orc",uuid:"Compendium.pf2e.ancestries.Item.lSGWXjcbOa6O5fTx"},hobgoblin:{name:"Hobgoblin",uuid:"Compendium.pf2e.ancestries.Item.piNLXUrm9iaGqD2i"},shoony:{name:"Shoony",uuid:"Compendium.pf2e.ancestries.Item.q6rsqYARyOGXZA8F"},goblin:{name:"Goblin",uuid:"Compendium.pf2e.ancestries.Item.sQfjTMDaZbT9DThq"},conrasu:{name:"Conrasu",uuid:"Compendium.pf2e.ancestries.Item.tZn4qIHCUA6wCdnI"},gnoll:{name:"Gnoll",uuid:"Compendium.pf2e.ancestries.Item.vxbQ1Yw4qwgjTzqo"},shisk:{name:"Shisk",uuid:"Compendium.pf2e.ancestries.Item.x1YinOddgUxwOLqP"},azarketi:{name:"Azarketi",uuid:"Compendium.pf2e.ancestries.Item.yFoojz6q3ZjvceFw"}};#heritagesWithoutAncestryInName={"half-elf":"human","half-orc":"human","skilled-heritage":"human","versatile-heritage":"human",draxie:"sprite",grig:"sprite",melixie:"sprite",nyktera:"sprite",pixie:"sprite","deep-rat":"ratfolk","desert-rat":"ratfolk","longsnout-rat":"ratfolk","sewer-rat":"ratfolk","shadow-rat":"ratfolk","snow-rat":"ratfolk","tunnel-rat":"ratfolk","rite-of-invocation":"conrasu","rite-of-knowing":"conrasu","rite-of-light":"conrasu","rite-of-passage":"conrasu","rite-of-reinforcement":"conrasu"};#ancestrySlugs=Object.keys(this.#officialAncestries);#heritageFromFeat(feature){const featureSlug=feature.system.slug??"",ancestrySlug=this.#heritagesWithoutAncestryInName[featureSlug]??this.#ancestrySlugs.find(s=>featureSlug.includes(s)),ancestryReference=this.#officialAncestries[ancestrySlug??""]??null,traits=feature.system.traits,{flags}=feature;return flags.core?.sourceId&&(flags.core.sourceId=flags.core.sourceId.replace("ancestryfeatures","heritages")),{_id:foundry.utils.randomID(),type:"heritage",img:feature.img.endsWith("/feat.svg")?"systems/pf2e/icons/default-icons/heritage.svg":feature.img,name:feature.name,effects:[],folder:feature.folder,flags:feature.flags,sort:feature.sort,ownership:feature.ownership,system:{description:feature.system.description,rules:feature.system.rules,schema:feature.system.schema,_migration:{version:null,previous:null},slug:feature.system.slug,ancestry:ancestryReference,traits:{value:traits.value.filter(t=>(t in creatureTraits||t.startsWith("hb_"))&&!(t in this.#officialAncestries)),rarity:traits.rarity,otherTags:[]}}}}async updateActor(actorSource){const heritageFeatures=actorSource.items.filter(i=>this.#isHeritageFeature(i)),firstHeritageFeature=heritageFeatures[0];if(!actorSource.items.some(i=>i.type==="heritage")&&firstHeritageFeature&&actorSource.type==="character"){const heritageSource=this.#heritageFromFeat(firstHeritageFeature);actorSource.items.push(heritageSource);const details=actorSource.system.details;details.heritage&&(details["-=heritage"]=null,"game"in globalThis||delete details.heritage)}for(const feature of heritageFeatures)actorSource.items.splice(actorSource.items.indexOf(feature),1)}async updateItem(itemSource,actorSource){if(actorSource||!this.#isHeritageFeature(itemSource))return;const newSource=itemSource;newSource.type="heritage",itemSource.img==="systems/pf2e/icons/default-icons/feat.svg"&&(itemSource.img="systems/pf2e/icons/default-icons/heritage.svg");const newSystemData=this.#heritageFromFeat(itemSource).system,deletionProperties=toDelete.map(k=>`-=${k}`);for(const property of deletionProperties)newSystemData[property]=null;if(!("game"in globalThis))for(const property of toDelete)delete newSystemData[property];newSource.system=newSystemData}}class Migration712ActorShieldStructure extends MigrationBase{static{__name(this,"Migration712ActorShieldStructure")}static{__name2(this,"Migration712ActorShieldStructure")}static version=.712;async updateActor(source){if(source.type==="character"||source.type==="npc"){const attributes=source.system.attributes;attributes.shield&&(attributes["-=shield"]=null,"game"in globalThis?attributes.shield={}:delete attributes.shield)}}}class Migration713FistToStrikeRE extends MigrationBase{static{__name(this,"Migration713FistToStrikeRE")}static{__name2(this,"Migration713FistToStrikeRE")}static version=.713;async updateItem(itemSource){const fistFeatures=["powerful-fist","martial-artist-dedication"];if(!(itemSource.type==="feat"&&fistFeatures.includes(itemSource.system.slug))||itemSource.system.rules.some(rule=>rule.key==="Strike"))return;const strike={key:"Strike",img:"systems/pf2e/icons/features/classes/powerful-fist.webp",slug:"fist",category:"unarmed",damage:{base:{damageType:"bludgeoning",dice:1,die:"d6"}},group:"brawling",label:"PF2E.Strike.Fist.Label",range:null,traits:["agile","finesse","nonlethal","unarmed"]};itemSource.system.rules=[strike]}}class Migration714RangeIncrementREs extends MigrationBase{static{__name(this,"Migration714RangeIncrementREs")}static{__name2(this,"Migration714RangeIncrementREs")}static version=.714;farLobber={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:30};farShot={definition:{all:["weapon:ranged"]},key:"AdjustStrike",mode:"multiply",property:"range-increment",value:2};farThrow={key:"AdjustModifier",mode:"add",predicate:{all:["weapon:trait:thrown"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1};huntPrey={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:2",predicate:{all:["hunted-prey"]}};legendaryShot={key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:5"};masterfulHunter=(()=>({key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",predicate:{all:["hunted-prey",{gte:["weapon:proficiency:rank",3]}]}}))();shootistsEdge=(()=>[{key:"ActiveEffectLike",mode:"upgrade",path:"system.attributes.classDC.rank",value:3},{key:"RollOption",domain:"ranged-attack-roll",option:"ignore-range-penalty:3",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}])();triangulate=[{default:!0,key:"ToggleProperty",label:"PF2E.SpecificRule.ToggleProperty.Triangulate",property:"flags.pf2e.rollOptions.all.triangulate"},{domain:"ranged-attack-roll",key:"RollOption",option:"ignore-range-penalty:2",predicate:{all:["triangulate"]}},{key:"AdjustModifier",mode:"add",predicate:{all:["triangulate"]},selectors:["ranged-attack-roll"],slug:"range-penalty",value:1}];uncannyBombs={definition:{all:["weapon:base:alchemical-bomb"]},key:"AdjustStrike",mode:"upgrade",property:"range-increment",value:60};unerringShot=(()=>({key:"RollOption",option:"ignore-range-penalty",phase:"beforeRoll",predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}}))();async updateItem(source){const{rules}=source.system;if(source.type==="feat")switch(source.system.slug){case"far-lobber":{source.system.rules=[this.farLobber];return}case"far-shot":{source.system.rules=[this.farShot];return}case"far-throw":{source.system.rules=[this.farThrow];return}case"hunt-prey":{!rules.some(r=>r.key==="RollOption"&&r.option===this.huntPrey.option)&&rules.push(this.huntPrey);return}case"legendary-shot":{source.system.rules=[this.legendaryShot];return}case"masterful-hunter":{!rules.some(r=>r.key==="RollOption"&&r.option===this.masterfulHunter.option)&&rules.push(this.masterfulHunter);return}case"shootists-edge":{source.system.rules=this.shootistsEdge;return}case"triangulate":{source.system.rules=this.triangulate;return}case"uncanny-bombs":{source.system.rules=[this.uncannyBombs];return}case"unerring-shot":{source.system.rules=[this.unerringShot];return}}}}class Migration715DangerousSorcery extends MigrationBase{static{__name(this,"Migration715DangerousSorcery")}static{__name2(this,"Migration715DangerousSorcery")}static version=.715;dangerousSorcery={key:"FlatModifier",phase:"afterDerived",predicate:{all:["item:spell-slot","item:duration:0","damaging-effect"]},selector:"spell-damage",value:"@spell.level"};async updateItem(source){if(source.type!=="feat")return;(source.system.slug??sluggify(source.name))==="dangerous-sorcery"&&!source.system.rules.length&&(source.system.rules=[this.dangerousSorcery])}}class Migration716StrikeDamageSelector extends MigrationBase{static{__name(this,"Migration716StrikeDamageSelector")}static{__name2(this,"Migration716StrikeDamageSelector")}static version=.716;itemsToSkip=new Set(["effect-fanatical-frenzy","effect-heroic-recovery","effect-lantern-of-hope","effect-lantern-of-hope-gestalt","spell-effect-inspire-courage","spell-effect-inspire-heroics-courage-2","spell-effect-inspire-heroics-courage-3","spell-effect-stoke-the-heart"]);async updateItem(source){if(this.itemsToSkip.has(source.system.slug??""))return;const{rules}=source.system;for(const rule of rules)isObject(rule)&&["damage","mundane-damage"].includes(String(rule.selector??""))&&(rule.selector="strike-damage")}}class Migration717TakeFeatLimits extends MigrationBase{static{__name(this,"Migration717TakeFeatLimits")}static{__name2(this,"Migration717TakeFeatLimits")}static version=.717;levelOneOnly=new Set(["celestial-eyes","chance-death","deliberate-death","elemental-eyes","eyes-of-the-night","fiendish-eyes","gravesight","willing-death"]);maxTakeable={"additional-lore":1/0,"advanced-domain":1/0,"advanced-general-training":1/0,"animal-senses":1/0,"animal-senses-darkvision":1/0,"animal-senses-low-light-vision":1/0,"animal-senses-scent-imprecise":1/0,"armor-proficiency":3,assurance:1/0,"automatic-knowledge":1/0,"blessing-of-the-sun-gods":1/0,"consult-the-spirits":1/0,"domain-initiate":1/0,"general-training":1/0,"greater-animal-senses":1/0,"greater-sun-blessing":1/0,"hellknight-order-cross-training":1/0,"living-weapon":1/0,"magic-arrow":1/0,"modular-dynamo":1/0,multilingual:1/0,"settlement-scholastics":1/0,"skill-training":1/0,"terrain-stalker":1/0};async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??"";source.system.traits.value.includes("lineage")||this.levelOneOnly.has(slug)?source.system.onlyLevel1=!0:"game"in globalThis&&(source.system.onlyLevel1=!1),!source.system.onlyLevel1&&slug in this.maxTakeable?source.system.maxTakable=this.maxTakeable[slug]:"game"in globalThis&&(source.system.maxTakable=1)}}function isEquipped(usage,equipped){return equipped.carryType==="dropped"?!1:usage.type==="carried"?!0:usage.type!==equipped.carryType||usage.type==="worn"&&usage.where&&!equipped.inSlot?!1:usage.type==="held"?(equipped.handsHeld??0)>=(usage.hands??1):!0}__name(isEquipped,"isEquipped"),__name2(isEquipped,"isEquipped");function getUsageDetails(usage){switch(usage){case"carried":case"":return{value:"carried",type:"carried"};case"held-in-one-hand":case"held-in-one-plus-hands":case"held-in-one-or-two-hands":return{value:usage,type:"held",hands:1};case"held-in-two-hands":return{value:usage,type:"held",hands:2};case"worn":return{value:usage,type:"worn"};case"wornarmor":case"wornamulet":case"wornanklets":case"wornarmbands":case"wornbackpack":case"wornbarding":case"wornbelt":case"wornbeltpouch":case"wornbracers":case"wornbracelet":case"worncloak":case"worncirclet":case"wornclothing":case"worncollar":case"worncrown":case"wornepaulet":case"worneyepiece":case"wornfootwear":case"worngarment":case"worngloves":case"wornheadwear":case"wornmask":case"wornnecklace":case"wornonbelt":case"wornring":case"wornshoes":case"wornhorseshoes":case"wornsaddle":case"wornwrist":return{value:usage,type:"worn",where:usage.substring(4)}}return{value:usage,type:"worn"}}__name(getUsageDetails,"getUsageDetails"),__name2(getUsageDetails,"getUsageDetails");class Migration718CarryType extends MigrationBase{static{__name(this,"Migration718CarryType")}static{__name2(this,"Migration718CarryType")}static version=.718;async updateItem(itemData,actor){if(!isPhysicalData(itemData))return;const systemData=itemData.system;if(systemData.usage instanceof Object||(systemData.usage={value:"held-in-one-hand"}),systemData.usage.value==="worn-gloves")systemData.usage.value="worngloves";else if(itemData.type==="armor"){const category=itemData.system.category;systemData.usage.value=category==="shield"?"held-in-one-hand":"wornarmor"}else itemData.type==="equipment"&&systemData.slug?.startsWith("clothing-")&&(systemData.usage.value="worn");if("game"in globalThis||actor)systemData.equipped??={carryType:"worn"},systemData.equipped.carryType??="worn";else{delete systemData.equipped;return}const equipped=systemData.equipped;if(!("value"in equipped))return;if(!(actor&&["character","npc"].includes(actor.type??""))){equipped["-=value"]=null,delete equipped.value;return}const containerId=itemData.system.containerId??{value:null};if(containerId instanceof Object&&containerId.value){const inStowingContainer=actor.items.some(i=>i.type==="backpack"&&i.system.stowing&&i._id===containerId.value);if(!inStowingContainer)containerId.value=null;else if(inStowingContainer){equipped.carryType="stowed";return}}equipped.carryType="worn";const usage=getUsageDetails(String(systemData.usage?.value));usage.type==="worn"?equipped.inSlot=!!equipped.value:usage.type==="held"&&(equipped.value&&(equipped.carryType="held"),equipped.handsHeld=equipped.value?usage.hands??1:0),equipped["-=value"]=null,delete equipped.value}}class Migration719ShrugFlanking extends MigrationBase{static{__name(this,"Migration719ShrugFlanking")}static{__name2(this,"Migration719ShrugFlanking")}static version=.719;async updateItem(source,actorSource){const slug=source.system.slug??"";switch(source.type){case"action":{if(slug==="all-around-vision")source.system.rules=[this.allAroundVision];else if(actorSource?.type==="npc"&&source.name==="Deny Advantage"){const npcId=actorSource.flags.core?.sourceId?.replace(/^Compendium\.[^.]+\./,"")??actorSource._id;if(this.needsDenyAdvantage(source.system.rules)){const rule=this.npcDenyAvantage(npcId);source.system.rules.push(rule)}}return}case"effect":{slug==="stance-wolf-stance"&&(source.system.rules=this.wolfStanceRules);return}case"feat":{source.system.slug=source.system.slug?.replace(/^deny-advantage-level-\d$/,"deny-advantage")??null;const featSlug=source.system.slug??"";if(["constant-gaze","deny-advantage"].includes(featSlug)&&this.needsDenyAdvantage(source.system.rules))source.system.rules.push(this.denyAdvantage);else if(featSlug==="gang-up")source.system.rules=[this.gangUp];else if(featSlug.startsWith("side-by-side")){const sideBySide=this.gangUp;sideBySide.value="animal-companion",source.system.rules=[sideBySide]}else if(["pack-tactics","squad-tactics"].includes(featSlug)){const tactics=this.gangUp;tactics.value=2,source.system.rules=[tactics]}}}}get allAroundVision(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flankable",value:!1}}get denyAdvantage(){return{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.flatFootable",value:"@actor.level"}}get gangUp(){return{key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:1}}npcVariants=new Map([["YsBSkW3aFwU1bl3w",13],["0Kb4z4h8KVqfrIju",8],["B09JfuBZHjcRXztU",4],["aaDiR0EIWRQx8wdy",3],["x4m5ks6Rd8fYzXPm",4],["qKHkamxIPbqxEiwp",6],["lCvJquCqvZJVnafy",8],["vkLhqX5oR1t89puZ",7],["aIT5S2fKgMZ6pVP2",11],["l6EuZR6zCdqyCywW",6],["QKkvnlqrhgLHuP1t",10],["ZY3q7AV1qbwWwNl2",8],["6pPolNZycfDiOl2I",8],["cQMM2Ld0IBM9GcDo",11],["VkG5yl9xcmziwpQD",4],["JrowrtDilEG8dN2s",11],["1lkay2gwgEquq0NF",6],["EMl8hARVJk8SNVyW",4],["j31HXlZiUqQrAHSB",12],["pjnTEh0NVd1DB6jI",4]]);get wolfStanceRules(){return[{category:"unarmed",damage:{base:{damageType:"piercing",dice:1,die:"d8"}},group:"brawling",key:"Strike",label:"PF2E.SpecificRule.Stance.Attack.WolfJaws",range:null,slug:"wolf-jaws",traits:["agile","backstabber","finesse","unarmed","nonlethal"]},{definition:{all:["weapon:wolf-jaws"]},key:"AdjustStrike",mode:"add",predicate:{all:["self:flanking"]},property:"traits",value:"trip"}]}npcDenyAvantage(npcId=""){const{denyAdvantage}=this;return denyAdvantage.value=this.npcVariants.get(npcId)??"@actor.level",denyAdvantage}needsDenyAdvantage(rules){return!rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="system.attributes.flanking.flatFootable")}}class Migration720UpdateSpellDescriptions extends MigrationBase{static{__name(this,"Migration720UpdateSpellDescriptions")}static{__name2(this,"Migration720UpdateSpellDescriptions")}static version=.72;spellUUIDs=new Set(["Compendium.pf2e.spells-srd.GoKkejPj5yWJPIPK","Compendium.pf2e.spells-srd.1b55SgYTV65JvmQd","Compendium.pf2e.spells-srd.b515AZlB0sridKSq","Compendium.pf2e.spells-srd.NBSBFHxBm88qxQUy","Compendium.pf2e.spells-srd.9TauMFkIsmvKJNzZ","Compendium.pf2e.spells-srd.LoBjvguamA12iyW0","Compendium.pf2e.spells-srd.IWUe32Y5k2QFd7YQ","Compendium.pf2e.spells-srd.WBmvzNDfpwka3qT4"]);spells=UUIDUtils.fromUUIDs([...this.spellUUIDs]);async updateItem(source){if(!(source.type==="spell"&&setHasElement(this.spellUUIDs,source.flags.core?.sourceId)))return;const spell=(await this.spells).find(s=>s instanceof SpellPF2e&&s.slug===source.system.slug);spell&&(source.system.description.value=spell.description)}}class Migration721SetReloadValues extends MigrationBase{static{__name(this,"Migration721SetReloadValues")}static{__name2(this,"Migration721SetReloadValues")}static version=.721;toUpdate=new Set(["air-repeater","composite-longbow","composite-shortbow","godsbreath-bow","hunters-bow","long-air-repeater","longbow","oathbow","repeating-crossbow","repeating-hand-crossbow","shortbow","singing-shortbow-greater","singing-shortbow","sky-piercing-bow"]);async updateItem(source){source.type==="weapon"&&setHasElement(this.toUpdate,source.system.slug)&&(source.system.reload.value="0")}}class Migration722CraftingSystemData extends MigrationBase{static{__name(this,"Migration722CraftingSystemData")}static{__name2(this,"Migration722CraftingSystemData")}static version=.722;async updateActor(source){if(source.type!=="character")return;if(!isObject(source.system.crafting)){const filledCrafting={entries:{},formulas:[]};source.system.crafting=filledCrafting}const crafting=source.system.crafting??{};(!isObject(crafting.entries)||Array.isArray(crafting.entries))&&(crafting.entries={}),Array.isArray(crafting.formulas)||(crafting.formulas=[])}}class Migration723CumulativeItemBonuses extends MigrationBase{static{__name(this,"Migration723CumulativeItemBonuses")}static{__name2(this,"Migration723CumulativeItemBonuses")}static version=.723;stanceFeats=(async()=>(await UUIDUtils.fromUUIDs(["Compendium.pf2e.feats-srd.ZPclfDmiHzEqblry","Compendium.pf2e.feats-srd.ZL5UU9quCTvcWzfY","Compendium.pf2e.feats-srd.n2hawNmzW7DBn1Lm","Compendium.pf2e.feats-srd.hO4sKslTrSQMLbGx"])).filter(d=>d instanceof FeatPF2e&&!!d.slug).reduce((record,f)=>({...record,[f.slug]:f}),{}))();mountainPattern=/^mountain-(?:stance|stronghold|quake)$/;async updateActor(source){if(source.type!=="character")return;const effects=source.items.filter(i=>i.type==="effect");for(const effect of effects)effect.system.slug?.startsWith("stance-mountain")&&source.items.findSplice(i=>i===effect)}async updateItem(source){if(source.system.slug)switch(source.type){case"feat":{if(source.system.slug==="animal-skin"){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.rules=feat.toObject().system.rules)}else if(this.mountainPattern.test(source.system.slug)){const feat=(await this.stanceFeats)[source.system.slug];feat&&(source.system.description.value=feat.description)}return}case"equipment":{if(!source.system.slug.startsWith("bracers-of-armor-"))return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="bracers-of-armor");return}case"effect":{if(source.system.slug!=="spell-effect-mage-armor")return;for(const rule of source.system.rules)rule.key==="FlatModifier"&&(rule.slug="mage-armor")}}}async updateMacro(source){source.type==="script"&&source.command.includes("Stance: Mountain Stance")&&(source.command=String.raw`const actors = game.user.getActiveTokens().flatMap((t) => t.actor ?? []);
|
|
if (actors.length === 0) {
|
|
return ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected", { localize: true });
|
|
}
|
|
|
|
const ITEM_UUID = "Compendium.pf2e.feat-effects.gYpy9XBPScIlY93p"; // Stance: Mountain Stance
|
|
const source = (await fromUuid(ITEM_UUID)).toObject();
|
|
source.flags = mergeObject(source.flags ?? {}, { core: { sourceId: ITEM_UUID } });
|
|
|
|
for (const actor of actors) {
|
|
const existing = actor.itemTypes.effect.find((e) => e.flags.core?.sourceId === ITEM_UUID);
|
|
if (existing) {
|
|
await existing.delete();
|
|
} else {
|
|
await actor.createEmbeddedDocuments("Item", [source]);
|
|
}
|
|
}`)}}class Migration724CraftingMaxItemLevel extends MigrationBase{static{__name(this,"Migration724CraftingMaxItemLevel")}static{__name2(this,"Migration724CraftingMaxItemLevel")}static version=.724;pathPattern=/^data\.crafting\.entries\.([-a-z]+)\.maxItemLevel$/i;async updateItem(source){if(source.type!=="feat")return;if(source.system.slug==="advanced-alchemy"){const rules=source.system.rules;for(const rule of rules)rule.predicate={all:["self:class:alchemist"]},rule.key==="CraftingEntry"&&(delete rule.name,rule.label="PF2E.TraitAlchemist")}else if(source.system.slug?.endsWith("-dedication")&&source.system.slug!=="alchemist-dedication"){const rules=source.system.rules.filter(r=>r.key==="CraftingEntry");for(const rule of rules){delete rule.name;const i18nKey=sluggify(source.system.slug.replace(/-dedication$/,""),{camel:"bactrian"});rule.label=`PF2E.SpecificRule.DedicationCraftingEntry.${i18nKey}`}}const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike");for(const rule of aeLikes){if(typeof rule.path!="string")continue;const selector=this.pathPattern.exec(rule.path)?.[1]??null;if(selector){const predicate=rule.predicate=foundry.utils.mergeObject({all:[]},isObject(rule.predicate)?rule.predicate:{}),slug=sluggify(selector);predicate.all=Array.from(new Set([...predicate.all,`crafting:entry:${slug}`]))}}}}class Migration725QuickClimbREs extends MigrationBase{static{__name(this,"Migration725QuickClimbREs")}static{__name2(this,"Migration725QuickClimbREs")}static version=.725;quickClimb=[{key:"BaseSpeed",predicate:{all:["self:skill:ath:rank:4"]},selector:"climb",value:"@actor.attributes.speed.value"},{key:"Note",predicate:{all:["action:climb"]},selector:"athletics",text:'<p class="compact-text"><strong>{item|name}</strong> You move 5 more feet on a success, and 10 more feet on a critical success.</p>'}];async updateItem(source){source.type==="feat"&&source.system.slug==="quick-climb"&&(source.system.rules=foundry.utils.deepClone(this.quickClimb))}}class Migration726JournalSetting extends MigrationBase{static{__name(this,"Migration726JournalSetting")}static{__name2(this,"Migration726JournalSetting")}static version=.726;async migrate(){const sheetClasses=game.settings.get("core","sheetClasses");if(isObject(sheetClasses)&&sheetClasses.JournalEntry?.base)return;const theme=game.settings.storage.get("world").getItem("pf2e.journalEntryTheme");if(!theme)return;const base=theme==="pf2eTheme"?"pf2e.JournalSheetStyledPF2e":"pf2e.JournalSheetPF2e";DocumentSheetConfig.updateDefaultSheets({JournalEntry:{base}})}}class Migration727TrimSelfRollOptions extends MigrationBase{static{__name(this,"Migration727TrimSelfRollOptions")}static{__name2(this,"Migration727TrimSelfRollOptions")}static version=.727;optionPattern=/^self:(ability|class|feat(?:ure)?|perception|skill):/;optionReplacement="$1:";trimRollOption(option){return option.replace(this.optionPattern,this.optionReplacement)}trimPredicates(obj){for(const[key,value]of Object.entries(obj))typeof value=="string"?obj[key]=this.trimRollOption(value):Array.isArray(value)?obj[key]=value.map(e=>typeof e=="string"?this.trimRollOption(e):isObject(e)?this.trimPredicates(e):e):isObject(value)&&(obj[key]=this.trimPredicates(value));return obj}async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r))}}class Migration728FlattenPhysicalProperties extends MigrationBase{static{__name(this,"Migration728FlattenPhysicalProperties")}static{__name2(this,"Migration728FlattenPhysicalProperties")}static version=.728;booleanKeys=["temporary","collapsed"];numericKeys=["quantity","hardness"];stringKeys=["stackGroup","containerId"];async updateItem(source){if(!isPhysicalData(source))return;const systemSource=source.system;if(systemSource.currency&&(delete systemSource.currency,systemSource["-=currency"]=null),systemSource.hands&&(delete systemSource.hands,systemSource["-=hands"]=null),systemSource.equipped&&isObject$1(systemSource.invested)){const value=systemSource.invested.value;if(typeof value=="boolean"||value===null){const shouldBeBoolean=source.system.traits.value.includes("invested")||source.type==="armor"&&(systemSource.potencyRune?.value??0)>0;systemSource.equipped.invested=shouldBeBoolean?!!value:null}}if(delete systemSource.invested,systemSource["-=invested"]=null,systemSource.capacity&&source.type!=="book"&&(delete systemSource.capacity,systemSource["-=capacity"]=null),source.type!=="backpack"&&(delete systemSource.bulkCapacity,systemSource["-=bulkCapacity"]=null,delete systemSource.collapsed,systemSource["-=collapsed"]=null),systemSource.size instanceof Object){const size=SIZES.includes(systemSource.size.value)?systemSource.size.value:"med";systemSource.size=size}"brokenThreshold"in systemSource&&(systemSource.brokenThreshold instanceof Object&&(systemSource.hp.brokenThreshold=Number(systemSource.brokenThreshold.value)),delete systemSource.brokenThreshold,systemSource["-=brokenThreshold"]=null),systemSource.hp.value=Number(systemSource.hp.value),systemSource.maxHp instanceof Object&&(systemSource.hp.max=Number(systemSource.maxHp.value)||0,delete systemSource.maxHp,systemSource["-=maxHp"]=null);for(const key of this.booleanKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=value.value)}for(const key of this.numericKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=Number(value.value)||0)}for(const key of this.stringKeys){const value=systemSource[key];value instanceof Object&&(systemSource[key]=String(value.value)||null)}}}class Migration729CumulativeItemBonusCleanup extends MigrationBase{static{__name(this,"Migration729CumulativeItemBonusCleanup")}static{__name2(this,"Migration729CumulativeItemBonusCleanup")}static version=.729;#explorersClothingVariants=new Set(["clothing-explorers","robe-of-the-arch-magi","robe-of-the-arch-magi-greater","sarkorian-god-caller-garb"]);isExplorersClothing(source){return source.type==="armor"&&this.#explorersClothingVariants.has(source.system.slug??"")}isStanceEffectOrAnimalSkinFeat(source){return source.type==="effect"&&source.system.slug==="stance-mountain-stance"||source.type==="feat"&&source.system.slug==="animal-skin"}async updateItem(source){if(this.isExplorersClothing(source))source.system.category="unarmored",source.system.group="cloth",source.system.baseItem="explorers-clothing",source.system.traits.value.includes("comfort")||source.system.traits.value.push("comfort");else if(this.isStanceEffectOrAnimalSkinFeat(source)){const rule=source.system.rules.find(r=>r.key==="AdjustModifier"&&r.slug==="clothing-explorers");rule&&(rule.slug="explorers-clothing")}else if(source.type==="equipment"){const isBracers=!!source.system.slug?.startsWith("bracers-of-armor-");for(const rule of source.system.rules)rule.key==="FlatModifier"&&rule.slug==="bracers-of-armor"&&!isBracers&&(source.system.slug==="metuaks-pendant"?rule.slug="metuaks-pendant":delete rule.slug)}}}class Migration730DeruneHandwraps extends MigrationBase{static{__name(this,"Migration730DeruneHandwraps")}static{__name2(this,"Migration730DeruneHandwraps")}static version=.73;async updateItem(source){if(source.type==="weapon"&&source.system.slug==="handwraps-of-mighty-blows"){const{rules}=source.system;for(const rule of[...rules])["Striking","WeaponPotency"].includes(String(rule.key))&&source.system.rules.splice(rules.indexOf(rule),1)}}}class Migration731TogglePropertyToRollOption extends Migration727TrimSelfRollOptions{static{__name(this,"Migration731TogglePropertyToRollOption")}static{__name2(this,"Migration731TogglePropertyToRollOption")}static version=.731;optionPattern=/^target:flatFooted$/;optionReplacement="target:condition:flat-footed";#pathPattern=/^flags\.pf2e\.rollOptions\.([^.]+)\.([^.]+)$/;async updateItem(source){source.system.rules=source.system.rules.map(r=>this.trimPredicates(r));const rules=source.system.rules;for(const rule of[...rules]){if(rule.key!=="ToggleProperty")continue;const match=this.#pathPattern.exec(rule.property?.trim()??"");if(!(match?.length===3&&match[1].length>=2&&match[2].length>=1)){rules.splice(rules.indexOf(rule),1);continue}rule.key="RollOption",rule.domain=match[1],rule.option=match[2],rule.toggleable=!0,delete rule.property,typeof rule.default=="boolean"&&(rule.value=rule.default,delete rule.default),sluggify(String(rule.label??""))===source.system.slug&&delete rule.label}}async updateActor(source){source.flags.pf2e?.rollOptions?.all&&(source.flags.pf2e.rollOptions.all["-=panache"]=!1,source.flags.pf2e.rollOptions.all["-=rage"]=!1,source.flags.pf2e.rollOptions.all["-=target:flatFooted"]=!1)}}class Migration732FixDedicationFeatTypes extends MigrationBase{static{__name(this,"Migration732FixDedicationFeatTypes")}static{__name2(this,"Migration732FixDedicationFeatTypes")}static version=.732;#hasWellFormedFeatType(system){return"featType"in system&&isObject(system.featType)&&"value"in system.featType&&typeof system.featType=="string"}async updateItem(source){if(source.type==="feat"){const system=source.system;if(!this.#hasWellFormedFeatType(system))system.featType={value:"bonus"};else{const{featType}=system;(featType.value==="dedication"||featType.value==="class"&&source.system.slug?.endsWith("-dedication"))&&(featType.value="archetype")}}}}class Migration733ItemBonusFromEquipment extends MigrationBase{static{__name(this,"Migration733ItemBonusFromEquipment")}static{__name2(this,"Migration733ItemBonusFromEquipment")}static version=.733;slugs=new Set(["animal-skin","stance-mountain-stance","spell-effect-mage-armor"]);async updateItem(source){const compendiumItem=this.slugs.has(source.system.slug??""),homebrewItem=!compendiumItem&&source.type==="feat";if(!(compendiumItem||homebrewItem))return;const rules=source.system.rules;for(const rule of rules)rule.key==="FlatModifier"&&rule.type==="item"&&(rule.fromEquipment=!1)}}class Migration734SpellLocationPropsAndSignature extends MigrationBase{static{__name(this,"Migration734SpellLocationPropsAndSignature")}static{__name2(this,"Migration734SpellLocationPropsAndSignature")}static version=.734;async updateActor(actor){const entries=actor.items.filter(item=>item.type==="spellcastingEntry"),spells=actor.items.filter(item=>item.type==="spell");for(const spellSource of spells){const spellData=spellSource.system,entrySource=entries.find(entry=>entry._id===spellData.location.value);if(!entrySource)continue;const entryData=entrySource.system;if(!entryData.signatureSpells)continue;entryData.signatureSpells.value.includes(spellSource._id??"")&&(spellData.location.signature=!0)}}async updateItem(source,actor){if(source.type==="spellcastingEntry"){const data=source.system;data.signatureSpells&&(delete data.signatureSpells,"game"in globalThis&&(data["-=signatureSpells"]=null))}if(source.type==="spell"){const data=source.system;(data.heightenedLevel||data.autoHeightenLevel)&&(actor&&(data.location.heightenedLevel=data.heightenedLevel?.value??void 0,data.location.autoHeightenLevel=data.autoHeightenLevel?.value??void 0),delete data.autoHeightenLevel,delete data.heightenedLevel,"game"in globalThis&&(data["-=autoHeightenLevel"]=null,data["-=heightenedLevel"]=null))}}}class Migration735FirearmAmmoAlchemical extends MigrationBase{static{__name(this,"Migration735FirearmAmmoAlchemical")}static{__name2(this,"Migration735FirearmAmmoAlchemical")}static version=.735;#needsTrait(source){return"consumableType"in source.system&&isObject$1(source.system.consumableType)&&source.system.consumableType.value==="ammo"&&!!source.system.stackGroup?.startsWith("rounds")&&source.system.slug!=="cutlery"&&!source.system.traits.value.includes("alchemical")}async updateItem(source){source.type==="consumable"&&this.#needsTrait(source)&&source.system.traits.value.unshift("alchemical")}}class Migration736RemoveBrokenThreshold extends MigrationBase{static{__name(this,"Migration736RemoveBrokenThreshold")}static{__name2(this,"Migration736RemoveBrokenThreshold")}static version=.736;#hasBrokenThreshold(source){return isPhysicalData(source)&&"brokenThreshold"in source.system}async updateItem(source){this.#hasBrokenThreshold(source)&&(delete source.system.brokenThreshold,source.system["-=brokenThreshold"]=null)}}class Migration737NormalizeRuleElementKeys extends Migration731TogglePropertyToRollOption{static{__name(this,"Migration737NormalizeRuleElementKeys")}static{__name2(this,"Migration737NormalizeRuleElementKeys")}static version=.737;async updateItem(source){const rules=source.system.rules;for(const rule of[...rules]){if(!isObject(rule)||typeof rule.key!="string"){rules.splice(rules.indexOf(rule),1);continue}rule.key=rule.key.trim().replace(/^PF2E\.RuleElement\./,"")}return super.updateItem(source)}}class Migration738UpdateLaughingShadow extends MigrationBase{static{__name(this,"Migration738UpdateLaughingShadow")}static{__name2(this,"Migration738UpdateLaughingShadow")}static version=.738;#shadowPromise=fromUuid("Compendium.pf2e.classfeatures.3gVDqDPSz4fB5T9G");#cascadePromise=fromUuid("Compendium.pf2e.feature-effects.fsjO5oTKttsbpaKl");async updateActor(source){const rollOptionsAll=source.flags.pf2e?.rollOptions?.all;rollOptionsAll instanceof Object&&"feature:laughing-shadow:damage"in rollOptionsAll&&(rollOptionsAll["-=feature:laughing-shadow:damage"]=!1)}async updateItem(source){if(source.type==="feat"&&source.system.slug==="laughing-shadow"){const laughingShadow=await this.#shadowPromise;if(!(laughingShadow instanceof ItemPF2e))return;source.system.rules=foundry.utils.deepClone(laughingShadow._source.system.rules)}else if(source.type==="effect"&&source.system.slug==="stance-arcane-cascade"){const arcaneCascade=await this.#cascadePromise;if(!(arcaneCascade instanceof ItemPF2e))return;const newRules=foundry.utils.deepClone(arcaneCascade._source.system.rules),withSelection=source.system.rules.find(r=>r.key==="ChoiceSet"&&typeof r.selection=="string");if(withSelection){const unselected=newRules.find(r=>r.key==="ChoiceSet");unselected&&(unselected.selection=withSelection.selection)}source.system.rules=newRules}}}class Migration739RecoveryCheckDC extends MigrationBase{static{__name(this,"Migration739RecoveryCheckDC")}static{__name2(this,"Migration739RecoveryCheckDC")}static version=.739;toughness=[{key:"FlatModifier",selector:"hp",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",path:"system.attributes.dying.recoveryDC",value:9}];defyDeath=[{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:8}];mountainsStoutness=[{key:"FlatModifier",selector:"hp",type:"untyped",value:"@actor.level"},{key:"ActiveEffectLike",mode:"downgrade",predicate:{not:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:9},{key:"ActiveEffectLike",mode:"downgrade",predicate:{all:["feat:toughness"]},path:"system.attributes.dying.recoveryDC",value:6}];async updateItem(source){if(source.type!=="feat")return;if(source.system.slug==="toughness"){source.system.rules=this.toughness;return}else if(source.system.slug==="defy-death"){source.system.rules=this.defyDeath;return}else if(source.system.slug==="mountains-stoutness"){source.system.rules=this.mountainsStoutness;return}const{rules}=source.system;for(const rule of[...rules])rule.key==="RecoveryCheckDC"&&source.system.rules.splice(rules.indexOf(rule),1)}}class Migration740MaxTakable extends MigrationBase{static{__name(this,"Migration740MaxTakable")}static{__name2(this,"Migration740MaxTakable")}static version=.74;async updateItem(source){if(source.type!=="feat")return;const systemData=source.system;"maxTaken"in systemData&&(typeof systemData.maxTaken=="number"&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=systemData.maxTaken),delete systemData.maxTaken,systemData["-=maxTaken"]=null),"maxTakable"in systemData&&typeof systemData.maxTakable!="number"&&(systemData.maxTakable=null)}}class Migration741RollOptionToggleToItem extends MigrationBase{static{__name(this,"Migration741RollOptionToggleToItem")}static{__name2(this,"Migration741RollOptionToggleToItem")}static version=.741;async updateActor(source){if(!(source.flags.pf2e?.rollOptions instanceof Object))return;const rules=source.items.flatMap(i=>i.system.rules).filter(r=>!!r.toggleable&&r.key==="RollOption"&&typeof r.domain=="string"&&r.domain.length>0&&typeof r.option=="string"&&r.option.length>0),{rollOptions}=source.flags.pf2e;for(const rule of rules){const domain=rollOptions[rule.domain];domain instanceof Object&&rule.option in domain&&(domain[`-=${rule.option}`]=!1,rule.value=!!domain[rule.option])}}}class Migration742RMAbilityBoostLevels extends MigrationBase{static{__name(this,"Migration742RMAbilityBoostLevels")}static{__name2(this,"Migration742RMAbilityBoostLevels")}static version=.742;async updateItem(source){if(source.type!=="class")return;const systemData=source.system;"abilityBoostLevels"in source.system&&(delete systemData.abilityBoostLevels,systemData["-=abilityBoostLevels"]=null)}}class Migration743FixWeaknessStructure extends MigrationBase{static{__name(this,"Migration743FixWeaknessStructure")}static{__name2(this,"Migration743FixWeaknessStructure")}static version=.743;async updateActor(source){if(source.type!=="character"&&source.type!=="npc")return;const traits=source.system.traits;Array.isArray(traits.dv)||(traits.dv=[]),Array.isArray(traits.dr)||(traits.dr=[])}}class Migration744MigrateSpellHeighten extends MigrationBase{static{__name(this,"Migration744MigrateSpellHeighten")}static{__name2(this,"Migration744MigrateSpellHeighten")}static version=.744;async updateItem(source){if(source.type!=="spell")return;const system=source.system;system.scaling&&(system.heightening={type:"interval",interval:system.scaling.interval,damage:system.scaling.damage},delete system.scaling,system["-=scaling"]=null)}}class Migration745EffectTargetToChoiceSet extends MigrationBase{static{__name(this,"Migration745EffectTargetToChoiceSet")}static{__name2(this,"Migration745EffectTargetToChoiceSet")}static version=.745;#isEffectTargetRE(rule){return rule.key==="EffectTarget"}#toChoiceSet(rule,itemSource,actorSource){const newRE={key:"ChoiceSet",choices:{ownedItems:!0,types:["weapon"]},prompt:"PF2E.SpecificRule.Prompt.Weapon"};if(typeof rule.targetId=="string"&&actorSource){const weapon=actorSource.items.find(i=>i.type==="weapon"&&i._id===rule.targetId);weapon&&(newRE.selection=weapon.system.slug??sluggify(weapon.name))}return itemSource.system.slug?.includes("blade-ally")?newRE.choices.includeHandwraps=!0:itemSource.system.slug?.includes("weapon-surge")?newRE.choices.predicate={all:["item:equipped"]}:itemSource.system.slug==="shillelagh"?(newRE.adjustName=!1,newRE.prompt="PF2E.SpecificRule.Prompt.Shillelagh",newRE.choices.predicate={all:["item:equipped"],any:["item:base:club","item:base:staff"]}):isObject$1(rule.predicate)&&(newRE.choices.predicate=foundry.utils.deepClone(rule.predicate)),newRE}async updateItem(source,actorSource){const{rules}=source.system;for(const rule of rules)if(this.#isEffectTargetRE(rule)){rules[rules.indexOf(rule)]=this.#toChoiceSet(rule,source,actorSource??null);const otherRules=rules.filter(r=>typeof r.selector=="string"&&/item\|data\.target/.test(r.selector));for(const other of otherRules){const flag=sluggify(source.system.slug??source.name,{camel:"dromedary"});other.selector=other.selector.replace(/\bdata\.target\b/,`flags.pf2e.rulesSelections.${flag}`)}}}}class Migration746StandardizePricing extends MigrationBase{static{__name(this,"Migration746StandardizePricing")}static{__name2(this,"Migration746StandardizePricing")}static version=.746;async updateItem(item){if(!(!isPhysicalData(item)&&item.type!=="kit"))if(isObject(item.system.price)||(item.system.price={value:CoinsPF2e.fromString(String(item.system.price)).toObject()}),item.type==="treasure"){const systemData=item.system;if(systemData.denomination||systemData.value){const value=systemData.value?.value??0,denomination=systemData.denomination?.value??"gp";systemData.price={value:{[denomination]:value}},systemData["-=denomination"]=null,delete systemData.denomination,systemData["-=value"]=null,delete systemData.value}}else isObject(item.system.price.value)||(item.system.price.value=CoinsPF2e.fromString(String(item.system.price.value)).toObject())}}class Migration747FixedHeightening extends MigrationBase{static{__name(this,"Migration747FixedHeightening")}static{__name2(this,"Migration747FixedHeightening")}static version=.747;async updateItem(item){if(item.type!=="spell")return;const isAcidSplash=(item.system.slug??sluggify(item.name))==="acid-splash";if(item.system.heightening?.type==="fixed"&&!isAcidSplash)return;const sourceId=item.flags.core?.sourceId;if(sourceId&&this.fixedHeightenSpells.has(sourceId)){const spell=(await this.loadSpells())[sourceId];spell&&spell.system.heightening?.type==="fixed"&&(item.system.heightening=spell.system.heightening,this.overwriteDamage(item,spell))}}overwriteDamage(spell,newSpell){const newDamage=newSpell.system.damage,newKeys=new Set(Object.keys(newDamage.value)),diff=Object.keys(spell.system.damage.value).filter(key=>!newKeys.has(key)),damage=spell.system.damage;damage.value=newDamage.value;for(const deleteKey of diff)isObject(damage.value)&&(damage.value[`-=${deleteKey}`]=null)}#loadedSpells;async loadSpells(){if(this.#loadedSpells)return this.#loadedSpells;const spells=await UUIDUtils.fromUUIDs([...this.fixedHeightenSpells]);return this.#loadedSpells=spells.reduce((record,spell)=>({...record,[spell.uuid]:spell}),{}),this.#loadedSpells}fixedHeightenSpells=new Set(["Compendium.pf2e.spells-srd.0fKHBh5goe2eiFYL","Compendium.pf2e.spells-srd.10VcmSYNBrvBphu1","Compendium.pf2e.spells-srd.2gQYrCPwBmwau26O","Compendium.pf2e.spells-srd.2iQKhCQBijhj5Rf3","Compendium.pf2e.spells-srd.4koZzrnMXhhosn0D","Compendium.pf2e.spells-srd.5WM3WjshXgrkVCg6","Compendium.pf2e.spells-srd.7CUgqHunmHfW2lC5","Compendium.pf2e.spells-srd.7OFKYR1VY6EXDuiR","Compendium.pf2e.spells-srd.9s5tqqXNzcoKamWx","Compendium.pf2e.spells-srd.BCuHKrDeJ4eq53M6","Compendium.pf2e.spells-srd.CxpFy4HJHf4ACbxF","Compendium.pf2e.spells-srd.D2nPKbIS67m9199U","Compendium.pf2e.spells-srd.DCQHaLrYXMI37dvW","Compendium.pf2e.spells-srd.DgcSiOCR1uDXGaEA","Compendium.pf2e.spells-srd.EfFMLVbmkBWmzoLF","Compendium.pf2e.spells-srd.Et8RSCLx8w7uOLvo","Compendium.pf2e.spells-srd.F23T5tHPo3WsFiHW","Compendium.pf2e.spells-srd.FhOaQDTSnsY7tiam","Compendium.pf2e.spells-srd.Fr58LDSrbndgld9n","Compendium.pf2e.spells-srd.GaRQlC9Yw1BGKHfN","Compendium.pf2e.spells-srd.HGmBY8KjgLV97nUp","Compendium.pf2e.spells-srd.HHGUBGle4OjoxvNR","Compendium.pf2e.spells-srd.HTou8cG05yuSkesj","Compendium.pf2e.spells-srd.HWrNMQENi9WSGbnF","Compendium.pf2e.spells-srd.HcIAQZjNXHemoXSU","Compendium.pf2e.spells-srd.Ifc2b6bNVdjKV7Si","Compendium.pf2e.spells-srd.JHntYF0SbaWKq7wR","Compendium.pf2e.spells-srd.LQzlKbYjZSMFQawP","Compendium.pf2e.spells-srd.LiGbewa9pO0yjbsY","Compendium.pf2e.spells-srd.Llx0xKvtu8S4z6TI","Compendium.pf2e.spells-srd.Mkbq9xlAUxHUHyR2","Compendium.pf2e.spells-srd.OAt2ZEns1gIOCgrn","Compendium.pf2e.spells-srd.OhD2Z6rIGGD5ocZA","Compendium.pf2e.spells-srd.PRrZ7anETWPm90YY","Compendium.pf2e.spells-srd.PjhUmyKnq6K5uDby","Compendium.pf2e.spells-srd.Popa5umI3H33levx","Compendium.pf2e.spells-srd.Pwq6T7xpfAJXV5aj","Compendium.pf2e.spells-srd.Q7QQ91vQtyi1Ux36","Compendium.pf2e.spells-srd.Seaah9amXg70RKw2","Compendium.pf2e.spells-srd.U58aQWJ47VrI36yP","Compendium.pf2e.spells-srd.UmXhuKrYZR3W16mQ","Compendium.pf2e.spells-srd.VTb0yI6P1bLkzuRr","Compendium.pf2e.spells-srd.VlNcjmYyu95vOUe8","Compendium.pf2e.spells-srd.W02bHXylIpoXbO4e","Compendium.pf2e.spells-srd.WsUwpfmhKrKwoIe3","Compendium.pf2e.spells-srd.Wt94cw03L77sbud7","Compendium.pf2e.spells-srd.XhgMx9WC6NfXd9RP","Compendium.pf2e.spells-srd.ZAX0OOcKtYMQlquR","Compendium.pf2e.spells-srd.ZqmP9gijBmK7y8Xy","Compendium.pf2e.spells-srd.aIHY2DArKFweIrpf","Compendium.pf2e.spells-srd.atlgGNI1E1Ox3O3a","Compendium.pf2e.spells-srd.bay4AfSu2iIozNNW","Compendium.pf2e.spells-srd.czO0wbT1i320gcu9","Compendium.pf2e.spells-srd.dINQzhqGmIsqGMUY","Compendium.pf2e.spells-srd.drmvQJETA3WZzXyw","Compendium.pf2e.spells-srd.e36Z2t6tLdW3RUzZ","Compendium.pf2e.spells-srd.fprqWKUc0jnMIyGU","Compendium.pf2e.spells-srd.gISYsBFby1TiXfBt","Compendium.pf2e.spells-srd.ivKnEtI1z4UqEKIA","Compendium.pf2e.spells-srd.kuoYff1csM5eAcAP","Compendium.pf2e.spells-srd.lbrWMnS2pecKaSVB","Compendium.pf2e.spells-srd.lsR3RLEdBG4rcSzd","Compendium.pf2e.spells-srd.nXmC2Xx9WmS5NsAo","Compendium.pf2e.spells-srd.o6YCGx4lycsYpww4","Compendium.pf2e.spells-srd.pZTqGY1MLRjgKasV","Compendium.pf2e.spells-srd.pt3gEnzA159uHcJC","Compendium.pf2e.spells-srd.pwzdSlJgYqN7bs2w","Compendium.pf2e.spells-srd.q5qmNn144ZJGxnvJ","Compendium.pf2e.spells-srd.qTr2oCgIXl703Whb","Compendium.pf2e.spells-srd.qwlh6aDgi86U3Q7H","Compendium.pf2e.spells-srd.r4HLQcYwB62bTayl","Compendium.pf2e.spells-srd.sFwoKj0TsacsmoWj","Compendium.pf2e.spells-srd.vLA0q0WOK2YPuJs6","Compendium.pf2e.spells-srd.vLzFcIaSXs7YTIqJ","Compendium.pf2e.spells-srd.vTQvfYu2llKQedmY","Compendium.pf2e.spells-srd.vctIUOOgSmxAF0KG","Compendium.pf2e.spells-srd.wzctak6BxOW8xvFV","Compendium.pf2e.spells-srd.x5rGOmhDRDVQPrnW","Compendium.pf2e.spells-srd.x7SPrsRxGb2Vy2nu","Compendium.pf2e.spells-srd.x9RIFhquazom4p02","Compendium.pf2e.spells-srd.xRgU9rrhmGAgG4Rc","Compendium.pf2e.spells-srd.yH13KXUK2x093NUv","Compendium.pf2e.spells-srd.yM3KTTSAIHhyuP14","Compendium.pf2e.spells-srd.zlnXpME1T2uvn8Lr","Compendium.pf2e.spells-srd.zul5cBTfr7NXHBZf"])}class Migration748BatchConsumablePricing extends MigrationBase{static{__name(this,"Migration748BatchConsumablePricing")}static{__name2(this,"Migration748BatchConsumablePricing")}static version=.748;async updateItem(item){if(!isPhysicalData(item))return;const slug=item.system.slug??sluggify(item.name);batched_5.has(slug)&&(item.system.price.per=5),batched_10.has(slug)&&(item.system.price.per=10)}}const batched_5=new Set(["rounds-harmona-gun","rounds-dwarven-scattergun","rounds-flingflenser","rounds-explosive-dogslicer"]),batched_10=new Set(["rounds-three-peaked-tree","rounds-dragon-mouth-pistol","rounds-pepperbox","rounds-fire-lance","rounds-flintlock-pistol","rounds-clan-pistol","bolts","rounds-hand-cannon","sun-shot","rounds-dagger-pistol","rounds-dueling-pistol","rounds-flintlock-musket","rounds-hammer-gun","rounds-black-powder-knuckle-dusters","rounds-slide-pistol","sling-bullets","rounds-double-barreled-musket","rounds-mace-multipistol","rounds-gnome-amalgam-musket","cutlery","rounds-axe-musket","rounds-mithral-tree","wooden-taws","rounds-gun-sword","rounds-blunderbuss","rounds-jezail","rounds-double-barreled-pistol","rounds-arquebus","rounds-cane-pistol","rounds-rapier-pistol","rounds-coat-pistol","rounds-piercing-wind","blowgun-darts","arrows","light-writer-plates","practice-target"]);class Migration749AssuranceREs extends MigrationBase{static{__name(this,"Migration749AssuranceREs")}static{__name2(this,"Migration749AssuranceREs")}static version=.749;#isChoiceSetWithSelection(rule){return rule.key==="ChoiceSet"}#newRules(skill){const selector=skill==="choice"?"{item|flags.pf2e.rulesSelections.assurance}":skill;return[{key:"SubstituteRoll",label:"PF2E.SpecificRule.SubstituteRoll.Assurance",selector,slug:"assurance",value:10},{key:"AdjustModifier",predicate:{all:["substitute:assurance"],not:["bonus:type:proficiency"]},selector,suppress:!0}]}async updateItem(source){const{slug,rules}=source.system;if(!(source.type==="feat"&&slug?.startsWith("assurance")))return;const firstRule=rules.at(0);if(slug==="assurance"&&firstRule&&rules.length===1&&this.#isChoiceSetWithSelection(firstRule))firstRule.flag="assurance",rules.push(...this.#newRules("choice"));else if(rules.length===0){const skill=/^assurance-([a-z]+)$/.exec(slug)?.at(1);setHasElement(SKILL_LONG_FORMS,skill)&&rules.push(...this.#newRules(skill))}}}class Migration750FixCorruptedPrice extends MigrationBase{static{__name(this,"Migration750FixCorruptedPrice")}static{__name2(this,"Migration750FixCorruptedPrice")}static version=.75;async updateItem(item){!isPhysicalData(item)&&item.type!=="kit"||typeof item.system.price=="string"&&(item.system.price={value:CoinsPF2e.fromString(item.system.price).toObject()})}}class Migration751ResetRollOptions extends MigrationBase{static{__name(this,"Migration751ResetRollOptions")}static{__name2(this,"Migration751ResetRollOptions")}static version=.751;async updateActor(source){isObject(source.flags.pf2e)&&"rollOptions"in source.flags.pf2e&&(source.flags.pf2e["-=rollOptions"]=null)}}class Migration752StrikeVsWeaponTraits extends MigrationBase{static{__name(this,"Migration752StrikeVsWeaponTraits")}static{__name2(this,"Migration752StrikeVsWeaponTraits")}static version=.752;#toSkip=new Set(["ghost-hunter","stance-arcane-cascade","spirit-strikes"]);async updateItem(source){if(this.#toSkip.has(source.system.slug??""))return;const rules=source.system.rules.filter(r=>r.key==="AdjustStrike"&&r.property==="traits");for(const rule of rules)objectHasKey(weaponTraits,rule.value)&&(rule.property="weapon-traits")}}class Migration753WeaponReloadTimes extends MigrationBase{static{__name(this,"Migration753WeaponReloadTimes")}static{__name2(this,"Migration753WeaponReloadTimes")}static version=.753;#hasThrownTrait(source){return source.system.traits.value.some(t=>t.startsWith("thrown"))}async updateItem(source){if(source.type!=="weapon")return;const slug=source.system.slug??"";["backpack-catapult","backpack-catapult"].includes(slug)?source.system.reload.value="10":(source.system.baseItem==="alchemical-bomb"||this.#hasThrownTrait(source))&&(source.system.reload.value="-")}}class Migration754MightyBulwarkAdjustModifiers extends MigrationBase{static{__name(this,"Migration754MightyBulwarkAdjustModifiers")}static{__name2(this,"Migration754MightyBulwarkAdjustModifiers")}static version=.754;async updateItem(source){if(!(source.type==="feat"&&source.system.slug==="mighty-bulwark"))return;const newRules=[{key:"FlatModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",type:"untyped",value:4},{key:"AdjustModifier",predicate:{all:["self:armor:trait:bulwark"]},selector:"reflex",slug:"dex",suppress:!0},{key:"AdjustModifier",selector:"reflex",slug:"bulwark",suppress:!0}];source.system.rules=newRules}}class Migration755GrantIdsToData extends MigrationBase{static{__name(this,"Migration755GrantIdsToData")}static{__name2(this,"Migration755GrantIdsToData")}static version=.755;async updateActor(source){for(const item of source.items){if(!item.flags.pf2e)continue;const systemFlags=item.flags.pf2e,{grantedBy,itemGrants}=systemFlags;typeof grantedBy=="string"&&(source.items.find(i=>i._id===grantedBy)?systemFlags.grantedBy={id:grantedBy}:systemFlags["-=grantedBy"]=null),Array.isArray(itemGrants)&&(systemFlags.itemGrants=itemGrants.flatMap(grant=>typeof grant=="string"?source.items.find(i=>i._id===grant)?{id:grant}:[]:grant))}}}class Migration756RMStoredResourceMaxes extends MigrationBase{static{__name(this,"Migration756RMStoredResourceMaxes")}static{__name2(this,"Migration756RMStoredResourceMaxes")}static version=.756;async updateActor(source){source.type==="character"&&(source["system.resources.focus.-=max"]=null,source["system.resources.crafting.infusedReagents.-=max"]=null,source["system.resources.-=investiture"]=null)}}class Migration757HillockHalfling extends MigrationBase{static{__name(this,"Migration757HillockHalfling")}static{__name2(this,"Migration757HillockHalfling")}static version=.757;async updateItem(itemSource){if(itemSource.type!=="heritage"||(itemSource.system.slug??sluggify(itemSource.name))!=="hillock-halfling")return;const rules=itemSource.system.rules;if(!rules.some(rule=>"path"in rule&&rule.path==="system.attributes.hp.recoveryAddend")){const element={key:"ActiveEffectLike",mode:"add",path:"system.attributes.hp.recoveryAddend",value:"@actor.level"};rules.push(element)}}}class Migration758PrunePCAttributes extends MigrationBase{static{__name(this,"Migration758PrunePCAttributes")}static{__name2(this,"Migration758PrunePCAttributes")}static version=.758;toDelete=["-=ac","-=ancestryhp","-=battleForm","-=classDC","-=classOrSpellDC","-=classhp","-=dexCap","-=doomed","-=dying","-=familiarAbilities","-=flanking","-=flatbonushp","-=flatbonussp","-=handsFree","-=hardness","hp.-=breakdown","hp.-=details","hp.-=max","hp.-=name","hp.-=negativeHealing","hp.-=recoveryMultiplier","hp.-=totalModifier","hp.-=tempsource","hp.-=_modifiers","initiative.-=_modifiers","initiative.-=breakdown","initiative.-=label","initiative.-=name","initiative.-=roll","initiative.-=tiebreakPriority","initiative.-=totalModifier","-=levelbonushp","-=levelbonussp","-=perception","-=polymorphed","-=reach","-=shield","speed.-=_modifiers","speed.-=breakdown","speed.-=name","speed.-=total","speed.-=totalModifier","speed.-=type","-=spellDC","-=wounded"];async updateActor(source){if(source.type==="character")for(const key of this.toDelete)source[`system.attributes.${key}`]=null}}class Migration759CritSpecRE extends MigrationBase{static{__name(this,"Migration759CritSpecRE")}static{__name2(this,"Migration759CritSpecRE")}static version=.759;async updateItem(source){if(!["feat","weapon"].includes(source.type))return;const critSpecKey="CriticalSpecialization";if(!source.system.rules.some(r=>r.key===critSpecKey))switch(source.system.slug){case"archer-dedication":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:group:bow",{gte:["weapon:proficiency:rank",2]}]}});return}case"azarketi-weapon-aptitude":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:trait:azarketi","weapon:base:crossbow","weapon:base:hand-crossbow","weapon:base:longspear","weapon:base:spear","weapon:base:trident"]}}];return}case"brawling-focus":{source.system.rules=[{key:critSpecKey,predicate:{any:["weapon:group:brawling",{and:["feat:monastic-weaponry","weapon:trait:monk",{not:"weapon:category:unarmed"},{gte:["weapon:proficiency:rank",1]}]}]}}];return}case"brutality":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["self:effect:rage","weapon:melee"]}});return}case"catfolk-weapon-rake":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:catfolk","weapon:base:hatchet","weapon:base:kama","weapon:base:kukri","weapon:base:scimitar","weapon:base:sickle"]}}];return}case"conrasu-weapon-understanding":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:conrasu","weapon:base:glaive","weapon:base:longspear","weapon:base:longsword","weapon:base:shortbow","weapon:base:spear"]}}];return}case"dwarven-weapon-cunning":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:dwarf","weapon:base:battle-axe","weapon:base:pick","weapon:base:warhammer"]}}];return}case"elven-weapon-elegance":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:elf","weapon:base:longbow","weapon:base:longsword","weapon:base:rapier","weapon:base:shortbow"]}}];return}case"fighter-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",3]}]}});return}case"genie-weapon-flourish":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:geniekin","weapon:base:falchion","weapon:base:ranseur","weapon:base:scimitar","weapon:base:trident"]}}];return}case"gnoll-weapon-practicality":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnoll","weapon:base:flail","weapon:base:khopesh","weapon:base:mambele","weapon:base:spear","weapon:base:war-flail"]}}];return}case"gnome-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:gnome","weapon:base:glaive","weapon:base:kukri"]}}];return}case"goblin-weapon-frenzy":{source.system.rules=[{key:"CriticalSpecialization",predicate:{all:["weapon:trait:goblin"]}}];return}case"grippli-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:grippli","weapon:base:blowgun","weapon:base:hatchet","weapon:base:scythe","weapon:base:shortbow"]}}];return}case"gunslinger-weapon-mastery":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{any:["weapon:group:firearm","weapon:tag:crossbow"]}});return}case"halfling-weapon-trickster":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:halfling","weapon:base:shortsword","weapon:base:sling"]}}];return}case"hobgoblin-weapon-discipline":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:group:polearm","weapon:group:spear","weapon:group:sword"]}}];return}case"improvised-critical":{source.system.rules=[{key:critSpecKey,predicate:{all:["weapon:tag:improvised"]}}];return}case"kobold-weapon-innovator":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:kobold","weapon:base:crossbow","weapon:base:greatpick","weapon:base:light-pick","weapon:base:pick","weapon:base:spear"]}}];return}case"mauler-dedication":{source.system.rules.push({key:"CriticalSpecialization",predicate:{all:["weapon:melee",{or:["weapon:category:simple","weapon:category:martial"]},{or:["weapon:usage:hands:2","weapon:trait:two-hand-d6","weapon:trait:two-hand-d8","weapon:trait:two-hand-d10","weapon:trait:two-hand-d12"]}]}});return}case"orc-weapon-carnage":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:trait:orc","weapon:base:falchion","weapon:base:greataxe"]}}];return}case"ranger-weapon-expertise":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["hunted-prey"],any:["weapon:category:simple","weapon:category:martial"]}});return}case"spike-launcher":{const rule={key:critSpecKey,alternate:!0,predicate:{all:["weapon:id:{item|_id}"]},text:"PF2E.Item.Weapon.CriticalSpecialization.bow"};source.system.rules.push(rule);return}case"student-of-the-staff":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.unshift({key:critSpecKey,predicate:{all:["weapon:base:staff"]}});return}case"sun-sling":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:id:{item|_id}","feat:suns-fury"]}});return}case"suns-fury":{source.system.rules=[];return}case"third-doctrine-warpriest":{source.system.rules.push({key:critSpecKey,predicate:{all:["weapon:deity-favored"]}});return}case"vanths-weapon-execution":{source.system.rules=[{key:"CriticalSpecialization",predicate:{any:["weapon:base:bo-staff","weapon:base:longbow","weapon:base:scythe","weapon:base:staff"]}}];return}case"weapon-expertise-swashbuckler":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:[{gte:["weapon:proficiency:rank",2]}]}});return}case"weapon-tricks":{source.system.rules=source.system.rules.filter(r=>r.key!=="Note"),source.system.rules.push({key:critSpecKey,predicate:{all:["target:condition:flat-footed"],any:[{and:[{or:["weapon:trait:agile","weapon:trait:finesse"]},{or:["weapon:category:simple","weapon:category:unarmed"]}]},"weapon:base:rapier","weapon:base:sap","weapon:base:shortbow","weapon:base:shortsword"]}});return}}}}class Migration760SeparateNoteTitle extends MigrationBase{static{__name(this,"Migration760SeparateNoteTitle")}static{__name2(this,"Migration760SeparateNoteTitle")}static version=.76;#cleanText(text){return text.replace(/^@Localize\[(.+)\]$/,"$1").replace(/^PF2E\.WeaponDescription([A-Z][a-z]+)$/,(substring,group)=>typeof group=="string"?`PF2E.Item.Weapon.CriticalSpecialization.${group.toLowerCase()}`:substring)}async updateItem(source){const notes=source.system.rules.filter(r=>r.key==="Note"&&typeof r.text=="string"&&!("title"in r));for(const note of notes){if(note.text=note.text.trim(),!note.text.startsWith("<p"))continue;const pElement=(()=>{const text=note.text.includes("</p>")?note.text:`${note.text}</p>`;try{const fragment=document.createElement("template");fragment.innerHTML=text;const children2=Array.from(fragment.content.childNodes);if(children2.length===1&&children2[0]instanceof HTMLElement)return children2[0];if(children2.length===2&&children2[0]instanceof HTMLParagraphElement&&children2[1]instanceof Text){const[first,second]=children2;return first.append(second),first}else return null}catch{return null}})();if(pElement?.nodeName!=="P")continue;const children=Array.from(pElement.childNodes);if(children.length===1&&children[0]instanceof Text){note.text=this.#cleanText(children[0].textContent??""),pElement.dataset.visibility&&["gm","owner"].includes(pElement.dataset.visibility)&&(note.visibility=pElement.dataset.visibility);continue}if(children.length!==2||!(children[0]instanceof HTMLElement)||children[0].nodeName!=="STRONG"||!(children[1]instanceof Text))continue;const strongElement=children[0];strongElement.remove();const newText=pElement.innerHTML.trim();if(newText===""||note.text.includes("<span"))continue;const newTitle=strongElement.innerHTML.trim();newTitle===source.name?note.title="{item|name}":newTitle==="Critical Specialization"?note.title="PF2E.Actor.Creature.CriticalSpecialization":newTitle==="Effect"?note.title="TYPES.Item.effect":note.title=newTitle,note.text=this.#cleanText(newText),pElement.dataset.visibility&&(note.visibility=pElement.dataset.visibility)}}}class Migration761ShotRules extends MigrationBase{static{__name(this,"Migration761ShotRules")}static{__name2(this,"Migration761ShotRules")}static version=.761;async updateItem(source){switch(source.type){case"effect":this.#updateEffect(source);break;case"feat":this.#updateFeat(source);break}}#updateEffect(source){if(source.system.slug==="stance-multishot-stance"){const newRules=[{key:"AdjustModifier",mode:"add",predicate:{all:["double-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1},{key:"AdjustModifier",mode:"add",predicate:{all:["triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:1}];source.system.rules=newRules}}#updateFeat(source){switch(source.system.slug){case"double-shot":{const newRules=[{domain:"ranged-attack-roll",key:"RollOption",option:"double-shot",toggleable:!0},{key:"FlatModifier",predicate:{all:["double-shot","weapon:reload:0"]},selector:"ranged-attack-roll",slug:"double-shot",value:-2}];source.system.rules=newRules;break}case"triple-shot":{const newRules=[{domain:"ranged-attack-roll",disabledIf:{not:["double-shot"]},key:"RollOption",option:"triple-shot",priority:51,toggleable:!0},{key:"AdjustModifier",mode:"override",predicate:{all:["double-shot","triple-shot"]},relabel:"{item|name}",selector:"ranged-attack-roll",slug:"double-shot",value:-4}];source.system.rules=newRules;break}}}}class Migration762UpdateBackgroundItems extends MigrationBase{static{__name(this,"Migration762UpdateBackgroundItems")}static{__name2(this,"Migration762UpdateBackgroundItems")}static version=.762;async updateItem(source){source.type==="background"&&(source.system.slug==="amnesiac"||source.system.slug==="discarded-duplicate")&&Object.values(source.system.boosts).length!==3&&(source.system.boosts[2]={value:["cha","con","dex","int","str","wis"],selected:null})}}class Migration763RestoreAnimalStrikeOptions extends MigrationBase{static{__name(this,"Migration763RestoreAnimalStrikeOptions")}static{__name2(this,"Migration763RestoreAnimalStrikeOptions")}static version=.763;async updateItem(source){if(source.type!=="feat"||!/^[a-z]+-animal-instinct$/.test(source.system.slug??""))return;const strikeRE=source.system.rules.find(r=>r.key==="Strike"&&!Array.isArray(r.options));strikeRE&&(strikeRE.options=["animal-instinct"])}}class Migration764PanacheVivaciousREs extends MigrationBase{static{__name(this,"Migration764PanacheVivaciousREs")}static{__name2(this,"Migration764PanacheVivaciousREs")}static version=.764;async updateItem(source){source.type==="feat"&&(source.system.slug==="panache"?source.system.rules=[]:source.system.slug==="vivacious-speed"&&(source.system.rules=this.#vivaciousRules))}get#vivaciousRules(){return[{key:"FlatModifier",predicate:{all:["self:effect:panache"]},selector:"speed",slug:"vivacious-full",type:"status",value:{brackets:[{end:2,value:5},{end:6,start:3,value:10},{end:10,start:7,value:15},{end:14,start:11,value:20},{end:18,start:15,value:25},{start:19,value:30}]}},{key:"FlatModifier",predicate:{not:["self:effect:panache"]},selector:"speed",slug:"vivacious-half",type:"status",value:{brackets:[{end:10,start:3,value:5},{end:18,start:11,value:10},{start:19,value:15}]}}]}}class Migration765ChoiceOwnedItemTypes extends MigrationBase{static{__name(this,"Migration765ChoiceOwnedItemTypes")}static{__name2(this,"Migration765ChoiceOwnedItemTypes")}static version=.765;async updateItem(source){for(const rule of source.system.rules)rule.key==="ChoiceSet"&&"choices"in rule&&isObject(rule.choices)&&rule.choices.ownedItems&&!rule.choices.types&&(rule.choices.types=["weapon"])}}class Migration766WipeURLSources extends MigrationBase{static{__name(this,"Migration766WipeURLSources")}static{__name2(this,"Migration766WipeURLSources")}static version=.766;async updateItem(source){(!("game"in globalThis)||source.flags.core?.sourceId?.startsWith("Compendium.pf2e."))&&"source"in source.system&&isObject(source.system.source)&&typeof source.system.source.value=="string"&&source.system.source.value.startsWith("http")&&(source.system.source.value="")}}class Migration767ConvertVoluntaryFlaws extends MigrationBase{static{__name(this,"Migration767ConvertVoluntaryFlaws")}static{__name2(this,"Migration767ConvertVoluntaryFlaws")}static version=.767;async updateItem(source){if(source.type!=="ancestry")return;const system=source.system,oldFlaws=Object.values(system.voluntaryFlaws??{}).map(b=>b.selected).filter(a=>!!a),oldBoosts=Object.values(system.voluntaryBoosts??{}).map(b=>b.selected).filter(a=>!!a);(oldBoosts.length||oldFlaws.length)&&(system.voluntary={boost:oldBoosts.at(0)||null,flaws:oldFlaws}),system.voluntaryBoosts&&(delete system.voluntaryBoosts,delete system["-=voluntaryBoosts"]),system.voluntaryFlaws&&(delete system.voluntaryFlaws,delete system.voluntaryFlaws)}}class Migration768AddNewAuras extends MigrationBase{static{__name(this,"Migration768AddNewAuras")}static{__name2(this,"Migration768AddNewAuras")}static version=.768;#auraOfLife={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.FPuICuxBLiDaEbDX"}],key:"Aura",radius:15,slug:"aura-of-life"};#enlightenedPresence={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.XM1AA8z5cHm8sJXM"}],key:"Aura",radius:15,slug:"enlightened-presence",traits:["emotion","mental"]};#eternalBlessing=[{domain:"all",key:"RollOption",option:"eternal-blessing-active",toggleable:!0,value:!0},{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.spell-effects.Gqy7K6FnbLtwGpud"}],key:"Aura",predicate:{all:["eternal-blessing-active"]},radius:15,slug:"eternal-blessing",traits:["enchantment","mental"]}];#marshalsAura={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.Ru4BNABCZ0hUbX7S"}],key:"Aura",radius:10,slug:"marshals-aura",traits:["emotion","mental","visual"]};async updateItem(source){if(!(source.type!=="feat"||source.system.rules.length>0))switch(source.system.slug){case"aura-of-life":source.system.rules=[foundry.utils.deepClone(this.#auraOfLife)];break;case"enlightened-presence":source.system.rules=[foundry.utils.deepClone(this.#enlightenedPresence)];break;case"eternal-blessing":source.system.rules=foundry.utils.deepClone(this.#eternalBlessing);break;case"marshal-dedication":source.system.rules=[foundry.utils.deepClone(this.#marshalsAura)];break}}}class Migration769NoUniversalistFocusPool extends MigrationBase{static{__name(this,"Migration769NoUniversalistFocusPool")}static{__name2(this,"Migration769NoUniversalistFocusPool")}static version=.769;async updateItem(source){if(source.type==="feat"&&source.system.slug==="arcane-school"){const rule=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="system.resources.focus.max");rule&&(rule.predicate={not:["feature:universalist"]})}}}class Migration770REDataToSystem extends MigrationBase{static{__name(this,"Migration770REDataToSystem")}static{__name2(this,"Migration770REDataToSystem")}static version=.77;async updateActor(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(actor|item)\.data\.data./g,"@$1.system.").replace(/@(actor|item)\.data./g,"@$1."))}async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/^data\.data\./,"system.").replace(/^data\./,"system.").replace(/"data\.data\./g,'"system.').replace(/"data\./g,'"system.').replace(/@(actor|item)\.data\.data./g,"@$1.system.").replace(/@(actor|item)\.data./g,"@$1.").replace(/\b(actor|item|rule)\|data\.data\./g,"$1|system.").replace(/\b(actor|item|rule)\|data\./g,"$1|system."))}}class Migration771SpellVariantsToSystem extends MigrationBase{static{__name(this,"Migration771SpellVariantsToSystem")}static{__name2(this,"Migration771SpellVariantsToSystem")}static version=.771;async updateItem(source){if(source.type==="spell"){for(const overlayData of Object.values(source.system.overlays??{}))if(overlayData.overlayType==="override"){const maybeWithData=overlayData;maybeWithData.data&&(delete Object.assign(maybeWithData,{system:maybeWithData.data}).data,maybeWithData["-=data"]=null)}}}}class Migration772V10EmbeddedSpellData extends MigrationBase{static{__name(this,"Migration772V10EmbeddedSpellData")}static{__name2(this,"Migration772V10EmbeddedSpellData")}static version=.772;async preUpdateItem(source){if(source.type==="consumable"&&source.system.spell){const embeddedSpell=source.system.spell;embeddedSpell.data?.data?(source.system.spell=embeddedSpell.data,source.system.spell.system=embeddedSpell.data.data,source.system.spell.system.location.heightenedLevel=Number(embeddedSpell.data.heightenedLevel)||source.system.spell.system.level.value,embeddedSpell.data["-=data"]=null,delete embeddedSpell.data.data):embeddedSpell.data?.system?(source.system.spell=embeddedSpell.data,source.system.spell.system.location.heightenedLevel=Number(embeddedSpell.data.heightenedLevel)||source.system.spell.system.level.value):embeddedSpell.data===null&&(source.system.spell=null)}}}class Migration773ReligiousSymbolUsage extends MigrationBase{static{__name(this,"Migration773ReligiousSymbolUsage")}static{__name2(this,"Migration773ReligiousSymbolUsage")}static version=.773;async updateItem(source){source.type==="equipment"&&source.system.slug?.startsWith("religious-symbol")&&(source.system.usage.value="held-in-one-hand")}}class Migration774UnpersistCraftingEntries extends MigrationBase{static{__name(this,"Migration774UnpersistCraftingEntries")}static{__name2(this,"Migration774UnpersistCraftingEntries")}static version=.774;munitionsCrafterPredicate={all:["item:trait:alchemical"],any:["item:trait:bomb","item:subtype:ammo"]};async updateActor(source){if(source.type==="character"){const craftingData=source.system.crafting??{},craftingEntries=craftingData.entries??{},rules=source.items.flatMap(i=>i.system.rules);for(const rule of rules)rule.key!=="CraftingEntry"||typeof rule.selector!="string"||rule.selector.length===0||!rule.requiredTraits||(rule.preparedFormulas=craftingEntries[rule.selector]?.actorPreparedFormulas??[]);delete craftingData.entries,craftingData["-=entries"]=null}}async updateItem(source){const rules=source.system.rules,craftingEntryRules=rules.filter(r=>r.key==="CraftingEntry"&&Array.isArray(r.requiredTraits)),newCraftingEntryRules=craftingEntryRules.map(craftingEntryRule=>(craftingEntryRule.craftableItems=craftingEntryRule.selector==="munitionsCrafter"?this.munitionsCrafterPredicate:this.generatePredicateFromRequiredTraits(craftingEntryRule.requiredTraits||[]),delete craftingEntryRule.requiredTraits,craftingEntryRule));for(const craftingEntryRule of craftingEntryRules){const index=rules.indexOf(craftingEntryRule);rules.splice(index,1,newCraftingEntryRules.shift()),delete craftingEntryRule.requiredTraits}const craftingEntryAELikes=rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&r.path.startsWith("system.crafting.entries.")),newCraftingEntryAELikes=craftingEntryAELikes.map(craftingEntryAELike=>(craftingEntryAELike.phase="beforeDerived",craftingEntryAELike));for(const craftingEntryAELike of craftingEntryAELikes){const index=rules.indexOf(craftingEntryAELike);rules.splice(index,1,newCraftingEntryAELikes.shift())}}generatePredicateFromRequiredTraits(requiredTraits){return requiredTraits.length===1?{all:requiredTraits[0].map(trait=>`item:trait:${trait}`)}:{any:requiredTraits.map(traits=>({and:traits.map(trait=>`item:trait:${trait}`)}))}}}class Migration775AgileFinesseRanged extends MigrationBase{static{__name(this,"Migration775AgileFinesseRanged")}static{__name2(this,"Migration775AgileFinesseRanged")}static version=.775;#findDamageDiceRE(source){return source.system.rules.find(r=>r.key==="DamageDice")??null}#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateItem(source){switch(source.type){case"action":{if(source.system.slug==="sneak-attack"){const damageDiceRE=this.#findDamageDiceRE(source);isObject(damageDiceRE)&&damageDiceRE.predicate&&Array.isArray(damageDiceRE.predicate.all)&&damageDiceRE.predicate.all.some(s=>s instanceof Object&&"or"in s)&&(damageDiceRE.predicate=this.#sneakAttackPredicate)}break}case"feat":switch(source.system.slug){case"athletic-strategist":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=this.#athleticStrategist);break}case"devise-a-stratagem":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=this.#deviseAStratagem);break}case"ruffian":{const damageDiceRE=this.#findDamageDiceRE(source);damageDiceRE&&(damageDiceRE.predicate=this.#ruffianPredicate);break}case"shadow-sneak-attack":case"sneak-attack":case"sneak-attacker":{const damageDiceRE=this.#findDamageDiceRE(source);if(damageDiceRE){const predicate=this.#sneakAttackPredicate;this.#isClassFeature(source)&&predicate.all?.unshift("class:rogue"),damageDiceRE.predicate=predicate}break}}}}get#athleticStrategist(){return{ability:"int",key:"FlatModifier",predicate:{all:["class:investigator","devise-a-stratagem",{or:["action:disarm","action:grapple","action:shove","action:trip"]}],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:base:sap"]},selector:"athletics",type:"ability"}}get#deviseAStratagem(){return{ability:"int",key:"FlatModifier",predicate:{all:["class:investigator","devise-a-stratagem"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:base:sap"]},selector:"attack-roll",type:"ability"}}get#ruffianPredicate(){return{all:["target:condition:flat-footed","weapon:category:simple",{nor:[{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:trait:agile","weapon:trait:finesse"]}]}}get#sneakAttackPredicate(){return{all:["target:condition:flat-footed"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]}]}}}class Migration776SlugifyConditionOverrides extends MigrationBase{static{__name(this,"Migration776SlugifyConditionOverrides")}static{__name2(this,"Migration776SlugifyConditionOverrides")}static version=.776;async updateItem(source){if(source.type!=="condition")return;const{system}=source;Array.isArray(system.overrides)&&system.overrides.every(o=>typeof o=="string")&&(system.overrides=system.overrides.map(o=>sluggify(o)))}}class Migration777HandOfTheApprentice extends MigrationBase{static{__name(this,"Migration777HandOfTheApprentice")}static{__name2(this,"Migration777HandOfTheApprentice")}static version=.777;async updateItem(source){if(source.type==="feat"&&source.system.slug==="hand-of-the-apprentice"){const rule={key:"ActiveEffectLike",mode:"add",path:"system.resources.focus.max",value:1};source.system.rules=[rule]}}}class Migration778RenameRetiredPackRefs extends MigrationBase{static{__name(this,"Migration778RenameRetiredPackRefs")}static{__name2(this,"Migration778RenameRetiredPackRefs")}static version=.778;async updateItem(source){const rename=__name2(text=>text.replace(/\bpf2e\.consumable-effects\b/g,"pf2e.equipment-effects").replace(/\bpf2e\.exploration-effects\b/g,"pf2e.other-effects").replace(/\bpf2e\.feature-effects\b/g,"pf2e.feat-effects").replace(/\bpf2e\.equipment-effects\.I9lfZUiCwMiGogVi\b/g,"pf2e.other-effects.I9lfZUiCwMiGogVi").replace(/\bpf2e\.equipment-effects\.Cover\b/g,"pf2e.other-effects.Effect: Cover"),"rename");source.system.rules=recursiveReplaceString(source.system.rules,rename),source.system.description=recursiveReplaceString(source.system.description,rename)}}class Migration779EliteWeak extends MigrationBase{static{__name(this,"Migration779EliteWeak")}static{__name2(this,"Migration779EliteWeak")}static version=.779;async updateActor(source){if(!(source.type==="npc"&&source.system.traits.traits?.value))return;const traits=source.system.traits.traits,adjustment=traits.value.includes("elite")?"elite":traits.value.includes("weak")?"weak":null;adjustment&&(source.system.attributes.adjustment=adjustment,traits.value=traits.value.filter(trait=>trait!=="elite"&&trait!=="weak"))}}class Migration780NumifySpeeds extends MigrationBase{static{__name(this,"Migration780NumifySpeeds")}static{__name2(this,"Migration780NumifySpeeds")}static version=.78;async updateActor(source){if(source.type!=="npc"&&source.type!=="character")return;const speeds=source.system.attributes.speed;speeds.value=this.#updateSpeed(speeds.value),Array.isArray(speeds.otherSpeeds)||(speeds.otherSpeeds=[]);for(const movementType of speeds.otherSpeeds)movementType.value=this.#updateSpeed(movementType.value)}#updateSpeed(speed){const numifiedValue=parseInt(String(speed),10);return Number.isNaN(numifiedValue)?25:numifiedValue}}class Migration781SuppressNoCrowbar extends MigrationBase{static{__name(this,"Migration781SuppressNoCrowbar")}static{__name2(this,"Migration781SuppressNoCrowbar")}static version=.781;get#suppressNoCrowbar(){return{key:"AdjustModifier",selector:"athletics",slug:"no-crowbar",suppress:!0}}async updateItem(source){if(!source.system.slug)return;const isCrowbar=source.type==="equipment"&&/^crowbar(?:-levered)?$/.test(source.system.slug),isForcedEntry=source.type==="feat"&&source.system.slug==="forced-entry";(isCrowbar||isForcedEntry)&&!source.system.rules.some(r=>r.key==="AdjustModifier")&&source.system.rules.push(this.#suppressNoCrowbar)}}class Migration782UnnestActorTraits extends MigrationBase{static{__name(this,"Migration782UnnestActorTraits")}static{__name2(this,"Migration782UnnestActorTraits")}static version=.782;async updateActor(source){const traits=source.system.traits;traits&&traits.traits&&Array.isArray(traits.traits.value)&&(traits.value=traits.traits.value,delete traits.traits,traits["-=traits"]=null)}}class Migration783RemoveClassSkillAELikes extends MigrationBase{static{__name(this,"Migration783RemoveClassSkillAELikes")}static{__name2(this,"Migration783RemoveClassSkillAELikes")}static version=.783;async updateItem(source){source.type==="class"&&(source.system.rules=source.system.rules.filter(r=>!(r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system.skills\.[a-z]{3}\.rank$/.test(r.path)&&r.value===1)))}}class Migration784CompBrowserPackSetting extends MigrationBase{static{__name(this,"Migration784CompBrowserPackSetting")}static{__name2(this,"Migration784CompBrowserPackSetting")}static version=.784;async migrate(){const savedSettings=game.settings.get("pf2e","compendiumBrowserPacks");if(savedSettings instanceof String){const settings=JSON.parse(savedSettings.toString());await game.settings.set("pf2e","compendiumBrowserPacks",settings);const browser=game?.pf2e?.compendiumBrowser;browser&&(browser.settings=settings,browser.initCompendiumList())}}}class Migration785ABCKitItemUUIDs extends MigrationBase{static{__name(this,"Migration785ABCKitItemUUIDs")}static{__name2(this,"Migration785ABCKitItemUUIDs")}static version=.785;async updateItem(source){switch(source.type){case"ancestry":case"background":case"class":case"kit":this.#convertToUUIDs(Object.values(source.system.items))}}#convertToUUIDs(references){for(const reference of references)reference.id&&reference.pack?reference.uuid=`Compendium.${reference.pack}.${reference.id}`:reference.id&&(reference.uuid=`Item.${reference.id}`),delete reference.id,delete reference.pack,reference["-=id"]=null,reference["-=pack"]=null,reference.items&&this.#convertToUUIDs(Object.values(reference.items))}}class Migration786RemoveIdentifiedData extends MigrationBase{static{__name(this,"Migration786RemoveIdentifiedData")}static{__name2(this,"Migration786RemoveIdentifiedData")}static version=.786;async updateItem(source){if(!isPhysicalData(source))return;const identification=source.system.identification??{};identification.identified&&(identification["-=identified"]=null)}}class Migration787ResolvablesToSystem extends MigrationBase{static{__name(this,"Migration787ResolvablesToSystem")}static{__name2(this,"Migration787ResolvablesToSystem")}static version=.787;async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(weapon|spell)\.data\.data./g,"@$1.system.").replace(/@(weapon|spell)\.data./g,"@$1."))}}class Migration788UpdateTanglefootBags extends MigrationBase{static{__name(this,"Migration788UpdateTanglefootBags")}static{__name2(this,"Migration788UpdateTanglefootBags")}static version=.788;async updateItem(source){if(source.type==="weapon"&&source.system.slug?.startsWith("tanglefoot-bag-"))switch(source.system.damage.dice=0,source.system.slug){case"tanglefoot-bag-lesser":{source.system.rules=this.#getRules("Lesser");return}case"tanglefoot-bag-moderate":{source.system.rules=this.#getRules("Moderate");return}case"tanglefoot-bag-greater":{source.system.rules=this.#getRules("Greater");return}case"tanglefoot-bag-major":{source.system.rules=this.#getRules("Major");return}}}#getRules(type){return[{key:"Note",outcome:["success"],selector:"{item|_id}-attack",text:`PF2E.BombNotes.TanglefootBag.${type}.success`,title:"TYPES.Item.effect"},{key:"Note",outcome:["criticalSuccess"],selector:"{item|_id}-attack",text:`PF2E.BombNotes.TanglefootBag.${type}.criticalSuccess`,title:"TYPES.Item.effect"}]}}class Migration789UpdatePreciseStrike extends MigrationBase{static{__name(this,"Migration789UpdatePreciseStrike")}static{__name2(this,"Migration789UpdatePreciseStrike")}static version=.789;async updateItem(source){if(source.type==="feat"){if(source.system.slug==="precise-strike")source.system.rules=this.#preciseStrikeRules;else if(source.system.slug==="finishing-precision"){const rules=source.system.rules.filter(r=>r.key==="GrantItem");source.system.rules=[...rules,...this.#finishingPrecisionRules]}}}get#preciseStrikeRules(){return[{domain:"damage-roll",key:"RollOption",label:"PF2E.SpecificRule.PreciseStrike.Finisher",option:"finisher",toggleable:!0},{damageCategory:"precision",key:"FlatModifier",predicate:{all:["class:swashbuckler","self:effect:panache",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"],not:["finisher"]},selector:"strike-damage",slug:"precise-strike",value:{brackets:[{end:4,value:2},{end:8,start:5,value:3},{end:12,start:9,value:4},{end:16,start:13,value:5},{start:17,value:6}]}},{category:"precision",dieSize:"d6",key:"DamageDice",predicate:{all:["class:swashbuckler","self:effect:panache","finisher",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"]},selector:"strike-damage",slug:"finisher",value:{brackets:[{end:4,value:{diceNumber:2}},{end:8,start:5,value:{diceNumber:3}},{end:12,start:9,value:{diceNumber:4}},{end:16,start:13,value:{diceNumber:5}},{start:17,value:{diceNumber:6}}]}}]}get#finishingPrecisionRules(){return[{damageCategory:"precision",key:"FlatModifier",predicate:{all:["self:effect:panache",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"],not:["finisher"]},selector:"strike-damage",slug:"finishing-precision",value:1},{category:"precision",diceNumber:1,dieSize:"d6",key:"DamageDice",predicate:{all:["self:effect:panache","finisher",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"]},selector:"strike-damage",slug:"finishing-precision"}]}}class Migration790MultipleClassDCs extends MigrationBase{static{__name(this,"Migration790MultipleClassDCs")}static{__name2(this,"Migration790MultipleClassDCs")}static version=.79;#otherClassDCs=new Map([["call-implement","thaumaturge"],["eerie-proclamation","ranger"],["stunning-fist","monk"],["ring-bell","thaumaturge"]]);#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateActor(source){if(source.type!=="character")return;const customModifiers=source.system.customModifiers??{};customModifiers?.class&&(customModifiers["-=class"]=null)}async updateItem(source){if(this.#isClassFeature(source)){const classSlug=source.system.traits.value.at(0);if(!classSlug)return;const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike");for(const aeLike of aeLikes)aeLike.path==="system.attributes.classDC.rank"&&(aeLike.path=`system.proficiencies.classDCs.${classSlug}.rank`)}const itemSlug=source.system.slug??"";if(this.#otherClassDCs.has(itemSlug)){const oldClassDCPattern=/\bsystem\.attributes\.classDC\b/,classSlug=this.#otherClassDCs.get(itemSlug),{description}=source.system;description.value=description.value.replace(oldClassDCPattern,`system.proficiencies.classDCs.${classSlug}`);const notes=source.system.rules.filter(r=>r.key==="Note"&&typeof r.text=="string");for(const note of notes)note.text=note.text.replace(oldClassDCPattern,`system.proficiencies.classDCs.${classSlug}`)}}}class Migration791RuffianHands extends MigrationBase{static{__name(this,"Migration791RuffianHands")}static{__name2(this,"Migration791RuffianHands")}static version=.791;async updateItem(source){if(!(source.type!=="feat"||!source.system.slug))switch(source.system.slug){case"ruffian":{source.system.rules.some(r=>r.key==="CriticalSpecialization")||source.system.rules.push(this.#critSpec);break}case"healing-hands":{const hands=this.#hands;hands.predicate={all:["item:slug:heal"]},source.system.rules=[hands];break}case"harming-hands":{const hands=this.#hands;hands.predicate={all:["item:slug:harm"]},source.system.rules=[hands];break}}}get#critSpec(){return{key:"CriticalSpecialization",predicate:{all:["target:condition:flat-footed","weapon:category:simple",{lte:["weapon:damage:die:faces",8]}]}}}get#hands(){return{key:"DamageDice",override:{dieSize:"d10"},selector:"spell-damage"}}}class Migration792RemoveTokenAELikes extends MigrationBase{static{__name(this,"Migration792RemoveTokenAELikes")}static{__name2(this,"Migration792RemoveTokenAELikes")}static version=.792;async updateItem(source){const rules=source.system.rules;for(const rule of[...rules])rule.key==="ActiveEffectLike"&&typeof rule.path=="string"&&/^token\./.test(rule.path)&&rules.splice(rules.indexOf(rule),1)}}class Migration793MakePredicatesArrays extends MigrationBase{static{__name(this,"Migration793MakePredicatesArrays")}static{__name2(this,"Migration793MakePredicatesArrays")}static version=.793;#convertLegacyData(predicate){const keys2=Object.keys(predicate);return keys2.length===0?[]:keys2.length===1&&Array.isArray(predicate.all)?foundry.utils.deepClone(predicate.all):keys2.length===1&&Array.isArray(predicate.any)&&predicate.any.length===1?foundry.utils.deepClone(predicate.any):foundry.utils.deepClone([predicate.all??[],Array.isArray(predicate.any)?{or:predicate.any}:[],Array.isArray(predicate.not)?predicate.not.length===1?{not:predicate.not[0]}:{nor:predicate.not}:[]].flat())}async updateActor(source){if("customModifiers"in source.system){isObject(source.system.customModifiers)||(source.system.customModifiers={});for(const modifier of Object.values(source.system.customModifiers).flat())modifier.predicate&&=[]}}async updateItem(source){const rules=source.system.rules;for(const rule of rules){if(this.#isOldRawPredicate(rule.predicate)&&(rule.predicate=this.#convertLegacyData(rule.predicate)),this.#isOldRawPredicate(rule.definition)&&(rule.definition=this.#convertLegacyData(rule.definition)),this.#isOldRawPredicate(rule.allowedDrops)&&(rule.allowedDrops={label:rule.allowedDrops.label??void 0,predicate:this.#convertLegacyData(rule.allowedDrops)}),this.#isOldRawPredicate(rule.predicate)&&(rule.predicate=this.#convertLegacyData(rule.predicate)),this.#isArrayChoiceSet(rule))for(const choice of rule.choices)this.#isOldRawPredicate(choice.predicate)&&(choice.predicate=this.#convertLegacyData(choice.predicate));else this.#isObjectChoiceSet(rule)?(this.#isOldRawPredicate(rule.choices.predicate)&&(rule.choices.predicate=this.#convertLegacyData(rule.choices.predicate)),this.#isOldRawPredicate(rule.choices.postFilter)&&(rule.choices.postFilter=this.#convertLegacyData(rule.choices.postFilter))):this.#isOldRawPredicate(rule.craftableItems)&&(rule.craftableItems=this.#convertLegacyData(rule.craftableItems));this.#isOldRawPredicate(rule.disabledIf)&&(rule.disabledIf=this.#convertLegacyData(rule.disabledIf))}}#isOldRawPredicate(predicate){return!predicate||Array.isArray(predicate)||isObject(predicate)&&Array.isArray(predicate.predicate)?!1:predicate instanceof Object}#isArrayChoiceSet(rule){return rule.key==="ChoiceSet"&&Array.isArray(rule.choices)}#isObjectChoiceSet(rule){return rule.key==="ChoiceSet"&&isObject(rule.choices)&&!Array.isArray(rule.choices)}}class Migration794AddWildShapeChoices extends MigrationBase{static{__name(this,"Migration794AddWildShapeChoices")}static{__name2(this,"Migration794AddWildShapeChoices")}static version=.794;#shapeFeats=new Set(["VaIHQzOE5ibmbtqU","OWedlrKGsVZVkSnT","wNHUryoRzlfDCFAd","F0MYBfiyOD8YHq5t","I9rSWQyueWHQyNxe","p0jZhb8PSswUsZaz","Le30algCdKIsxmeK","54JzsYCx3uoj7Wlz"].map(id=>`Compendium.pf2e.feats-srd.${id}`));async updateItem(source){const sourceId=source.flags.core?.sourceId;if(source.type==="feat"&&sourceId&&this.#shapeFeats.has(sourceId)){const fromPack=await fromUuid(sourceId);fromPack instanceof FeatPF2e&&(source.system.rules=fromPack.toObject().system.rules)}}}class Migration795CleanupFlatFootedToggle extends MigrationBase{static{__name(this,"Migration795CleanupFlatFootedToggle")}static{__name2(this,"Migration795CleanupFlatFootedToggle")}static version=.795;get#flatFootedToggle(){return{key:"RollOption",domain:"all",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}}async updateActor(source){source.flags.pf2e?.rollOptions&&(source.flags.pf2e["-=rollOptions"]=null)}async updateItem(source){if(source.type==="feat"||source.type==="action"&&source.system.slug==="sneak-attack")switch(source.system.slug){case"sneak-attack":case"laughing-shadow":case"shadow-sneak-attack":case"butterflys-sting":case"game-hunter-dedication":source.system.rules.some(r=>this.#isFlatFootedToggle(r))||source.system.rules.push(this.#flatFootedToggle)}}#isFlatFootedToggle(rule){return rule.key==="RollOption"&&rule.option==="target:condition:flat-footed"&&rule.toggleable==="totm"}}class Migration796ItemGrantsToObjects extends MigrationBase{static{__name(this,"Migration796ItemGrantsToObjects")}static{__name2(this,"Migration796ItemGrantsToObjects")}static version=.796;async updateActor(source){for(const item of source.items){const systemFlags=item.flags.pf2e;!systemFlags?.itemGrants||!Array.isArray(systemFlags.itemGrants)||(systemFlags.itemGrants=systemFlags.itemGrants.reduce((grantsObject,grant)=>{if(typeof grant=="string"||grant instanceof Object){const[flag,grantSource]=this.#convertToEntry(source,item,grant);if(flag!==null){const modifiedFlag=this.#modifyFlag(grantsObject,flag);grantsObject[modifiedFlag]=grantSource}}return grantsObject},{}))}}#convertToEntry(actor,granter,grantedData){const grantedId=grantedData instanceof Object?grantedData.id:grantedData;return actor.items.some(i=>i._id===grantedId)?[sluggify(granter.name,{camel:"dromedary"}),{id:grantedId}]:[null,null]}#modifyFlag(grantedItems,flag){const pattern=new RegExp(`^${flag}\\d*$`),nthGrant=Object.keys(grantedItems).filter(g=>pattern.test(g)).length;return nthGrant===0?flag:`${flag}${nthGrant+1}`}}class Migration797MetagameSetting extends MigrationBase{static{__name(this,"Migration797MetagameSetting")}static{__name2(this,"Migration797MetagameSetting")}static version=.797;visibilitySettings=["showDC","showResults"];settings=[...this.visibilitySettings,"tokenSetsNameVisibility","secretDamage","secretCondition","partyVision"];async migrate(){for(const setting of this.settings){const storage=game.settings.storage.get("world"),newKey=`metagame_${setting}`,oldValue=storage.getItem(`pf2e.metagame.${setting}`)??null,existingValueRaw=storage.getItem(`pf2e.${newKey}`)??null;if(oldValue!==null&&existingValueRaw!==null){const newValue=this.visibilitySettings.includes(setting)?!["gm","owner"].includes(oldValue):oldValue;game.settings.set("pf2e",newKey,newValue)}}}}class Migration798WeaponToItemStatements extends MigrationBase{static{__name(this,"Migration798WeaponToItemStatements")}static{__name2(this,"Migration798WeaponToItemStatements")}static version=.798;async updateItem(source){const rules=source.system.rules;for(const rule of rules)for(const property of["predicate","definition"]){const predicate=rule[property];Array.isArray(predicate)&&(rule[property]=recursiveReplaceString(predicate,s=>s.replace(/^weapon:/,"item:")))}}}class Migration799RMRecallKnowledgeDuplicates extends MigrationBase{static{__name(this,"Migration799RMRecallKnowledgeDuplicates")}static{__name2(this,"Migration799RMRecallKnowledgeDuplicates")}static version=.799;#oldIdsPattern=new RegExp("pf2e\\.actionspf2e\\.(?:".concat(["KygTSeDvsFoSO6HW","B0Eu3EfwIa9kyDEA","SeUolRoPzorFUAaI","eT1jXYvz2YH70Ovp","B2BpIZFHoF9Kjzpx","LZgjpWd0pL3vK9Q1","KUfLlXDWTcAWhl8l"].join("|")).concat(")"),"g");async updateItem(source){source.system.description.value??="",source.system.description.value=source.system.description.value.replace(this.#oldIdsPattern,"pf2e.actionspf2e.1OagaWtBpVXExToo")}}class Migration800SelfEffectPanacheRage extends MigrationBase{static{__name(this,"Migration800SelfEffectPanacheRage")}static{__name2(this,"Migration800SelfEffectPanacheRage")}static version=.8;async updateItem(source,actorSource){if(!(actorSource?._id==="bpTQfx4UixMV3Fja"||actorSource?.flags.core?.sourceId==="Compendium.pf2e.extinction-curse-bestiary.Actor.bpTQfx4UixMV3Fja"))for(const rule of source.system.rules)rule.predicate&&Array.isArray(rule.predicate)&&(rule.predicate=recursiveReplaceString(rule.predicate,s=>s.replace(/^(rage|panache)$/,"self:effect:$1")))}}class Migration801ColorDarkvision extends MigrationBase{static{__name(this,"Migration801ColorDarkvision")}static{__name2(this,"Migration801ColorDarkvision")}static version=.801;get#colorDarkvision(){return{key:"ActiveEffectLike",path:"flags.pf2e.colorDarkvision",mode:"override",value:!0}}async updateItem(source){if(!source.system.slug)return;const isFetchling=source.type==="ancestry"&&source.system.slug==="fetchling",isResonantLight=source.type==="feat"&&source.system.slug==="resonant-reflection-reflection-of-light",getsColorDarkvision=isFetchling||isResonantLight,rules=source.system.rules;getsColorDarkvision&&!rules.some(r=>r.path==="flags.pf2e.colorDarkvision")&&source.system.rules.push(this.#colorDarkvision)}}class Migration802StripFeatActionCategory extends MigrationBase{static{__name(this,"Migration802StripFeatActionCategory")}static{__name2(this,"Migration802StripFeatActionCategory")}static version=.802;async updateItem(source){if(source.type!=="feat")return;const feat=source.system;feat.actionCategory&&(delete feat.actionCategory,feat["-=actionCategory"]=null)}}class Migration803NormalizeSpellArea extends MigrationBase{static{__name(this,"Migration803NormalizeSpellArea")}static{__name2(this,"Migration803NormalizeSpellArea")}static version=.803;#AREA_TYPES=new Set(["burst","cone","cube","emanation","line","square"]);async updateItem(source){if(source.type!=="spell")return;const area=source.system.area;area&&(area.value=Number(area.value),"areaType"in area&&this.#isAreaType(area.areaType)&&(area.type=area.areaType,delete area.areaType,area["-=areaType"]=null)),area?.value&&this.#isAreaType(area.type)||(source.system.area=null),"areasize"in source.system&&isObject(source.system.areasize)&&(this.#hasDetails(source.system.areasize.value)&&area&&(area.details=source.system.areasize.value),delete source.system.areasize,source.system["-=areasize"]=null)}#isAreaType(areaType){return typeof areaType=="string"&&areaType.length>0&&this.#AREA_TYPES.has(areaType)}#hasDetails(details){return typeof details=="string"&&details.trim().length>0&&!/^\d+-foot (?:burst|cone|cube|emanation|line|square)$/.test(details)}}class Migration804RemoveConsumableProperties extends MigrationBase{static{__name(this,"Migration804RemoveConsumableProperties")}static{__name2(this,"Migration804RemoveConsumableProperties")}static version=.804;async updateItem(source){if(source.type!=="consumable")return;const system=source.system;system.uses&&delete system.uses,system.autoUse&&(delete system.autoUse,system["-=autoUse"]=null),isObject$1(system.charges)&&"_deprecated"in system.charges&&(delete system.charges._deprecated,system.charges["-=deprecated"]=null),isObject$1(system.consume)&&"_deprecated"in system.consume&&(delete system.consume._deprecated,system.consume["-=deprecated"]=null)}}class Migration805InlineDamageRolls extends MigrationBase{static{__name(this,"Migration805InlineDamageRolls")}static{__name2(this,"Migration805InlineDamageRolls")}static version=.805;#pattern=/\[\[\/r .+?\]\]\]?(?:\{[^}]+\})?/g;#damageTypeLabelPattern=(()=>{const dicePattern="[0-9]{1,2}d[0-9]{1,2}(?:\\s*[-+]\\s*[0-9]{1,3})?",typesUnion=["acid","bleed","bludgeoning","chaotic","cold","electricity","evil","fire","force","good","lawful","mental","negative","piercing","poison","positive","slashing","sonic","untyped"].join("|");return new RegExp(`^${dicePattern} (?:${typesUnion})(?: damage)?$`,"i")})();#updateDamageFormula(text){const skipStrings=["splash","precision","persistent","d20","#"];return text.replace(this.#pattern,match=>{const labelEndsWithDamage=match.toLowerCase().endsWith("damage}");if(skipStrings.some(s=>match.includes(s)))return match;const customLabel=/\{([^}]+)\}$/.exec(match)?.at(1),expressions=match.replace(/\{[^}]+\}$/,"").match(/\{[^}]+\}\[\w+\]/g)??[];if(expressions.length===0)return match;const instances=expressions.map(i=>i.trim().replace(/^\{([^}]+)\}\[([a-z]+)\]$/i,["+","-","*","/"].some(o=>i.includes(o))?"($1)[$2]":"$1[$2]").toLowerCase()),reassembled=instances.length===1?`[[/r ${instances[0]}]]`:`[[/r {${instances.join(",")}}]]`;return customLabel&&!this.#damageTypeLabelPattern.test(customLabel)?`${reassembled}{${customLabel}}`:labelEndsWithDamage?`${reassembled} damage`:reassembled})}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration806TorchImprovisedOtherTags extends MigrationBase{static{__name(this,"Migration806TorchImprovisedOtherTags")}static{__name2(this,"Migration806TorchImprovisedOtherTags")}static version=.806;async updateItem(source){if(source.type==="equipment"&&source.system.slug==="torch"){const torchStrikeRE=source.system.rules.find(r=>r.key==="Strike"&&r.otherTags===void 0);torchStrikeRE&&(delete torchStrikeRE.traits,torchStrikeRE.otherTags=["improvised"])}}}class Migration807RMActivatedEffectFields extends MigrationBase{static{__name(this,"Migration807RMActivatedEffectFields")}static{__name2(this,"Migration807RMActivatedEffectFields")}static version=.807;async updateItem(source){if(source.type==="consumable")for(const property of["activation","duration","range","target","uses"])property in source.system&&(delete source.system[property],source.system[`-=${property}`]=null)}}class Migration808CountDamageDice extends MigrationBase{static{__name(this,"Migration808CountDamageDice")}static{__name2(this,"Migration808CountDamageDice")}static version=.808;async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/\(?\b1\s*\+\s*@(item|weapon)(?:.system)?.runes.striking\)?/g,"@$1.system.damage.dice"))}}class Migration809AutomatonEnhancements extends MigrationBase{static{__name(this,"Migration809AutomatonEnhancements")}static{__name2(this,"Migration809AutomatonEnhancements")}static version=.809;get#automatonEnhancements(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.automaton.enhancements",priority:10,value:{greater:[],lesser:[]}}}async updateItem(source){const isAutomaton=source.type==="ancestry"&&source.system.slug==="automaton",rules=source.system.rules;isAutomaton&&!rules.some(r=>r.path==="flags.pf2e.automaton.enhancements")&&source.system.rules.push(this.#automatonEnhancements)}}class Migration810LootDescriptionValue extends MigrationBase{static{__name(this,"Migration810LootDescriptionValue")}static{__name2(this,"Migration810LootDescriptionValue")}static version=.81;async updateActor(source){if(source.type==="loot"){const details=source.system.details;details.description instanceof Object&&(details.description=String(details.description.value??""))}}}class Migration811InlineDamageRollsPersistent extends MigrationBase{static{__name(this,"Migration811InlineDamageRollsPersistent")}static{__name2(this,"Migration811InlineDamageRollsPersistent")}static version=.811;#conditionPattern=/(?<=\]\]|})(\s*@(?:UUID|Compendium)\[(?:Compendium\.)?pf2e\.conditionitems\.(?:Persistent Damage|lDVqvLKA6eF3Df60)\]\{[^}]+})/g;#pattern=/\[\[\/r ([^[\]]+(\[.*?\])?)\]\](\{\dd\d[^{}]*\})?/g;#updateDamageFormula(text){return text.replace(this.#conditionPattern," damage").replace(this.#pattern,(match,formula)=>{if(!match.includes("persistent"))return match;const hashStyle=formula.match(/([^#]+)#\s*persistent ([^#]+)/);if(hashStyle){const expression=hashStyle[1].trim(),damageType=hashStyle[2].trim(),expressionCleaned=["+","-","*","/"].some(o=>expression.includes(o))?`(${expression})`:expression;return match.replace(formula,`${expressionCleaned}[persistent,${damageType}]`)}const expressions=formula.match(/\{[^}]+\}\[[\w,]+\]/g)??[];if(expressions.length){const withoutLabel=match.replace(/\{\dd\d[^{}]*\}$/,""),instances=expressions.map(i=>i.replace(/^\{([^}]+)\}\[([a-z,]+)\]$/,["+","-","*","/"].some(o=>i.includes(o))?"($1)[$2]":"$1[$2]")),reassembled=instances.length===1?instances[0]:`{${instances.join(",")}}`;return withoutLabel.replace(formula,reassembled)}return match})}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration812RestructureIWR extends MigrationBase{static{__name(this,"Migration812RestructureIWR")}static{__name2(this,"Migration812RestructureIWR")}static version=.812;async updateActor(source){const traits=source.system.traits;if(!traits||source.type==="familiar")return;const{attributes}=source.system;if("ci"in traits&&("game"in globalThis||delete traits.ci,traits["-=ci"]=null),"di"in traits){const oldData=traits.di;if("game"in globalThis||delete traits.di,traits["-=di"]=null,isObject$1(oldData)&&"value"in oldData&&Array.isArray(oldData.value)&&oldData.value.length>0){const immunities=oldData.value.map(i=>this.#normalizeType(String(i))).filter(i=>setHasElement(IMMUNITY_TYPES,i)).map(i=>({type:i}));immunities.length>0&&(attributes.immunities=immunities)}}if("dv"in traits){const oldData=traits.dv;if("game"in globalThis||delete traits.dv,traits["-=dv"]=null,Array.isArray(oldData)&&oldData.length>0){const weaknesses=this.#getWR(oldData,WEAKNESS_TYPES).map(data=>{const weakness=pick(data,["type","value"]),exceptions=this.#parseExceptions(String(data.exceptions??"")).exceptions.filter(e=>setHasElement(WEAKNESS_TYPES,e));return exceptions.length>0&&(weakness.exceptions=exceptions),weakness});weaknesses.length>0&&(attributes.weaknesses=weaknesses)}}if("dr"in traits){const oldData=traits.dr;if("game"in globalThis||delete traits.dr,traits["-=dr"]=null,Array.isArray(oldData)&&oldData.length>0){const resistances=this.#getWR(oldData,RESISTANCE_TYPES).map(data=>{const resistance=pick(data,["type","value"]),parsed=this.#parseExceptions(String(data.exceptions??"")),exceptions=parsed.exceptions.filter(e=>setHasElement(RESISTANCE_TYPES,e));exceptions.length>0&&(resistance.exceptions=exceptions);const doubleVs=parsed.doubleVs.filter(e=>setHasElement(RESISTANCE_TYPES,e));return doubleVs.length>0&&(resistance.doubleVs=doubleVs),resistance});resistances.length>0&&(attributes.resistances=resistances)}}}async updateItem(source){if(source.type==="weapon"){const material=source.system.preciousMaterial??{};material.value=typeof material.value=="string"?sluggify(material.value):null,source.system.preciousMaterialGrade&&(source.system.preciousMaterialGrade.value||=null)}const iwrREs=source.system.rules.filter(r=>typeof r.key=="string"&&["Immunity","Weakness","Resistance"].includes(r.key)&&"type"in r&&typeof r.type=="string");for(const rule of iwrREs)if(rule.type=rule.type.startsWith("{")?rule.type:this.#normalizeType(rule.type),typeof rule.except=="string"){const exceptions=this.#parseExceptions(rule.except).exceptions.filter(exception=>rule.key==="Immunity"?setHasElement(IMMUNITY_TYPES,exception):rule.key==="Weakness"?setHasElement(WEAKNESS_TYPES,exception):setHasElement(RESISTANCE_TYPES,exception));exceptions.length>0&&(rule.exceptions=exceptions),delete rule.except}const adjustStrikeREs=source.system.rules.filter(r=>r.key==="AdjustStrike"&&typeof r.value=="string");for(const rule of adjustStrikeREs)rule.value=rule.value.startsWith("{")||["property-runes","weapon-traits"].includes(rule.property)?rule.value:this.#normalizeType(rule.value)}#getWR(maybeWR,typeSet){return maybeWR.filter(r=>isObject$1(r)&&typeof r.type=="string"&&typeof r.value=="number").map(wr=>(wr.type=this.#normalizeType(wr.type),wr.value=Math.abs(wr.value),wr)).filter(r=>setHasElement(typeSet,r.type))}#oldENmappings={"PF2E.ResistanceException.Bludgeoning":"except bludgeoning","PF2E.ResistanceException.ForceGhostTouchDoubleNonMagical":"except force, or ghost touch; double resistance vs. non-magical","PF2E.ResistanceException.ForceGhostTouchNegativeDoubleNonMagical":"except force, ghost touch, or negative; double resistance vs. non-magical","PF2E.ResistanceException.ForceGhostTouchPositiveDoubleNonMagical":"except force, ghost touch, or positive; double resistance vs. non-magical"};#parseExceptions(text){const normalized=(this.#oldENmappings[text]??text).toLowerCase().replace("PF2E.TraitForce","force").replace("PF2E.TraitPositive","positive").replace("cold iron","cold-iron").replace("critical hits","critical-hits").replace("ghost touch","ghost-touch").replace("nonmagical","non-magical").replace("weapons shedding bright light","weapons-shedding-bright-light").replace("unarmed","unarmed-attacks").replace(/\bexcept\b/,"").trim().replace(/\s+/," ");if(!normalized)return{exceptions:[],doubleVs:[]};const doubleIndex=normalized.indexOf("double"),exceptions=(doubleIndex===-1?normalized:normalized.slice(0,doubleIndex)).split(/[,\s]+/).map(d=>sluggify(d)),doubleVs=normalized.slice(doubleIndex).split(/[,\s]+/).map(d=>sluggify(d));return{exceptions,doubleVs}}#normalizeType(text){switch(text=text.trim(),text){case"all":case"All":return"all-damage";case"arrow":return"arrow-vulnerability";case"axe":return"axe-vulnerability";case"coldiron":return"cold-iron";case"nonlethal":return"nonlethal-attacks";case"nonmagical-attacks":return"non-magical";case"protean anatomy":return"protean-anatomy";case"unarmed":return"unarmed-attacks";default:return sluggify(text)}}}class Migration813NormalizeColdIron extends MigrationBase{static{__name(this,"Migration813NormalizeColdIron")}static{__name2(this,"Migration813NormalizeColdIron")}static version=.813;async updateItem(source){switch(source.type){case"melee":{const traits=source.system.traits;traits.value=traits.value.map(t=>t.replace(/^coldiron$/i,"cold-iron"));return}case"armor":case"weapon":{const preciousMaterial=source.system.preciousMaterial;if(typeof preciousMaterial?.value!="string")return;preciousMaterial.value&&=preciousMaterial.value.replace(/^coldiron$/i,"cold-iron"),source.type==="weapon"&&this.#updateWeaponMaterialData(source);return}}const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet"&&"choices"in r&&Array.isArray(r.choices)&&r.choices.every(c=>isObject(c)&&"value"in c&&typeof c.value=="string"));for(const choiceSet of choiceSets)this.#updateChoiceSet(choiceSet)}#updateWeaponMaterialData(source){if(source.type!=="weapon"||!isObject(source.system.specific))return;const specificData=source.system.specific;specificData.value||(delete specificData.material,delete specificData.price,delete specificData.runes,specificData["-=material"]=null,specificData["-=price"]=null,specificData["-=runes"]=null);const material=specificData.material;material?.precious?(material.precious.type&&=material.precious.type.replace(/^coldiron$/i,"cold-iron"),delete material.base,material["-=base"]=null):typeof material?.type=="string"&&typeof material.grade=="string"&&(material.precious={type:material.type.replace(/^coldiron$/i,"cold-iron"),grade:material.grade},delete material.type,delete material.grade,material["-=type"]=null,material["-=grade"]=null)}#updateChoiceSet(choiceSet){for(const choice of choiceSet.choices)/coldiron/i.test(String(choice.value))&&(choice.value="cold-iron");/coldiron/i.test(String(choiceSet.selection))&&(choiceSet.selection="cold-iron")}}class Migration814CalculatedExpandedSplash extends MigrationBase{static{__name(this,"Migration814CalculatedExpandedSplash")}static{__name2(this,"Migration814CalculatedExpandedSplash")}static version=.814;async updateItem(source){if(source.type==="feat")switch(source.system.slug){case"calculated-splash":{const rules=[{key:"AdjustModifier",mode:"upgrade",predicate:[{not:"feat:expanded-splash"}],relabel:"{item|name}",selector:"alchemical-bomb-damage",slug:"splash",value:"@actor.abilities.int.mod"}];source.system.rules=rules;return}case"expanded-splash":{const rules=[{damageCategory:"splash",key:"FlatModifier",predicate:["item:trait:splash"],selector:"alchemical-bomb-damage",value:"@actor.abilities.int.mod"},{key:"Note",predicate:["item:trait:splash"],selector:"alchemical-bomb-damage",text:"The bomb deals splash damage to every creature within 10 feet of the target.",title:"{item|name}"}];source.system.rules=rules}}}}class Migration815ConsumableDataCleanup extends MigrationBase{static{__name(this,"Migration815ConsumableDataCleanup")}static{__name2(this,"Migration815ConsumableDataCleanup")}static version=.815;consumableKeys=new Set(["autoDestroy","baseItem","bulk","charges","consumableType","consume","containerId","description","equipped","equippedBulk","hardness","hp","identification","level","negateBulk","preciousMaterial","preciousMaterialGrade","price","quantity","rules","schema","size","slug","source","spell","stackGroup","temporary","traits","usage","weight"]);async updateItem(source){if(source.type!=="consumable")return;const systemData=source.system;for(const key of Object.keys(systemData)){const value=systemData[key];this.consumableKeys.has(key)?isObject(value)&&"_deprecated"in value&&(delete value._deprecated,value["-=_deprecated"]=null):(delete systemData[key],systemData[`-=${key}`]=null)}}}class Migration816AlchemistResearchFields extends MigrationBase{static{__name(this,"Migration816AlchemistResearchFields")}static{__name2(this,"Migration816AlchemistResearchFields")}static version=.816;get#bomberSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.8QAFgy9U8PxEa7Dw",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.RGs4uR3CAvgbtBAA",perpetualInfusions:"Compendium.pf2e.classfeatures.DFQDtT1Van4fFEHi",perpetualPerfection:"Compendium.pf2e.classfeatures.xO90iBD8XNGyaCkz",perpetualPotency:"Compendium.pf2e.classfeatures.8rEVg03QJ71ic3PP"}}}get#chirurgeonSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.qC0Iz6SlG2i9gv6g",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.JJcaVijwRt9dsnac",perpetualInfusions:"Compendium.pf2e.classfeatures.fzvIe6FwwCuIdnjX",perpetualPerfection:"Compendium.pf2e.classfeatures.YByJ9O7oe8wxfbqs",perpetualPotency:"Compendium.pf2e.classfeatures.VS5vkqUQu4n7E28Y"}}}get#mutagenistSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.V4Jt7eDnJBLv5bDj",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.1BKdOJ0HNL6Eg3xw",perpetualInfusions:"Compendium.pf2e.classfeatures.Dug1oaVYejLmYEFt",perpetualPerfection:"Compendium.pf2e.classfeatures.CGetAmSbv06fW7GT",perpetualPotency:"Compendium.pf2e.classfeatures.mZFqRLYOQEqKA8ri"}}}get#toxicologistSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.6zo2PJGYoig7nFpR",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.tnqyQrhrZeDtDvcO",perpetualInfusions:"Compendium.pf2e.classfeatures.LlZ5R50z9j8jysZL",perpetualPerfection:"Compendium.pf2e.classfeatures.3R19zS7gERhEX87F",perpetualPotency:"Compendium.pf2e.classfeatures.JOdbVu14phvdjhaY"}}}async updateItem(source){if(!(source.type!=="feat"||!source.system.slug)&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.alchemist"))switch(source.system.slug){case"bomber":{source.system.rules.push(this.#bomberSetFlags);break}case"chirurgeon":{source.system.rules.push(this.#chirurgeonSetFlags);break}case"mutagenist":{source.system.rules.push(this.#mutagenistSetFlags);break}case"toxicologist":{source.system.rules.push(this.#toxicologistSetFlags);break}}}}class Migration817FieldDiscoveryPredicates extends MigrationBase{static{__name(this,"Migration817FieldDiscoveryPredicates")}static{__name2(this,"Migration817FieldDiscoveryPredicates")}static version=.817;async updateItem(source){const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&"path"in r&&typeof r.path=="string"&&/^system.crafting.entries.\w+.fieldDiscovery$/.test(r.path)&&"value"in r&&typeof r.value=="string");for(const rule of aeLikes)switch(rule.value){case"bomb":rule.value=["item:base:alchemical-bomb"];break;case"elixir":rule.value=["item:trait:elixir","item:trait:healing"];break;case"mutagen":rule.value=["item:trait:mutagen"];break;case"poison":rule.value=["item:trait:alchemical","item:trait:poison"];break;default:rule.value=[`item:trait:${rule.value}`]}}}class Migration818BasicUndeadNegativeHealing extends MigrationBase{static{__name(this,"Migration818BasicUndeadNegativeHealing")}static{__name2(this,"Migration818BasicUndeadNegativeHealing")}static version=.818;#needsRE(source){return source.system.slug==="basic-undead-benefits"&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&"path"in r&&r.path==="system.attributes.hp.negativeHealing")}async updateItem(source){if(source.type==="feat"&&this.#needsRE(source)){const rule={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};source.system.rules.push(rule)}}}class Migration819SpinTaleAdventureSpecific extends MigrationBase{static{__name(this,"Migration819SpinTaleAdventureSpecific")}static{__name2(this,"Migration819SpinTaleAdventureSpecific")}static version=.819;async updateItem(source){if(source.type==="feat"){const oldSpinTale="Compendium.pf2e.adventure-specific-actions.Spin Tale",newSpinTale="Compendium.pf2e.actionspf2e.Spin Tale",oldSpinTaleId="Compendium.pf2e.adventure-specific-actions.5gahZQXf3UVwATSC",newSpinTaleId="Compendium.pf2e.actionspf2e.hPZQ5vA9QHEPtjFW";source.system.description.value=source.system.description.value.replace(oldSpinTale,newSpinTale),source.system.description.value=source.system.description.value.replace(oldSpinTaleId,newSpinTaleId)}}}class Migration820RemoveUnusedTraitsData extends MigrationBase{static{__name(this,"Migration820RemoveUnusedTraitsData")}static{__name2(this,"Migration820RemoveUnusedTraitsData")}static version=.82;async updateItem(source){source.system.traits;const systemSource=source.system;systemSource.traits&&("custom"in systemSource.traits&&(delete systemSource.traits.custom,systemSource.traits["-=custom"]=null),(source.type==="spellcastingEntry"||source.type==="condition")&&(delete systemSource.traits,systemSource["-=traits"]=null))}}class Migration821InlineDamageRolls extends MigrationBase{static{__name(this,"Migration821InlineDamageRolls")}static{__name2(this,"Migration821InlineDamageRolls")}static version=.821;#splashPattern1=/\[\[(\/b?r)\s*{([^}]*)}\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#splashPattern2=/\[\[(\/b?r)\s*([^[]*)\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#damagePatternSingle=/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#damagePatternPair=/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*[+,]\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#cleanFormula(formula){return formula=formula.replace(/\s+/g,""),["+","-","*","/"].some(o=>formula.includes(o))?`(${formula})`:formula}#buildSplashFormula(roll,formula,damage,tag){return formula=this.#cleanFormula(formula),damage=damage.trim(),tag=tag?.trim()??"",tag.length>0?`[[${roll} (${formula}[splash])[${damage}] ${tag}]]`:`[[${roll} (${formula}[splash])[${damage}]]]`}#buildDamageFormula(roll,parts,tag){if(tag=tag?.trim()??"",parts.length===1){const formula=this.#cleanFormula(parts[0].formula),damage=parts[0].damage.trim();return tag.length>0?`[[${roll} ${formula}[${damage}] ${tag}]]`:`[[${roll} ${formula}[${damage}]]]`}else if(parts.length>1){const assembled=parts.map(p=>{const formula=this.#cleanFormula(p.formula),damage=p.damage.trim();return`${formula}[${damage}]`}).join(",");return tag.length>0?`[[${roll} {${assembled}} ${tag}]]`:`[[${roll} {${assembled}}]]`}else return""}#updateDamageFormula(text){return text=text.replace(this.#splashPattern1,(_,roll,formula,damage,tag)=>this.#buildSplashFormula(roll,formula,damage,tag)),text=text.replace(this.#splashPattern2,(_,roll,formula,damage,tag)=>this.#buildSplashFormula(roll,formula,damage,tag)),text=text.replace(this.#damagePatternSingle,(_,roll,formula,damage,tag)=>this.#buildDamageFormula(roll,[{formula,damage}],tag)),text=text.replace(this.#damagePatternPair,(_,roll,formula1,damage1,formula2,damage2,tag)=>this.#buildDamageFormula(roll,[{formula:formula1,damage:damage1},{formula:formula2,damage:damage2}],tag)),text}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration822BladeAllyConsolidation extends MigrationBase{static{__name(this,"Migration822BladeAllyConsolidation")}static{__name2(this,"Migration822BladeAllyConsolidation")}static version=.822;#rename(text){return text.replace(/\bfeat-effects\.Effect: Blade Ally Anarchic Rune\b/g,"equipment-srd.Anarchic").replace(/\bfeat-effects\.xLXFK4mtzgAF4zvx\b/g,"equipment-srd.65YL6nk1jIzCWutt").replace(/\bfeat-effects\.Effect: Blade Ally Axiomatic Rune\b/g,"equipment-srd.Axiomatic").replace(/\bfeat-effects\.ZzE6jPbCyUqEqhcb\b/g,"equipment-srd.6xu6dPIaUZ7edKEB").replace(/\bfeat-effects\.Effect: Blade Ally Disrupting Rune\b/g,"equipment-srd.Disrupting").replace(/\bfeat-effects\.eippbzuocVM6ftcj\b/g,"equipment-srd.LwQb7ryTC8FlOXgX").replace(/\bfeat-effects\.Effect: Blade Ally Fearsome Rune\b/g,"equipment-srd.Fearsome").replace(/\bfeat-effects\.6LgJB4ypaSTWSJLu\b/g,"equipment-srd.P6v2AtJw7AUwaDzf").replace(/\bfeat-effects\.Effect: Blade Ally Flaming Rune\b/g,"equipment-srd.Flaming").replace(/\bfeat-effects\.YxYr18vleIt2t3RS\b/g,"equipment-srd.XszNvxnymWYRaoTp").replace(/\bfeat-effects\.Effect: Blade Ally Holy Rune\b/g,"equipment-srd.Holy").replace(/\bfeat-effects\.l98IthkklgLDJXIo\b/g,"equipment-srd.DH0kB9Wbr5pDeunX").replace(/\bfeat-effects\.Effect: Blade Ally Keen Rune\b/g,"equipment-srd.Keen").replace(/\bfeat-effects\.Gf7h44DcTB43464h\b/g,"equipment-srd.hg3IogR8ue2IWwgS").replace(/\bfeat-effects\.Effect: Blade Ally Unholy Rune\b/g,"equipment-srd.Unholy").replace(/\bfeat-effects\.rGSc2PtvU3mgm18S\b/g,"equipment-srd.gmMrJREf4JSHd2dZ").replace(/\bfeat-effects\.Effect: Blade Ally Ghost Touch Rune\b/g,"equipment-srd.Ghost Touch").replace(/\bfeat-effects\.Rgio0hasm2epEMfh\b/g,"equipment-srd.JQdwHECogcTzdd8R").replace(/\bfeat-effects\.Effect: Blade Ally Disrupting Rune (Greater)\b/g,"equipment-srd.Disrupting (Greater)").replace(/\bfeat-effects\.HjfIXg5btodThCTW\b/g,"equipment-srd.oVrVzML63VFvVfKk")}async updateItem(source){source.system.description.value.includes("feat-effects")&&(source.system.description.value=this.#rename(source.system.description.value))}}class Migration823HeritageAncestrySlug extends MigrationBase{static{__name(this,"Migration823HeritageAncestrySlug")}static{__name2(this,"Migration823HeritageAncestrySlug")}static version=.823;async updateItem(source){if(source.type!=="heritage"||!source.system.ancestry||source.system.ancestry.slug)return;const ancestry=await fromUuid(source.system.ancestry.uuid);source.system.ancestry.slug=ancestry instanceof AncestryPF2e?ancestry.slug??sluggify(ancestry.name):sluggify(source.system.ancestry.name)}}class Migration824SneakAttackDamageSource extends MigrationBase{static{__name(this,"Migration824SneakAttackDamageSource")}static{__name2(this,"Migration824SneakAttackDamageSource")}static version=.824;async updateItem(source){if(source.type==="feat")switch(source.system.slug){case"sneak-attack":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",predicate:["class:rogue"],value:"ternary(lt(@actor.level, 5), 1, ternary(lt(@actor.level, 11), 2, ternary(lt(@actor.level, 17), 3, 4)))"},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",predicate:["class:rogue"],value:6},{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",predicate:["target:condition:flat-footed",{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]}]}],selector:"strike-damage"},{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}];source.system.rules=rules;return}case"ruffian":{const rules=[{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",label:"PF2E.SpecificRule.SneakAttack",predicate:["target:condition:flat-footed","item:category:simple",{nor:[{and:["item:ranged",{not:"item:thrown-melee"}]},"item:trait:agile","item:trait:finesse"]}],selector:"strike-damage"},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.medium.rank",value:1},{key:"ActiveEffectLike",mode:"upgrade",path:"system.skills.itm.rank",value:1},{key:"CriticalSpecialization",predicate:["target:condition:flat-footed","item:category:simple",{lte:["item:damage:die:faces",8]}]}];source.system.rules=rules;return}case"sneak-attacker":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",value:1},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",value:"ternary(lt(@actor.level, 6), 4, 6)"},{key:"GrantItem",uuid:"Compendium.pf2e.classfeatures.Sneak Attack"}];source.system.rules=rules;return}case"butterflys-sting":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",value:1},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",value:6},{key:"GrantItem",uuid:"Compendium.pf2e.classfeatures.Sneak Attack"},{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}];source.system.rules=rules;return}case"magical-trickster":{const rules=[{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",predicate:["item:trait:attack","target:condition:flat-footed"],selector:"spell-damage"}];source.system.rules=rules;return}}}}class Migration825KhakkharaFengHuoLun extends MigrationBase{static{__name(this,"Migration825KhakkharaFengHuoLun")}static{__name2(this,"Migration825KhakkharaFengHuoLun")}static version=.825;async updateItem(source){if(source.img.endsWith("icons/equipment/weapons/khakkara.webp")&&(source.img=source.img.replace("khakkara.webp","khakkhara.webp")),source.type==="weapon"){const fixBaseItemAndSlug=__name2((oldId,newId)=>{source.system.baseItem===oldId&&(source.system.baseItem=newId),source.system.slug===oldId&&(source.system.slug=newId)},"fixBaseItemAndSlug");fixBaseItemAndSlug("khakkara","khakkhara"),fixBaseItemAndSlug("wind-and-fire-wheel","feng-huo-lun")}else if(source.type==="feat"){const oldLink="@UUID[Compendium.pf2e.equipment-srd.Khakkara]",newLink="@UUID[Compendium.pf2e.equipment-srd.Khakkhara]";source.system.description.value=source.system.description.value.replace(oldLink,newLink);for(const rule of source.system.rules)rule.key==="ActiveEffectLike"&&"path"in rule&&rule.path==="system.martial.weapon-base-khakkara.rank"&&(rule.path="system.martial.weapon-base-khakkhara.rank")}}}class Migration826GutConditionData extends MigrationBase{static{__name(this,"Migration826GutConditionData")}static{__name2(this,"Migration826GutConditionData")}static version=.826;async updateItem(source){if(source.type!=="condition")return;const system=source.system,topLevel=["active","base","removable","hud","modifiers","sources","alsoApplies"];for(const key of topLevel)key in system&&(delete system[key],system[`-=${key}`]=null);const valueData=system.value;for(const key of["immutable","modifiers"])key in valueData&&(delete valueData[key],valueData[`-=${key}`]=null);const durationData=system.duration;for(const key of["perpetual","text"])key in durationData&&(delete durationData[key],durationData[`-=${key}`]=null);system.group||=null}}class Migration827FixTVShieldTraits extends MigrationBase{static{__name(this,"Migration827FixTVShieldTraits")}static{__name2(this,"Migration827FixTVShieldTraits")}static version=.827;async updateItem(source){if(source.type!=="armor")return;const traits=source.system.traits;switch(source.system.slug){case"dart-shield":{traits.value=["launching-dart"];return}case"klar":{traits.value=["integrated-1d6-s-versatile-p"];return}case"meteor-shield":{traits.value=["shield-throw-30"];return}case"razor-disc":{traits.value=["integrated-1d6-s","shield-throw-20"];return}}}}class Migration828PruneInvalidTraits extends MigrationBase{static{__name(this,"Migration828PruneInvalidTraits")}static{__name2(this,"Migration828PruneInvalidTraits")}static version=.828;async updateActor(source){const traits=source.system.traits;if(traits)switch(source.type){case"character":case"npc":{traits.value=traits.value.filter(t=>t in creatureTraits);return}case"hazard":{traits.value=traits.value.filter(t=>t in hazardTraits);return}case"vehicle":{traits.value=traits.value.filter(t=>t in vehicleTraits);return}}}async updateItem(source){const traits=source.system.traits;if(!(!traits?.value||!Array.isArray(traits.value)))switch(traits.value=traits.value.filter(t=>typeof t=="string"),source.type){case"action":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory").replace(/^concentration$/,"concentrate").replace(/^(interact|manipulation)$/i,"manipulate").replace(/^vocal$/,"verbal")).filter(t=>t.startsWith("hb_")||t in actionTraits);return}case"affliction":case"effect":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in actionTraits||t in spellTraits);return}case"ancestry":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in creatureTraits||["animal"].includes(t));return}case"armor":{traits.value=traits.value.map(t=>source.system.slug?.includes("helmsmans")?t.replace(/^shield-throw$/,"shield-throw-30"):source.system.slug?.includes("klar")?t.replace(/^integrated$/,"integrated-1d6-s-versatile-p"):t).filter(t=>t.startsWith("hb_")||t in armorTraits);return}case"backpack":case"equipment":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in equipmentTraits);return}case"consumable":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in consumableTraits);return}case"class":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in classTraits);return}case"feat":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in featTraits);return}case"melee":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in npcAttackTraits);return}case"spell":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory")).filter(t=>t.startsWith("hb_")||t in spellTraits);return}case"weapon":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in weaponTraits);return}}}}class Migration829RMRitualEntries extends MigrationBase{static{__name(this,"Migration829RMRitualEntries")}static{__name2(this,"Migration829RMRitualEntries")}static version=.829;async updateActor(source){for(const item of source.items.filter(i=>i.type==="spellcastingEntry"))item.system.prepared.value==="ritual"&&(source.items.splice(source.items.indexOf(item),1),source.type==="npc"&&(source.system.spellcasting??={},source.system.spellcasting.rituals={dc:item.system.spelldc.dc}))}async updateItem(source){!("category"in source.system)||!isObject(source.system.category)||typeof source.system.category.value!="string"||source.type==="spell"&&source.system.category.value==="ritual"&&source.system.location&&(source.system.location.value=null)}}class Migration830BarbarianRework extends MigrationBase{static{__name(this,"Migration830BarbarianRework")}static{__name2(this,"Migration830BarbarianRework")}static version=.83;async updateItem(source){source.system.description.value=this.#removeLinks(source.system.description.value);for(const rule of source.system.rules)rule.key==="ActiveEffectLike"&&"path"in rule&&(rule.path==="system.custom.modifiers.barbarian-dedication-count"||rule.path==="flags.pf2e.rollOptions.all.barbarian-dedication")&&(rule.path="flags.pf2e.barbarian.archetypeFeatCount"),rule.key==="FlatModifier"&&rule.value==="3 * @actor.system.custom.modifiers.barbarian-dedication-count"&&(rule.value="3 * @actor.flags.pf2e.barbarian.archetypeFeatCount")}#removeLinks(text){return text.replace("@UUID[Compendium.pf2e.classfeatures.vlRvOQS1HZZqSyh7]{Ape}","Ape").replace("@UUID[Compendium.pf2e.classfeatures.uGY2yddm8mZx8Yo2]{Bear}","Bear").replace("@UUID[Compendium.pf2e.classfeatures.31sPXwmEbbcvgsM9]{Bull}","Bull").replace("@UUID[Compendium.pf2e.classfeatures.vCNtX2LwlemhA3tu]{Cat}","Cat").replace("@UUID[Compendium.pf2e.classfeatures.RQUJgDjJODO775qb]{Deer}","Deer").replace("@UUID[Compendium.pf2e.classfeatures.CXZwt1e6ManeBaFV]{Frog}","Frog").replace("@UUID[Compendium.pf2e.classfeatures.OJmI1L4dhQfz8vze]{Shark}","Shark").replace("@UUID[Compendium.pf2e.classfeatures.pIYWMCNnYDQfSRQh]{Snake}","Snake").replace("@UUID[Compendium.pf2e.classfeatures.xX6KnYYgHlPGoTG6]{Wolf}","Wolf").replace("@UUID[Compendium.pf2e.classfeatures.VNbDNiWjARtGQQAs]{Black}","Black").replace("@UUID[Compendium.pf2e.classfeatures.RiOww9KMu06D7wtW]{Blue}","Blue").replace("@UUID[Compendium.pf2e.classfeatures.IezPDYlweTtwCqkT]{Green}","Green").replace("@UUID[Compendium.pf2e.classfeatures.hyHgLQCDMSrR4RfE]{Red}","Red").replace("@UUID[Compendium.pf2e.classfeatures.2esqOHCn4GcZ4zYD]{White}","White").replace("@UUID[Compendium.pf2e.classfeatures.b5rvKZQCfpgBenKJ]{Brass}","Brass").replace("@UUID[Compendium.pf2e.classfeatures.kdzIxHpzeRbdRqQA]{Bronze}","Bronze").replace("@UUID[Compendium.pf2e.classfeatures.1ZugTzJHsa94AZRW]{Copper}","Copper").replace("@UUID[Compendium.pf2e.classfeatures.3lxIGMbsPZLNEXQ7]{Gold}","Gold").replace("@UUID[Compendium.pf2e.classfeatures.Z2eWkfXblU0QxFx1]{Silver}","Silver").replace("@UUID[Compendium.pf2e.classfeatures.Ape Animal Instinct]{Ape}","Ape").replace("@UUID[Compendium.pf2e.classfeatures.Bear Animal Instinct]{Bear}","Bear").replace("@UUID[Compendium.pf2e.classfeatures.Bull Animal Instinct]{Bull}","Bull").replace("@UUID[Compendium.pf2e.classfeatures.Cat Animal Instinct]{Cat}","Cat").replace("@UUID[Compendium.pf2e.classfeatures.Deer Animal Instinct]{Deer}","Deer").replace("@UUID[Compendium.pf2e.classfeatures.Frog Animal Instinct]{Frog}","Frog").replace("@UUID[Compendium.pf2e.classfeatures.Shark Animal Instinct]{Shark}","Shark").replace("@UUID[Compendium.pf2e.classfeatures.Snake Animal Instinct]{Snake}","Snake").replace("@UUID[Compendium.pf2e.classfeatures.Wolf Animal Instinct]{Wolf}","Wolf").replace("@UUID[Compendium.pf2e.classfeatures.Black Dragon Instinct]{Black}","Black").replace("@UUID[Compendium.pf2e.classfeatures.Blue Dragon Instinct]{Blue}","Blue").replace("@UUID[Compendium.pf2e.classfeatures.Green Dragon Instinct]{Green}","Green").replace("@UUID[Compendium.pf2e.classfeatures.Red Dragon Instinct]{Red}","Red").replace("@UUID[Compendium.pf2e.classfeatures.White Dragon Instinct]{White}","White").replace("@UUID[Compendium.pf2e.classfeatures.Brass Dragon Instinct]{Brass}","Brass").replace("@UUID[Compendium.pf2e.classfeatures.Bronze Dragon Instinct]{Bronze}","Bronze").replace("@UUID[Compendium.pf2e.classfeatures.Copper Dragon Instinct]{Copper}","Copper").replace("@UUID[Compendium.pf2e.classfeatures.Gold Dragon Instinct]{Gold}","Gold").replace("@UUID[Compendium.pf2e.classfeatures.Silver Dragon Instinct]{Silver}","Silver")}}class Migration831ClericDoctrines extends MigrationBase{static{__name(this,"Migration831ClericDoctrines")}static{__name2(this,"Migration831ClericDoctrines")}static version=.831;get#cloisteredClericSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.cleric",value:{firstDoctrine:"Compendium.pf2e.classfeatures.aiwxBj5MjnafCMyn",secondDoctrine:"Compendium.pf2e.classfeatures.sa7BWfnyCswAvBVa",thirdDoctrine:"Compendium.pf2e.classfeatures.s8WEmc4GGZSHSC7q",fourthDoctrine:"Compendium.pf2e.classfeatures.vxOf4LXZcqUG3P7a",fifthDoctrine:"Compendium.pf2e.classfeatures.n9W8MjjRgPpUTvWf",finalDoctrine:"Compendium.pf2e.classfeatures.DgGefatQ4v6xT6f9"}}}get#warpriestSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.cleric",value:{firstDoctrine:"Compendium.pf2e.classfeatures.xxkszluN9icAiTO4",secondDoctrine:"Compendium.pf2e.classfeatures.D34mPo29r1J3DPaX",thirdDoctrine:"Compendium.pf2e.classfeatures.Zp81uTBItG1xlH4O",fourthDoctrine:"Compendium.pf2e.classfeatures.px3gVYp7zlEQIpcl",fifthDoctrine:"Compendium.pf2e.classfeatures.kmimy4VOaoEOgOiQ",finalDoctrine:"Compendium.pf2e.classfeatures.N1ugDqZlslxbp3Uy"}}}async updateItem(source){if(!(source.type!=="feat"||!source.system.slug)&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.cleric"))switch(source.system.slug){case"cloistered-cleric":{source.system.rules.push(this.#cloisteredClericSetFlags);break}case"warpriest":{source.system.rules.push(this.#warpriestSetFlags);break}}}}class Migration832ChoiceSetFlags extends MigrationBase{static{__name(this,"Migration832ChoiceSetFlags")}static{__name2(this,"Migration832ChoiceSetFlags")}static version=.832;async updateItem(source){const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet"&&"flag"in r&&typeof r.flag=="string");for(const choiceSet of choiceSets){const originalFlag=choiceSet.flag;if(choiceSet.flag=sluggify(choiceSet.flag,{camel:"dromedary"}),choiceSet.flag!==originalFlag){console.log(`${originalFlag} ->> ${choiceSet.flag}`);const pattern=new RegExp(String.raw`\brulesSelections\.${originalFlag}\b`,"g");source.system.rules=source.system.rules.map(r=>r.key==="ChoiceSet"?r:recursiveReplaceString(r,s=>s.replace(pattern,`rulesSelections.${choiceSet.flag}`)))}}}}class Migration833AddRogueToysFixPrecision extends MigrationBase{static{__name(this,"Migration833AddRogueToysFixPrecision")}static{__name2(this,"Migration833AddRogueToysFixPrecision")}static version=.833;async updateItem(source){if(source.type!=="feat")return;const flatFootedId="game"in globalThis?"AJh5ex99aV6VTggg":"Flat-Footed";switch(source.system.slug){case"surprise-attack":{const rules=[{key:"EphemeralEffect",predicate:["encounter:round:1",{lt:["self:participant:initiative:rank","target:participant:initiative:rank"]},{or:["self:participant:initiative:stat:deception","self:participant:initiative:stat:stealth"]}],selectors:["strike-attack-roll","spell-attack-roll","strike-damage","attack-spell-damage"],uuid:`Compendium.pf2e.conditionitems.Item.${flatFootedId}`}];source.system.rules=rules;break}case"dread-striker":{const rules=[{key:"EphemeralEffect",predicate:["target:condition:frightened"],selectors:["strike-attack-roll","spell-attack-roll","strike-damage","attack-spell-damage"],uuid:`Compendium.pf2e.conditionitems.Item.${flatFootedId}`}];source.system.rules=rules;break}case"precision":{if(source.system.rules.some(r=>"damageType"in r&&r.damageType==="precision")){const rules=[{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.Ranger.HuntersEdge.FirstAttack",option:"first-attack",toggleable:!0},{category:"precision",diceNumber:"ternary(lt(@actor.level, 11), 1, ternary(lt(@actor.level, 19), 2, 3))",dieSize:"d8",key:"DamageDice",predicate:["first-attack"],selector:"strike-damage"}];source.system.rules=rules}break}}}}const FEAT_CATEGORIES=new Set(["ancestry","bonus","class","general","skill"]),FEATURE_CATEGORIES=new Set(["ancestryfeature","classfeature","curse","deityboon","pfsboon"]),FEAT_OR_FEATURE_CATEGORIES=new Set(["ancestry","ancestryfeature","bonus","class","classfeature","curse","deityboon","general","pfsboon","skill"]);class Migration834FeatCategories extends MigrationBase{static{__name(this,"Migration834FeatCategories")}static{__name2(this,"Migration834FeatCategories")}static version=.834;#updateCategoryData(system){const{traits}=system;if("featType"in system&&isObject(system.featType)){const category=system.featType.value;delete system.featType,"game"in globalThis&&(system["-=featType"]=null),category==="archetype"?(system.category=system.traits.value.includes("skill")?"skill":"class",traits.value.includes("archetype")||(traits.value.push("archetype"),traits.value.sort())):setHasElement(FEAT_OR_FEATURE_CATEGORIES,category)&&(system.category=category)}setHasElement(FEAT_OR_FEATURE_CATEGORIES,system.category)||(system.category="bonus"),system.category==="skill"&&!traits.value.includes("archetype")&&!traits.value.includes("general")&&(system.traits.value.push("general"),system.traits.value.sort())}async updateItem(source){source.type==="feat"&&this.#updateCategoryData(source.system);const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet");for(const rule of choiceSets)isObject(rule.allowedDrops)&&"predicate"in rule.allowedDrops&&Array.isArray(rule.allowedDrops.predicate)&&(rule.allowedDrops.predicate=recursiveReplaceString(rule.allowedDrops.predicate,s=>s.replace(/\bfeat(?:ure)?-type\b/,"category"))),isObject(rule.choices)&&"query"in rule.choices&&typeof rule.choices.query=="string"&&(rule.choices.query=rule.choices.query.replace('"featType.value":"archetype"','"category":"class"').replace("featType.value","category"))}}class Migration835InitiativeLongform extends MigrationBase{static{__name(this,"Migration835InitiativeLongform")}static{__name2(this,"Migration835InitiativeLongform")}static version=.835;async updateActor(actor){if(!("initiative"in actor.system.attributes))return;const initiative=actor.system.attributes.initiative;if(!initiative||!initiative.ability)return;const ability=initiative.ability;objectHasKey(SKILL_DICTIONARY,ability)?initiative.statistic=SKILL_DICTIONARY[ability]:initiative.statistic="perception",delete initiative.ability,initiative["-=ability"]=null}}class Migration836EnergizingConsolidation extends MigrationBase{static{__name(this,"Migration836EnergizingConsolidation")}static{__name2(this,"Migration836EnergizingConsolidation")}static version=.836;#rename(text){const newEffectEnergizingRune="equipment-effects.R5ywXEYZFV1WBe8t";return text.replace("equipment-effects.ClsVhp5baFRjZQ23",newEffectEnergizingRune).replace("equipment-effects.68xcDyxsNgD3JddD",newEffectEnergizingRune).replace("equipment-effects.9BsFdrEc7hkPWgSd",newEffectEnergizingRune).replace("equipment-effects.ascxqSlMEN9R6OOy",newEffectEnergizingRune).replace("equipment-effects.4RnEUeYEzC919GZR",newEffectEnergizingRune)}async updateItem(source){source.system.description.value.includes("equipment-effects")&&(source.system.description.value=this.#rename(source.system.description.value))}}class Migration837MoveHazardBookSources extends MigrationBase{static{__name(this,"Migration837MoveHazardBookSources")}static{__name2(this,"Migration837MoveHazardBookSources")}static version=.837;async updateActor(source){if(source.type==="hazard"&&isObject(source.system.source)){const value=typeof source.system.source.value=="string"?source.system.source.value:"",author=typeof source.system.source.author=="string"?source.system.source.author:"";source.system.details.source={value,author},"game"in globalThis?source.system["-=source"]=null:delete source.system.source}}}class Migration838StrikeAttackRollSelector extends MigrationBase{static{__name(this,"Migration838StrikeAttackRollSelector")}static{__name2(this,"Migration838StrikeAttackRollSelector")}static version=.838;async updateItem(source){Array.isArray(source.system.rules)||(source.system.rules=[]);for(const rule of source.system.rules)"selector"in rule&&(rule.selector==="mundane-attack"?rule.selector="strike-attack-roll":Array.isArray(rule.selector)&&(rule.selector=rule.selector.map(s=>s==="mundane-attack"?"strike-attack-roll":s)))}}class Migration839ActionCategories extends MigrationBase{static{__name(this,"Migration839ActionCategories")}static{__name2(this,"Migration839ActionCategories")}static version=.839;async updateItem(source,actorSource){if(source.type!=="action")return;const system=source.system;if(system.actionCategory){const npcCategories=["offensive","defensive","interaction"],oldValue=system.actionCategory.value||null,mustBeNull=oldValue&&npcCategories.includes(oldValue)&&actorSource&&actorSource.type!=="npc";system.category=mustBeNull?null:oldValue,delete system.actionCategory,system["-=actionCategory"]=null}}}class Migration840ArrayWrapPredicates extends MigrationBase{static{__name(this,"Migration840ArrayWrapPredicates")}static{__name2(this,"Migration840ArrayWrapPredicates")}static version=.84;#wrapPredicate(predicate){if(Array.isArray(predicate))return predicate;const arrayWrapped=[predicate];return predicate&&PredicatePF2e.isValid(arrayWrapped)?arrayWrapped:void 0}async updateItem(source){for(const rule of source.system.rules)"predicate"in rule&&(rule.predicate=this.#wrapPredicate(rule.predicate)),"definition"in rule&&(rule.definition=this.#wrapPredicate(rule.definition))}}class Migration841V11UUIDFormat extends MigrationBase{static{__name(this,"Migration841V11UUIDFormat")}static{__name2(this,"Migration841V11UUIDFormat")}static version=.841;#replaceUUID(uuid,explicitDocType){if(typeof uuid!="string"||!uuid.startsWith("Compendium."))return uuid;const documentType=(()=>{if(explicitDocType)return explicitDocType;if("game"in globalThis){const{collection}=foundry.utils.parseUuid(uuid)??{};return collection instanceof CompendiumCollection?collection.metadata.type??null:null}return null})();if(!documentType)return uuid;const parts=uuid.split(/\.(?! )/);if(parts.length!==4)return uuid;const[head,scope,pack,id]=parts;return`${head}.${scope}.${pack}.${documentType}.${id}`}#replaceUUIDsInLinks(text){return typeof text!="string"?text:Array.from(text.matchAll(/(?<=@UUID\[)[^\]]+(?=\])/g)).reduce((replaced,[link])=>replaced.replace(link,s=>this.#replaceUUID(s)),text)}async updateActor(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=this.#replaceUUID(source.flags.core.sourceId,"Actor")),source.type==="character"){if(isObject(source.system.crafting)&&Array.isArray(source.system.crafting.formulas))for(const formula of source.system.crafting.formulas)formula.uuid=this.#replaceUUID(formula.uuid,"Item")}else if(source.type==="npc"){const{details}=source.system;details.publicNotes&&=this.#replaceUUIDsInLinks(details.publicNotes),details.privateNotes&&=this.#replaceUUIDsInLinks(details.privateNotes)}else if(source.type==="hazard"){const{details}=source.system;details.reset&&=this.#replaceUUIDsInLinks(details.reset),details.description&&=this.#replaceUUIDsInLinks(details.description),details.routine&&=this.#replaceUUIDsInLinks(details.routine),details.disable&&=this.#replaceUUIDsInLinks(details.disable)}}async updateItem(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=this.#replaceUUID(source.flags.core.sourceId,"Item")),source.system.rules=source.system.rules.map(rule=>("text"in rule&&typeof rule.text=="string"&&(rule.text=this.#replaceUUIDsInLinks(rule.text)),recursiveReplaceString(rule,s=>this.#replaceUUID(s,"Item")))),itemIsOfType(source,"ancestry","background","class","kit")){const items=source.system.items;for(const entry of Object.values(items))if(entry.uuid=this.#replaceUUID(entry.uuid,"Item"),isObject(entry.items))for(const subentry of Object.values(entry.items))subentry.uuid=this.#replaceUUID(subentry.uuid,"Item")}else if(source.type==="heritage")source.system.ancestry?.uuid&&(source.system.ancestry.uuid=this.#replaceUUID(source.system.ancestry.uuid,"Item"));else if(source.type==="deity")for(const[key,spell]of Object.entries(source.system.spells))source.system.spells[Number(key)]=this.#replaceUUID(spell);const{description}=source.system;description.value??="",description.value=this.#replaceUUIDsInLinks(description.value),description.value=description.value.replace(/Compendium\.pf2e\.journals\.(?!JournalEntry)/g,"Compendium.pf2e.journals.JournalEntry."),description.gm&&=this.#replaceUUIDsInLinks(description.gm)}async updateJournalEntry(source){for(const page of source.pages)page.text.content&&=this.#replaceUUIDsInLinks(page.text.content)}}class Migration842NumifyNumericSettings extends MigrationBase{static{__name(this,"Migration842NumifyNumericSettings")}static{__name2(this,"Migration842NumifyNumericSettings")}static version=.842;async migrate(){for(const setting of["staminaVariant","worldClock.timeConvention"]){const value=game.settings.storage.get("world").getItem(`pf2e.${setting}`);value!==null&&typeof value!="number"&&await game.settings.set("pf2e",setting,Number(value))}}}class Migration843RMArmorCustomModifiers extends MigrationBase{static{__name(this,"Migration843RMArmorCustomModifiers")}static{__name2(this,"Migration843RMArmorCustomModifiers")}static version=.843;async updateActor(source){if(source.type==="character"&&source.system.customModifiers?.armor){const customModifiers=source.system.customModifiers;customModifiers["-=armor"]=null}}}class Migration844DeityDomainUUIDs extends MigrationBase{static{__name(this,"Migration844DeityDomainUUIDs")}static{__name2(this,"Migration844DeityDomainUUIDs")}static version=.844;#updateUUIDs(text){return this.#idMap.reduce((oldText,data)=>{const pattern=new RegExp(String.raw`\bCompendium\.pf2e\.domains\.(?:JournalEntry?\.)?(?:${data.oldId}|${data.name})\](?:\{[^}]+})?`,"g");return oldText.replace(pattern,`Compendium.pf2e.journals.JournalEntry.EEZvDB1Z7ezwaxIr.JournalEntryPage.${data.pageId}]{${data.name}}`)},text)}async updateActor(source){source.type==="npc"&&(source.system.details.publicNotes&&=this.#updateUUIDs(source.system.details.publicNotes))}async updateItem(source){source.system.description.gm&&=this.#updateUUIDs(source.system.description.gm),source.system.description.value&&=this.#updateUUIDs(source.system.description.value)}#idMap=[{oldId:"0cbxczrql4MwAHwV",name:"Glyph Domain",pageId:"9g1dNytABTpmmGkG"},{oldId:"1BU8deh48XZFclWl",name:"Healing Domain",pageId:"A7vErdGAweYsFcW8"},{oldId:"1NHV4ujqoR2JVWpY",name:"Travel Domain",pageId:"bTujFcUut9RX4GCy"},{oldId:"1aoUqGYDrdpnPWio",name:"Family Domain",pageId:"SAnmegCTIqGW9S7S"},{oldId:"41qaGiMit8nDP4xv",name:"Abomination Domain",pageId:"qMS6QepvY7UQQjcr"},{oldId:"6klWznsb0f2bNg3T",name:"Void Domain",pageId:"xLxrtbsj4acqgsyC"},{oldId:"8ITGLquhimrr9CNv",name:"Indulgence Domain",pageId:"GiuzDTtkQAgtGW6n"},{oldId:"8pPvbTMZLIsvCwQk",name:"Darkness Domain",pageId:"CM9ZqWwl7myKn2X1"},{oldId:"9blxcDLIRPWenK5f",name:"Plague Domain",pageId:"hGoWOjdsUz16oJUm"},{oldId:"9tsJg13xeJLGzzGV",name:"Undeath Domain",pageId:"RIlgBuWGfHC1rzYu"},{oldId:"AaY3BmDItGry4oac",name:"Decay Domain",pageId:"cAxBEZsej32riaY5"},{oldId:"B40VxP6oZ0mIR4PS",name:"Fate Domain",pageId:"EC2eB0JglDG5j1gT"},{oldId:"BlovCvjhk4Ag07w2",name:"Dreams Domain",pageId:"0wCEUwABKPdKPj8e"},{oldId:"FJ9D4qpeRhJvjHai",name:"Star Domain",pageId:"6bDpXy7pQdGrd2og"},{oldId:"HYe7Yv1fYUANVVI3",name:"Death Domain",pageId:"798PFdS8FmefcOl0"},{oldId:"HpZ4NQIqBRcFihyE",name:"Wealth Domain",pageId:"mJBp4KIszuqrmnp5"},{oldId:"J7K7kHoIE69558Su",name:"Freedom Domain",pageId:"5MjSsuKOLBoiL8FB"},{oldId:"KXFxeEyD6MmJ3a6V",name:"Naga Domain",pageId:"QzsUe3Rt3SifTQvb"},{oldId:"KzuJAIWdjwoPjHkc",name:"Secrecy Domain",pageId:"S1gyomjojgtCdxc3"},{oldId:"M7koZH0zimcMgRDb",name:"Destruction Domain",pageId:"AOQZjqgfafqqtHOB"},{oldId:"MRHDhBQvgJhDZ1zq",name:"Cities Domain",pageId:"QSk78hQR3zskMlq2"},{oldId:"MktBsoHR9HsKrbbr",name:"Zeal Domain",pageId:"DI3MYGIK8iEycanU"},{oldId:"NA4v0iwIPgkde8DP",name:"Ambition Domain",pageId:"yaMJsfYZmWJLqbFE"},{oldId:"NEI4MDBGNjEtOEIy",name:"Introspection Domain",pageId:"qjnUXickBOBDBu2N"},{oldId:"O1qeC0mIufSf3wv5",name:"Passion Domain",pageId:"ajCEExOaxuB4C1tY"},{oldId:"OsM8NfP408uB6yTi",name:"Wyrmkin Domain",pageId:"nuywscaiVGXLQpZ1"},{oldId:"PrFvU65ewfst69Mp",name:"Water Domain",pageId:"U8WVR6EDfmUaMCbu"},{oldId:"TpFgfwcWrfT8zVMP",name:"Pain Domain",pageId:"FtW1gtbHgO0KofPl"},{oldId:"WrmaTmOHojfhiENF",name:"Truth Domain",pageId:"lgsJz7mZ1OTe340e"},{oldId:"X7MkBRJGUIp91k6f",name:"Sorrow Domain",pageId:"5TqEbLR9QT3gJGe3"},{oldId:"Xs6XznYHOZyQ0hJl",name:"Tyranny Domain",pageId:"T0JHj79aGphlZ4Mt"},{oldId:"Y2kOBQydrsSqGCyn",name:"Magic Domain",pageId:"DS95vr2zmTsjsMhU"},{oldId:"YQ6IT8DgEpqvOREx",name:"Might Domain",pageId:"MOVMHZU1SfkhNN1K"},{oldId:"ZAx1RUB376BjNdlF",name:"Repose Domain",pageId:"CbsAiY68e8n5vVVN"},{oldId:"Ze2hoTyOQHbaQ6jD",name:"Air Domain",pageId:"T2y0vuYibZCL7CH0"},{oldId:"ZyFTUCbA0zYrzynD",name:"Creation Domain",pageId:"ydbCjJ9PPmRzZhDN"},{oldId:"a0fe0kFowMMwUFZa",name:"Nightmares Domain",pageId:"R20JXF43vU5RQyUj"},{oldId:"c9odhpRoKId5dXmn",name:"Perfection Domain",pageId:"Czi3XXuNOSE7ISpd"},{oldId:"dnljU1twPjH4KFgO",name:"Swarm Domain",pageId:"rd0jQwvTK4jpv95o"},{oldId:"fVfFKKvGocG2JM5q",name:"Toil Domain",pageId:"EQfZepZX6rxxBRqG"},{oldId:"fqr2OnTww3bAq0ae",name:"Sun Domain",pageId:"CkBvj5y1lAm1jnsc"},{oldId:"giUsAWI9NbpdeUzl",name:"Knowledge Domain",pageId:"0GwpYEjCHWyfQvgg"},{oldId:"i4UU3qCjIMwejIQF",name:"Delirium Domain",pageId:"tuThzOCvMLbRVba8"},{oldId:"jWmGQxJvKh5y5zfB",name:"Protection Domain",pageId:"Dx47K8wpx8KZUa9S"},{oldId:"l2EFJssJKu7rG77m",name:"Luck Domain",pageId:"L11XsA5G89xVKlDw"},{oldId:"mBvjWSvg7UYdS9TL",name:"Moon Domain",pageId:"Y3DFBCWiM9GBIlfl"},{oldId:"p5Q5RGl1lKgs5DZZ",name:"Soul Domain",pageId:"rtobUemb6vF2Yu3Y"},{oldId:"rIDXRIdb9m2E3qC6",name:"Earth Domain",pageId:"zkiLWWYzzqoxmN2J"},{oldId:"rIZ7OoG8c4Cct42M",name:"Vigil Domain",pageId:"StXN6IHR6evRaeXF"},{oldId:"udASTZy5jJWFCt5w",name:"Time Domain",pageId:"3P0NWwP3s7bIiidH"},{oldId:"unN0otycQZanf3va",name:"Duty Domain",pageId:"uGQKjk2w4whzomky"},{oldId:"uy8GUGIOmEUNqIhH",name:"Trickery Domain",pageId:"xJtbGqoz3BcCjUik"},{oldId:"v4SDXgCuPdZqhMeL",name:"Fire Domain",pageId:"egSErNozlL3HRK1y"},{oldId:"wCPGej4ZwdKCNtym",name:"Change Domain",pageId:"7xrNAgAnBqBgE3yM"},{oldId:"wPtGuF1bh4wvKE6Q",name:"Confidence Domain",pageId:"flmxRzGxN2rRNyxZ"},{oldId:"xYx8UD0JnFyBHGhJ",name:"Nature Domain",pageId:"wBhgIgt47v9uspp3"},{oldId:"y3TTKFLPbP09HZUW",name:"Cold Domain",pageId:"jq9O1tl76g2AzLOh"},{oldId:"ywn4ODaUt382Z3Nz",name:"Lightning Domain",pageId:"Kca7UPuMm44tOo9n"},{oldId:"zec5N7EnDJANGHmy",name:"Dust Domain",pageId:"6qTjtFWaBO5b60zJ"}]}class Migration845EmptySpellConsumables extends MigrationBase{static{__name(this,"Migration845EmptySpellConsumables")}static{__name2(this,"Migration845EmptySpellConsumables")}static version=.845;async preUpdateItem(source){if(source.type==="consumable"){const spell=source.system.spell;isObject(spell)&&!["_id","name","type","system"].every(p=>p in spell)&&(source.system.spell=null)}}}class Migration846SpellSchoolOptional extends MigrationBase{static{__name(this,"Migration846SpellSchoolOptional")}static{__name2(this,"Migration846SpellSchoolOptional")}static version=.846;async updateItem(source){if(source.type!=="spell")return;const system=source.system;if(system.school){const traits=system.traits;traits.value=uniq(compact([...source.system.traits.value,system.school.value])),system["-=school"]=null,delete system.school}}}class Migration847TempHPRuleEvents extends MigrationBase{static{__name(this,"Migration847TempHPRuleEvents")}static{__name2(this,"Migration847TempHPRuleEvents")}static version=.847;async updateItem(source){const rules=source.system.rules.filter(r=>r.key==="TempHP");for(const rule of rules)rule.onCreate!==void 0&&(rule.events??={},rule.events.onCreate=rule.onCreate,delete rule.onCreate),rule.onTurnStart!==void 0&&(rule.events??={},rule.events.onTurnStart=rule.onTurnStart,delete rule.onTurnStart)}}class Migration848NumericArmorProperties extends MigrationBase{static{__name(this,"Migration848NumericArmorProperties")}static{__name2(this,"Migration848NumericArmorProperties")}static version=.848;#oldToNew=[["armor","acBonus"],["dex","dexCap"],["check","checkPenalty"],["speed","speedPenalty"],["strength","strength"]];async updateItem(source){if(source.type==="armor")for(const[oldKey,newKey]of this.#oldToNew){const oldProperty=source.system[oldKey],newProperty=isObject(source.system[newKey])?0:source.system[newKey]??0;if(isObject(oldProperty)&&newProperty===0)if(delete source.system[oldKey],oldKey==="strength"){const value=Number(oldProperty.value)||null;source.system[newKey]=value===null?null:Math.max(Math.floor((value-10)/2),0)}else tupleHasValue(["checkPenalty","speedPenalty"],newKey)?(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null):(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null)}}}class Migration849DeleteBrokenThreshold extends MigrationBase{static{__name(this,"Migration849DeleteBrokenThreshold")}static{__name2(this,"Migration849DeleteBrokenThreshold")}static version=.849;async updateItem(source){const hitPoints="hp"in source.system&&isObject(source.system.hp)?source.system.hp:null;isObject(hitPoints)&&"brokenThreshold"in hitPoints&&(delete hitPoints.brokenThreshold,hitPoints["-=brokenThreshold"]=null)}}class Migration850FlatFootedToOffGuard extends MigrationBase{static{__name(this,"Migration850FlatFootedToOffGuard")}static{__name2(this,"Migration850FlatFootedToOffGuard")}static version=.85;#oldNamePattern=new RegExp(/\bFlat-Footed\b/g);#newName="Off-Guard";#imgPattern=/(?<=systems\/pf2e\/icons\/conditions(?:-2)?\/)flat-?footed.webp$/i;#aToAnUUIDPatern=/\ba(?= @UUID\[Compendium\.pf2e\.conditionitems\.Item\.(?:Flat-Footed|AJh5ex99aV6VTggg)\])/g;#replace(text){return text.replace(this.#imgPattern,"off-guard.webp").replace(/^flat-footed$/,"off-guard").replace(/(?<=[:.])flat-footed\b/g,"off-guard").replace(/\.Flat-Footed\b/g,".Off-Guard").replace(/\bFlatFooted\b/g,"OffGuard").replace(/\.flatFootable\b/g,".offGuardable").replace(this.#oldNamePattern,"Off-Guard").replace(/\bflatfooted\b/g,"flat-footed").replace(/\ba flat-footed\b/g,"an off-guard").replace(this.#aToAnUUIDPatern,"an").replace(/\bFlat-footed\b/g,"Off-guard").replace(/\bflat-footed\b/g,"off-guard")}async updateActor(source){source.type==="hazard"&&(source.system.details.routine&&=this.#replace(source.system.details.routine)),"attributes"in source.system&&isObject$1(source.system.attributes)&&"immunities"in source.system.attributes&&(source.system.attributes.immunities=recursiveReplaceString(source.system.attributes.immunities,s=>this.#replace(s)))}async updateItem(source){source.name=source.name.replace(this.#oldNamePattern,this.#newName),source.img=source.img.replace(this.#imgPattern,"off-guard.webp"),source.system=recursiveReplaceString(source.system,s=>this.#replace(s))}async updateJournalEntry(source){source.name!=="Remaster Changes"&&(source.name=source.name.replace(this.#oldNamePattern,this.#newName),"img"in source&&typeof source.img=="string"&&(source.img=source.img.replace(this.#imgPattern,"off-guard.webp")),source.pages=recursiveReplaceString(source.pages,s=>this.#replace(s)),"content"in source&&typeof source.content=="string"&&(source.content=this.#replace(source.content)))}}class Migration851JustInnovationId extends MigrationBase{static{__name(this,"Migration851JustInnovationId")}static{__name2(this,"Migration851JustInnovationId")}static version=.851;async updateItem(source){if(source.type!=="feat")return;source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,s=>s.replace("flags.pf2e.armorInnovationId","flags.pf2e.innovationId")));const hasAELike=source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.innovationId");if(source.system.slug==="weapon-innovation"&&!hasAELike){const reSource={key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.innovationId",value:"{item|flags.pf2e.itemGrants.weaponInnovation.id}"};source.system.rules.push(reSource)}else if(source.system.slug==="construct-innovation"&&!hasAELike){const reSource={key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.innovationId",value:null};source.system.rules.push(reSource)}else if(source.system.slug==="inventor-weapon-expertise"&&!source.system.rules.some(r=>r.key==="CriticalSpecialization")){const reSource={key:"CriticalSpecialization",predicate:["feature:weapon-innovation","item:id:{actor|flags.pf2e.innovationId}"]};source.system.rules.push(reSource)}}}class Migration852AbilityScoresToModifiers extends MigrationBase{static{__name(this,"Migration852AbilityScoresToModifiers")}static{__name2(this,"Migration852AbilityScoresToModifiers")}static version=.852;async updateActor(source){if(source.type!=="character")return;if(source.system.abilities&&Object.keys(source.system.abilities).length>0){const abilityObjects=Object.values(source.system.abilities);for(const data of abilityObjects)typeof data.value=="number"&&(data.mod=Math.min(Math.max(Math.trunc((data.value-10)/2),-5),10)||0,delete data.value,data["-=value"]=null)}else if(source.system.abilities){const systemData=source.system;delete systemData.abilities,systemData["-=abilities"]=null}const build=source.system.build??{};build.abilities&&(build.attributes=build.abilities,delete build.abilities,build["-=abilities"]=null)}async updateItem(source){const apexRules=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system\.abilities\..+\.value$/.test(r.path)&&typeof r.value=="number");for(const rule of apexRules)switch(rule.path=rule.path.replace(/\.value$/,".mod"),rule.mode){case"add":case"remove":case"subtract":rule.value=Math.min(Math.max(Math.trunc(rule.value/2),-5),10)||0;break;case"downgrade":case"override":case"upgrade":rule.value=Math.min(Math.max(Math.trunc((rule.value-10)/2),-5),10)||0;break}const otherRules=source.system.rules.filter(r=>"value"in r&&typeof r.value=="string"&&/\.abilities\.[a-z]{3}\.value\b/.test(r.value));for(const rule of otherRules)rule.value=rule.value.replace(/(?:floor\()?\(?@actor.abilities.([a-z]{3})\.value ?- ?10\) ?\/ ?2\)?/,"@actor.abilities.$1.mod").replace(/\s+/g," ").trim();if(source.system.slug==="thaumaturges-investiture"){source.system.rules=source.system.rules.filter(r=>r.key!=="ActiveEffectLike");const bracketedAELike={key:"ActiveEffectLike",mode:"upgrade",path:"system.resources.investiture.max",value:{brackets:[{end:4,start:4,value:14},{end:5,start:5,value:16},{end:6,start:6,value:18},{start:7,value:20}],field:"system.abilities.cha.mod"}};source.system.rules.push(bracketedAELike)}}}class Migration853RemasterLanguages extends MigrationBase{static{__name(this,"Migration853RemasterLanguages")}static{__name2(this,"Migration853RemasterLanguages")}static version=.853;#OLD_TO_NEW_LANGUAGES=new Map([["aquan","thalassic"],["auran","sussuran"],["ignan","pyric"],["sylvan","fey"],["terran","petran"]]);async updateActor(source){const languages=source.system.traits?.languages??{};languages?.value&&(languages.value=languages.value.map(l=>this.#OLD_TO_NEW_LANGUAGES.get(l)??l).sort())}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#OLD_TO_NEW_LANGUAGES.get(s)??s),source.type==="ancestry"&&Array.isArray(source.system.additionalLanguages?.value)&&source.system.additionalLanguages.value.sort()}}class Migration854BracketedAbilityScoresToModifiers extends MigrationBase{static{__name(this,"Migration854BracketedAbilityScoresToModifiers")}static{__name2(this,"Migration854BracketedAbilityScoresToModifiers")}static version=.854;async updateItem(source){const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system\.abilities\..+\.value$/.test(r.path)&&isObject(r.value)&&typeof r.value.field=="string"&&/^actor\|system\.abilities\.[a-z]{3}\.value$/.test(r.value.field)&&Array.isArray(r.value.brackets)&&r.value.brackets.every(b=>isObject(b)&&typeof b.value=="number"));for(const aeLike of aeLikes){aeLike.path=aeLike.path.replace(/\.value$/,".mod"),aeLike.value.field&&=aeLike.value.field.replace(/\.value$/,".mod");for(const bracket of aeLike.value.brackets)typeof bracket.start=="number"&&(bracket.start=Math.trunc((bracket.start-10)/2)),typeof bracket.end=="number"&&(bracket.end=Math.trunc((bracket.end-10)/2)),bracket.value=bracket.value/2}}}class Migration855ApexEquipmentSystemData extends MigrationBase{static{__name(this,"Migration855ApexEquipmentSystemData")}static{__name2(this,"Migration855ApexEquipmentSystemData")}static version=.855;async updateItem(source){if(source.type!=="equipment"||!source.system.traits.value.includes("apex"))return;const attributeModPattern=/^system\.abilities\.([a-z]{3})\.mod$/,isApexRE=__name2(r=>r.key==="ActiveEffectLike"&&attributeModPattern.test(String(r.path)),"isApexRE"),apexAttribute=source.system.rules.flatMap(r=>isApexRE(r)?attributeModPattern.exec(String(r.path))?.at(1):[]).shift();setHasElement(ATTRIBUTE_ABBREVIATIONS,apexAttribute)&&(source.system.apex??={attribute:apexAttribute},source.system.rules=source.system.rules.filter(r=>!isApexRE(r)))}}class Migration856NoSystemDotCustom extends MigrationBase{static{__name(this,"Migration856NoSystemDotCustom")}static{__name2(this,"Migration856NoSystemDotCustom")}static version=.856;async updateItem(source){source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,s=>s.replace(/\bsystem\.custom\.(?:modifiers\.)?([-a-z]+)/,(_match,group1)=>`flags.pf2e.${sluggify(group1,{camel:"dromedary"})}`)))}}class Migration857WeaponSpecializationRE extends MigrationBase{static{__name(this,"Migration857WeaponSpecializationRE")}static{__name2(this,"Migration857WeaponSpecializationRE")}static version=.857;async updateItem(source){const slug=source.system.slug??sluggify(source.name);source.type!=="feat"||!slug.includes("weapon-specialization")||slug.includes("eidolon-weapon-specialization")||source.system.rules.some(r=>r.slug==="weapon-specialization")||(slug.includes("greater-weapon-specialization")?source.system.rules.unshift({key:"AdjustModifier",mode:"multiply",relabel:"PF2E.GreaterWeaponSpecialization",selector:"strike-damage",slug:"weapon-specialization",value:2}):source.system.rules.unshift({hideIfDisabled:!0,key:"FlatModifier",label:"PF2E.WeaponSpecialization",predicate:[{gte:["item:proficiency:rank",2]}],selector:"strike-damage",slug:"weapon-specialization",value:2},{key:"AdjustModifier",mode:"upgrade",predicate:["item:proficiency:rank:3"],priority:0,selector:"strike-damage",slug:"weapon-specialization",value:3},{key:"AdjustModifier",mode:"upgrade",predicate:["item:proficiency:rank:4"],priority:0,selector:"strike-damage",slug:"weapon-specialization",value:4}))}}class Migration858FakeWeaponSpecialization extends MigrationBase{static{__name(this,"Migration858FakeWeaponSpecialization")}static{__name2(this,"Migration858FakeWeaponSpecialization")}static version=.858;#testHasOption(source){return source.system.rules.some(r=>r.key==="RollOption"&&"option"in r&&["feature:greater-weapon-specialization","feature:weapon-specialization"].includes(String(r.option)))}async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??sluggify(source.name);slug==="greater-weapon-specialization-barbarian"&&!this.#testHasOption(source)?source.system.rules.push({domain:"all",key:"RollOption",option:"feature:greater-weapon-specialization"}):slug==="psychic-weapon-specialization"&&!this.#testHasOption(source)&&source.system.rules.push({domain:"all",key:"RollOption",option:"feature:weapon-specialization"})}}class Migration859MaterialTypeGrade extends MigrationBase{static{__name(this,"Migration859MaterialTypeGrade")}static{__name2(this,"Migration859MaterialTypeGrade")}static version=.859;#PRECIOUS_MATERIAL_TYPES=new Set([...PRECIOUS_MATERIAL_TYPES].filter(t=>t.replace("duskwood","darkwood").replace("dawnsilver","mithral")));#hasOldMaterialData(source){return"preciousMaterial"in source.system&&isObject(source.system.preciousMaterial)&&"preciousMaterialGrade"in source.system&&isObject(source.system.preciousMaterialGrade)}async updateItem(source){if(itemIsOfType(source,"physical")&&this.#hasOldMaterialData(source)){const{preciousMaterial,preciousMaterialGrade}=source.system,type=this.#PRECIOUS_MATERIAL_TYPES.has(String(preciousMaterial?.value))?preciousMaterial?.value??null:null,grade=setHasElement(PRECIOUS_MATERIAL_GRADES,preciousMaterialGrade?.value)?preciousMaterialGrade?.value??null:null;source.system.material={type,grade},"game"in globalThis?(source.system["-=preciousMaterial"]=null,source.system["-=preciousMaterialGrade"]=null):(delete source.system.preciousMaterial,delete source.system.preciousMaterialGrade)}}}class Migration860RMGroup extends MigrationBase{static{__name(this,"Migration860RMGroup")}static{__name2(this,"Migration860RMGroup")}static version=.86;async updateItem(source){itemIsOfType(source,"armor","condition","weapon")||!("group"in source.system)||("game"in globalThis?source.system["-=group"]=null:delete source.system.group)}}class Migration861AuraColorsToAppearance extends MigrationBase{static{__name(this,"Migration861AuraColorsToAppearance")}static{__name2(this,"Migration861AuraColorsToAppearance")}static version=.861;async updateItem(source){const auraREs=source.system.rules.filter(r=>r.key==="Aura"&&"colors"in r&&isObject(r.colors));for(const rule of auraREs)rule.appearance={},typeof rule.colors?.border=="string"&&(rule.appearance.border={color:rule.colors.border}),typeof rule.colors?.fill=="string"&&(rule.appearance.highlight={color:rule.colors.fill}),delete rule.colors}}class Migration862SpecificMagicArmor extends MigrationBase{static{__name(this,"Migration862SpecificMagicArmor")}static{__name2(this,"Migration862SpecificMagicArmor")}static version=.862;#resilientRuneValues=new Map([["",0],["resilient",1],["greaterResilient",3],["majorResilient",3]]);async updateItem(source){if(source.type!=="armor"||source.system.category==="shield")return;switch(source.system.slug){case"power-suit":source.system.baseItem="power-suit";break;case"subterfuge-suit":source.system.baseItem;break;case"clothing-explorers":source.system.slug="explorers-clothing",source.name.endsWith("Clothing (Explorer's)")&&(source.name="Explorer's Clothing")}source.system.slug==="power-suit"&&(source.system.baseItem??="power-suit"),source.system.slug==="subterfuge-suit"&&(source.system.baseItem??="subterfuge-suit");const isMagical=!!("potencyRune"in source.system&&isObject$1(source.system.potencyRune)&&source.system.potencyRune.value||"resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)&&source.system.resiliencyRune.value);if(!!(source.system.baseItem&&source.system.slug)&&isMagical&&source.system.baseItem!==source.system.slug){const system=source.system;system.specific??={value:!0,material:source.system.material??null,runes:{potency:"potencyRune"in source.system&&isObject$1(source.system.potencyRune)&&source.system.potencyRune.value?Number(source.system.potencyRune?.value)||1:0,resilient:"resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)&&source.system.resiliencyRune.value?this.#resilientRuneValues.get(String(source.system.resiliencyRune?.value??""))||1:0,property:[]}}}}}class Migration863FixMisspelledOrganaizationsProperty extends MigrationBase{static{__name(this,"Migration863FixMisspelledOrganaizationsProperty")}static{__name2(this,"Migration863FixMisspelledOrganaizationsProperty")}static version=.863;async updateActor(source){if(source.type!=="character")return;const biography=source.system.details.biography;biography.organaizations!==void 0&&(biography.organizations=biography.organaizations,delete biography.organaizations,biography["-=organaizations"]=null)}}class Migration864RemoveWeaponMAP extends MigrationBase{static{__name(this,"Migration864RemoveWeaponMAP")}static{__name2(this,"Migration864RemoveWeaponMAP")}static version=.864;async updateItem(source){if(source.type==="weapon"&&isObject(source.system.MAP)){const mapValue=-1*Number(source.system.MAP.value);if(mapValue<0&&mapValue!==-5){const rule={key:"MultipleAttackPenalty",selector:"{item|id}-attack",value:mapValue};source.system.rules.push(rule)}"game"in globalThis?source.system["-=MAP"]=null:delete source.system.MAP}}}class Migration865VitalityVoid extends MigrationBase{static{__name(this,"Migration865VitalityVoid")}static{__name2(this,"Migration865VitalityVoid")}static version=.865;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/^positive$/,"vitality").replace(/^negative$/,"void").replace(/^versatile-positive$/,"versatile-vitality").replace(/^versatile-negative$/,"versatile-void").replace(/\bpositive\]/g,"vitality]").replace(/\bnegative\]/g,"void]").replace(/\[positive\b/g,"[vitality").replace(/\[negative\b/g,"[void").replace(/\bRollFlavor\.positive\b/g,"RollFlavor.vitality").replace(/\bRollFlavor\.negative\b/g,"RollFlavor.void").replace(/\bTraitPositive\b/g,"TraitVitality").replace(/\bTraitNegative\b/g,"TraitVoid").replace(/\bTraitVersatilePositive\b/g,"TraitVersatileVitality").replace(/\bTraitVersatileNegative\b/g,"TraitVersatileVoid").replace(/\bnegative negative damage\b/,"void damage"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags=this.#replaceStrings(source.flags)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags=this.#replaceStrings(source.flags)}}class Migration866LinkToActorSizeAgain extends MigrationBase{static{__name(this,"Migration866LinkToActorSizeAgain")}static{__name2(this,"Migration866LinkToActorSizeAgain")}static version=.866;async updateActor(actorSource){SIZE_LINKABLE_ACTOR_TYPES.has(actorSource.type)||actorSource.prototypeToken.flags.pf2e&&(actorSource.prototypeToken.flags.pf2e.linkToActorSize=!1,actorSource.prototypeToken.flags.pf2e.autoscale=!1)}async updateToken(tokenSource,actor){!actor||SIZE_LINKABLE_ACTOR_TYPES.has(actor.type)||foundry.utils.mergeObject(tokenSource.flags,{pf2e:{linkToActorSize:!1,autoscale:!1}})}}class Migration867DamageRollDomainFix extends MigrationBase{static{__name(this,"Migration867DamageRollDomainFix")}static{__name2(this,"Migration867DamageRollDomainFix")}static version=.867;async updateItem(source){for(const rule of source.system.rules??[])"domain"in rule&&rule.domain==="damage-roll"&&(rule.domain="damage")}}class Migration868StrikeRERange extends MigrationBase{static{__name(this,"Migration868StrikeRERange")}static{__name2(this,"Migration868StrikeRERange")}static version=.868;async updateItem(source){const strikeREs=source.system.rules.filter(r=>r.key==="Strike");for(const rule of strikeREs)typeof rule.maxRange=="number"&&rule.range!==rule.maxRange/6?rule.range={max:rule.maxRange}:typeof rule.range=="number"&&(rule.range={increment:rule.range}),delete rule.maxRange}}class Migration869RefreshMightyBulwark extends MigrationBase{static{__name(this,"Migration869RefreshMightyBulwark")}static{__name2(this,"Migration869RefreshMightyBulwark")}static version=.869;get#mightyBulwarkRules(){return[{key:"FlatModifier",predicate:["armor:trait:bulwark"],selector:"reflex",value:4},{key:"AdjustModifier",predicate:["armor:trait:bulwark"],selector:"reflex",slug:"dex",suppress:!0},{key:"AdjustModifier",selector:"reflex",slug:"bulwark",suppress:!0}]}async updateItem(source){if(source.type==="feat"&&source.system.slug==="mighty-bulwark")source.system.rules=this.#mightyBulwarkRules;else for(const rule of source.system.rules)"option"in rule&&rule.option==="self:armor:strength-requirement-met"&&(rule.option="armor:strength-requirement-met")}}class Migration870MartialToProficiencies extends MigrationBase{static{__name(this,"Migration870MartialToProficiencies")}static{__name2(this,"Migration870MartialToProficiencies")}static version=.87;#defensePathPattern=new RegExp(String.raw`system\.martial\.(?:${Array.from(ARMOR_CATEGORIES).join("|")})\.`);async updateActor(source){if(source.type!=="character")return;const systemSource=source.system,oldData=isObject(systemSource.martial)&&Object.keys(systemSource.martial).length>0?systemSource.martial:{};for(const[key,data]of Object.entries(oldData))!data.rank||["simple","unarmed","unarmored"].includes(key)&&data.rank===1||(systemSource.proficiencies??={},setHasElement(ARMOR_CATEGORIES,key)?(systemSource.proficiencies.defenses??={},systemSource.proficiencies.defenses[key]={rank:data.rank}):(systemSource.proficiencies.attacks??={},systemSource.proficiencies.attacks[key]={custom:data.custom,rank:data.rank}));"game"in globalThis&&"martial"in systemSource?systemSource["-=martial"]=null:delete systemSource.martial}async updateItem(source){source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,text=>{const key=this.#defensePathPattern.test(text)?"defenses":"attacks";return text.replace(/\bsystem\.martial\./g,`system.proficiencies.${key}.`)}))}}class Migration871MigrateRollActionMacroParams extends MigrationBase{static{__name(this,"Migration871MigrateRollActionMacroParams")}static{__name2(this,"Migration871MigrateRollActionMacroParams")}static version=.871;async updateMacro(source){if(source.type!=="script")return;const matches=source.command.matchAll(/game\.pf2e\.rollActionMacro\("(.+)".*"(.+)"\)/gm);for(const match of matches){if(match.length<3)continue;const[current,itemId,slug]=match;source.command=source.command.replace(current,`game.pf2e.rollActionMacro({ itemId: "${itemId}", slug: "${slug}" })`)}}}class Migration872MoveSchemaProperty extends MigrationBase{static{__name(this,"Migration872MoveSchemaProperty")}static{__name2(this,"Migration872MoveSchemaProperty")}static version=.872;#mvSchema(systemData){const migrations=systemData._migration??={version:null,previous:null};"schema"in systemData&&(systemData["-=schema"]=null,isObject(systemData.schema)&&typeof systemData.schema.version=="number"&&(migrations.version=systemData.schema.version))}async updateActor(source){this.#mvSchema(source.system)}async updateItem(source){this.#mvSchema(source.system)}}class Migration873RemoveBonusBulkLimit extends MigrationBase{static{__name(this,"Migration873RemoveBonusBulkLimit")}static{__name2(this,"Migration873RemoveBonusBulkLimit")}static version=.873;async updateActor(source){if(source.type!=="character"&&source.type!=="npc")return;const data=source.system;"bonusLimitBulk"in data.attributes&&(delete data.attributes.bonusLimitBulk,data.attributes["-=bonusLimitBulk"]=null),"bonusEncumbranceBulk"in data.attributes&&(delete data.attributes.bonusEncumbranceBulk,data.attributes["-=bonusEncumbranceBulk"]=null)}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,text=>text.replace(/^system\.attributes\.bonusEncumbranceBulk$/,"inventory.bulk.encumberedAfterAddend").replace(/^system\.attributes\.bonusLimitBulk$/,"inventory.bulk.maxAddend"))}}class Migration874MoveStaminaStuff extends MigrationBase{static{__name(this,"Migration874MoveStaminaStuff")}static{__name2(this,"Migration874MoveStaminaStuff")}static version=.874;async updateActor(source){if(source.type!=="character")return;const variantEnabled="game"in globalThis&&game.settings.storage.get("world").find(s=>s.key==="pf2e.staminaVariant")?.value!=='"0"'&&game.settings.get("pf2e","staminaVariant"),systemSource=source.system;if(isObject(systemSource.attributes.sp)){const value=Math.floor(Number(systemSource.attributes.sp.value))||0;value>0&&variantEnabled&&(systemSource.attributes.hp.sp={value}),delete systemSource.attributes.sp,systemSource.attributes["-=sp"]=null}if(isObject(systemSource.attributes.resolve)){const value=Math.floor(Number(systemSource.attributes.resolve.value))||0;value>0&&variantEnabled&&(systemSource.resources.resolve={value}),delete systemSource.attributes.resolve,systemSource.attributes["-=resolve"]=null}}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,text=>text.replace(/^system\.attributes\.sp\.max$/,"system.attributes.hp.sp.max").replace(/^system\.attributes\.resolve.max$/,"system.resources.resolve.max"))}async migrate(){const staminaVariant=game.settings.storage.get("world").find(s=>s.key==="pf2e.staminaVariant");["1",'"1"'].includes(staminaVariant?._source.value??"")?await game.settings.set("pf2e","staminaVariant",!0):staminaVariant&&await game.settings.set("pf2e","staminaVariant",!1),game.settings.storage.get("world").find(s=>s.key==="pf2e.proficiencyVariant")?._source.value==='"ProficiencyWithoutLevel"'?await game.settings.set("pf2e","proficiencyVariant",!0):staminaVariant&&await game.settings.set("pf2e","proficiencyVariant",!1)}}class Migration875SetInnovationIdEarly extends MigrationBase{static{__name(this,"Migration875SetInnovationIdEarly")}static{__name2(this,"Migration875SetInnovationIdEarly")}static version=.875;async updateItem(source){if(source.type!=="feat"||!["armor-innovation","weapon-innovation"].includes(source.system.slug??""))return;const aeLike=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.innovationId");aeLike&&(aeLike.priority=5)}}class Migration876FeatLevelTaken extends MigrationBase{static{__name(this,"Migration876FeatLevelTaken")}static{__name2(this,"Migration876FeatLevelTaken")}static version=.876;async updateItem(source,actorSource){if(source.type!=="feat"||!setHasElement(FEAT_CATEGORIES,source.system.category))return;const location=source.system.location??"",background=actorSource?.items.find(i=>i.type==="background");if(location===background?._id)source.system.level.taken=1;else{const levelString=/^.+-(\d+)$/.exec(location)?.[1]??"NaN";levelString&&(source.system.level.taken=Number(levelString)||void 0)}const{category,traits}=source.system;category==="skill"&&!traits.value.includes("skill")?traits.value.push("skill"):category==="general"&&!traits.value.includes("general")&&traits.value.push("general"),traits.value.sort()}}class Migration877PublicationData extends MigrationBase{static{__name(this,"Migration877PublicationData")}static{__name2(this,"Migration877PublicationData")}static version=.877;#setPublicationData(systemSource,oldData){const title=typeof oldData.value=="string"?oldData.value.trim():"",authors=typeof oldData.author=="string"?oldData.author.trim():"",license=title==="Pathfinder Player Core"?"ORC":"OGL",remaster=["Pathfinder Player Core","Pathfinder Rage of Elements"].includes(title),publication={title,authors,license,remaster};isObject$1(systemSource.details)?systemSource.details.publication=publication:systemSource.publication=publication}async updateActor(source){source.type!=="hazard"&&source.type!=="npc"&&source.type!=="vehicle"||(source.type==="vehicle"&&isObject$1(source.system.source)?(this.#setPublicationData(source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):(source.type==="hazard"||source.type==="npc")&&isObject$1(source.system.details.source)&&(this.#setPublicationData(source.system,source.system.details.source),"game"in globalThis?source.system.details["-=source"]=null:delete source.system.details.source))}async updateItem(source){if("details"in source.system&&isObject$1(source.system.details)){const oldDataInWrongPlace=source.system.details.source;isObject$1(oldDataInWrongPlace)&&typeof oldDataInWrongPlace.value=="string"&&(source.system.source={value:oldDataInWrongPlace.value.trim()}),"game"in globalThis?source.system["-=details"]=null:delete source.system.details}isObject$1(source.system.source)?(this.#setPublicationData(source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):!source.system.publication&&!("game"in globalThis)&&this.#setPublicationData(source.system,{})}}class Migration878TakeABreather extends MigrationBase{static{__name(this,"Migration878TakeABreather")}static{__name2(this,"Migration878TakeABreather")}static version=.878;async updateMacro(source){source.type==="script"&&source.command.includes("console.log(resolve, sp)")&&(source.command="game.pf2e.actions.takeABreather();")}}class Migration879DeviseAStratagemAndFriends extends MigrationBase{static{__name(this,"Migration879DeviseAStratagemAndFriends")}static{__name2(this,"Migration879DeviseAStratagemAndFriends")}static version=.879;async updateItem(source){if(source.type==="action"&&source.system.slug==="devise-a-stratagem"){const rules=[{domain:"all",key:"RollOption",option:"target:mark:devise-a-stratagem",toggleable:"totm"},{ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem",{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap"]}],selector:"strike-attack-roll",type:"ability"}];source.system.rules=rules}else if(source.type==="feat"&&source.system.slug==="athletic-strategist"){const rule={ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem",{or:["action:disarm","action:grapple","action:shove","action:trip"]},{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap",{and:["feat:takedown-expert","item:group:club","item:hands-held:1"]}]}],selector:"athletics",type:"ability"};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="ongoing-strategy"){const rule={damageCategory:"precision",key:"FlatModifier",predicate:["class:investigator",{not:"check:substitution:devise-a-stratagem"},{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap",{and:["feat:takedown-expert","item:group:club","item:hands-held:1"]}]}],selector:"strike-damage",value:{brackets:[{end:4,value:1},{end:8,start:5,value:2},{end:12,start:9,value:3},{end:16,start:13,value:4},{start:17,value:5}]}};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="shared-stratagem"){const rule={key:"Note",predicate:["target:mark:devise-a-stratagem"],selector:"strike-attack-roll",text:"PF2E.SpecificRule.Investigator.SharedStratagem.Note",title:"{item|name}",outcome:["success","criticalSuccess"]};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="takedown-expert"){const rule={ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem","item:hands-held:1"],selector:"club-group-attack-roll",type:"ability"};source.system.rules=[rule]}}}class UserPF2e extends User{static{__name(this,"UserPF2e")}static{__name2(this,"UserPF2e")}prepareData(){super.prepareData(),canvas.ready&&canvas.tokens.controlled.length>0&&game.pf2e.effectPanel.refresh()}prepareBaseData(){super.prepareBaseData(),this.flags=foundry.utils.mergeObject({pf2e:{settings:{showEffectPanel:!0,showCheckDialogs:!0,showDamageDialogs:!0,searchPackContents:!1,monochromeDarkvision:!0}}},this.flags)}get settings(){return this.flags.pf2e.settings}getActiveTokens(){return!canvas.ready||canvas.tokens.controlled.length===0?compact([game.user.character?.getActiveTokens(!0,!0).shift()]):canvas.tokens.controlled.map(t=>t.document)}clearTargets(){this.updateTokenTargets()}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),game.user.id!==userId)return;const keys2=Object.keys(foundry.utils.flattenObject(changed));keys2.includes("flags.pf2e.settings.showEffectPanel")&&game.pf2e.effectPanel.refresh(),keys2.includes("flags.pf2e.settings.monochromeDarkvision")&&canvas.ready&&(canvas.scene?.reset(),canvas.perception.update({initializeVision:!0,refreshLighting:!0},!0))}}class Migration880SplitShowDialogsSettings extends MigrationBase{static{__name(this,"Migration880SplitShowDialogsSettings")}static{__name2(this,"Migration880SplitShowDialogsSettings")}static version=.88;async migrate(){const userUpdates=game.users.contents.flatMap(user=>{const settings=user._source.flags.pf2e?.settings;return typeof settings?.showRollDialogs=="boolean"?(settings.showCheckDialogs=settings.showRollDialogs,settings.showDamageDialogs=settings.showRollDialogs,settings["-=showRollDialogs"]=null,{_id:user.id,"flags.pf2e.settings":settings}):[]});await UserPF2e.updateDocuments(userUpdates)}}class Migration881NoHBPrefix extends MigrationBase{static{__name(this,"Migration881NoHBPrefix")}static{__name2(this,"Migration881NoHBPrefix")}static version=.881;async updateActor(source){const traits=source.system.traits;if(traits?.value&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>typeof t=="string").map(t=>t.replace(/^hb_/,""))),source.type==="character"&&source.system.proficiencies?.attacks){const attacks=source.system.proficiencies.attacks;for(const[key,value]of Object.entries(attacks))key.includes("hb_")&&(attacks[key.replace("hb_","")]=value,attacks[`-=${key}`]=null)}}async updateItem(source){source.system=recursiveReplaceString(source.system,t=>t.replace(/^hb_/,""))}}class Migration882SpellDataReorganization extends MigrationBase{static{__name(this,"Migration882SpellDataReorganization")}static{__name2(this,"Migration882SpellDataReorganization")}static version=.882;#SCHOOL_TRAITS=new Set(["abjuration","conjuration","divination","enchantment","evocation","necromancy","transmutation"]);#DAMAGE_TYPES=new Set([...DAMAGE_TYPES,"good","evil","lawful","chaotic"]);#ensureTraitsPresence(system){return foundry.utils.mergeObject({value:[]},system.traits??{value:[]})}#migrateRule(rule){if("type"in rule){if(typeof rule.type=="string"&&this.#SCHOOL_TRAITS.has(rule.type))return[];Array.isArray(rule.type)&&(rule.type=rule.type.filter(t=>!this.#SCHOOL_TRAITS.has(t)))}return"traits"in rule&&Array.isArray(rule.traits)&&(rule.traits=rule.traits.filter(t=>!this.#SCHOOL_TRAITS.has(t))),Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>!this.#SCHOOL_TRAITS.has(s))),rule}async updateActor(source){const traits=source.system.traits??{value:[]};Array.isArray(traits.value)&&(traits.value=uniq(compact(traits.value).filter(t=>!this.#SCHOOL_TRAITS.has(t))).sort()),source.system.attributes.immunities=source.system.attributes.immunities?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type)),source.system.attributes.weaknesses=source.system.attributes.weaknesses?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type)),source.system.attributes.resistances=source.system.attributes.resistances?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type))}async updateItem(source,actorSource,{topLevel=!0}={}){topLevel&&source.system?.rules&&(source.system.rules=source.system.rules.flatMap(r=>r&&this.#migrateRule(r)));const traits=source.system?.traits??{value:[]};if(Array.isArray(traits.value)&&(traits.value=uniq(compact(traits.value).filter(t=>!this.#SCHOOL_TRAITS.has(t)).map(t=>t==="metamagic"?"spellshape":t).sort())),source.type!=="spell")return;const system=source.system??{};isObject(system.traditions)&&"value"in system.traditions&&Array.isArray(system.traditions.value)&&(system.traits=this.#ensureTraitsPresence(system),system.traits.traditions=[...system.traditions.value].sort()),"traditions"in system&&(system["-=traditions"]=null),system.category?.value==="focus"&&(system.traits=this.#ensureTraitsPresence(system)).value.push("focus"),isObject(system.components)&&(system.components.verbal&&(system.traits=this.#ensureTraitsPresence(system)).value.push("concentrate"),(system.components.material||system.components.somatic)&&(system.traits=this.#ensureTraitsPresence(system)).value.push("manipulate")),"components"in system&&(system["-=components"]=null),isObject(system.materials)&&typeof system.materials.value=="string"?system.requirements=system.materials.value:topLevel&&(system.requirements||=""),"materials"in system&&(system["-=materials"]=null),topLevel&&(system.duration={value:system.duration?.value??"",sustained:isObject(system.sustained)?!!system.sustained.value||system.duration?.value?.includes("sustained")||!1:system.duration?.sustained??!1}),"sustained"in system&&(system["-=sustained"]=null),isObject(system.hasCounteractCheck)?system.counteraction=!!system.hasCounteractCheck.value:topLevel&&(system.counteraction??=!1),"hasCounteractCheck"in system&&(system["-=hasCounteractCheck"]=null),isObject(system.save)&&typeof system.save?.value=="string"&&tupleHasValue(SAVE_TYPES,system.save.value)&&(system.defense={save:{statistic:system.save.value,basic:!!system.save.basic}}),topLevel&&(system.defense??=null),"save"in system&&(system["-=save"]=null);const oldSpellDamage=foundry.utils.deepClone(system.damage);if(isObject(oldSpellDamage)&&isObject$1(oldSpellDamage?.value)){system.damage={};for(const[key,partial]of Object.entries(oldSpellDamage?.value)){if(topLevel&&["lay-on-hands","touch-of-corruption"].includes(source.system?.slug??""))break;if(!isObject$1(partial))continue;const typeData=isObject$1(partial.type)?partial.type:{},damageType=this.#DAMAGE_TYPES.has(String(typeData.value))?typeData.value:topLevel?"untyped":void 0,damageCategory=setHasElement(DAMAGE_CATEGORIES_UNIQUE,typeData.subtype)?typeData.subtype:topLevel?null:void 0;system.damage[key]={applyMod:typeof partial.applyMod=="boolean"?partial.applyMod:void 0,formula:typeof partial.value=="string"?partial.value:topLevel?"":void 0,type:damageType,category:damageCategory,materials:Array.isArray(typeData.categories)?typeData.categories:topLevel?[]:void 0}}const damageWithDeletions=system.damage;for(const[key,oldValue]of Object.entries(oldSpellDamage))(key==="value"||!isObject(oldValue))&&(damageWithDeletions[`-=${key}`]=null)}if(isObject(system.spellType)){if(system.spellType.value==="attack"&&!system.traits?.value?.includes("attack"))(system.traits=this.#ensureTraitsPresence(system)).value.push("attack");else if(system.spellType.value==="heal")for(const[key,damagePartial]of Object.entries(system.damage??{}))key!=="value"&&isObject(damagePartial)&&(damagePartial.kinds=["healing"]);for(const[key,damagePartial]of Object.entries(system.damage??{}))key!=="value"&&isObject(damagePartial)&&(damagePartial.kinds??=["damage"])}if("spellType"in system&&(system["-=spellType"]=null),isObject(system.category)&&"value"in system.category&&system.category.value==="ritual"){const primaryCheck=isObject(system.primarycheck)&&typeof system.primarycheck.value=="string"?system.primarycheck.value.trim():"",secondaryChecks=isObject(system.secondarycheck)&&typeof system.secondarycheck.value=="string"?system.secondarycheck.value.trim():"",secondaryCasters=isObject(system.secondarycasters)&&Number(system.secondarycasters.value)||0;system.ritual={primary:{check:primaryCheck},secondary:{checks:secondaryChecks,casters:secondaryCasters}}}"category"in system&&(system["-=category"]=null),"primarycheck"in system&&(system["-=primarycheck"]=null),"secondarycheck"in system&&(system["-=secondarycheck"]=null),"secondarycasters"in system&&(system["-=secondarycasters"]=null);const oldKeys=["ability","areatype","damageType","prepared","rarity","spellCategorie","usage"];for(const key of oldKeys)key in system&&(system[`-=${key}`]=null);if(isObject(system.heightening)&&system.heightening.type==="fixed")for(const spellPartial of Object.values(system.heightening.levels??{}))await this.updateItem({name:source.name,type:"spell",system:spellPartial},actorSource,{topLevel:!1});for(const overlay of Object.values(system?.overlays??{}))overlay.overlayType==="override"&&await this.updateItem({name:overlay.name??source.name,type:"spell",system:overlay.system??{}},actorSource,{topLevel:!1})}}class Migration883BanishAlignment extends MigrationBase{static{__name(this,"Migration883BanishAlignment")}static{__name2(this,"Migration883BanishAlignment")}static version=.883;#ALIGNMENTS=new Set(["good","evil","lawful","chaotic"]);#migrateRule(rule){return"traits"in rule&&Array.isArray(rule.traits)&&(rule.traits=rule.traits.filter(t=>!this.#ALIGNMENTS.has(t))),Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>!this.#ALIGNMENTS.has(s))),rule}async updateActor(source){const details=source.system.details;if(isObject(details.alignment)&&typeof details.alignment.value=="string"){const traits=source.system.traits??{value:[]};switch(details.alignment.value){case"LG":traits.value.push("lawful","good");break;case"NG":traits.value.push("good");break;case"CG":traits.value.push("chaotic","good");break;case"LE":traits.value.push("lawful","evil");break;case"NE":traits.value.push("evil");break;case"CE":traits.value.push("chaotic","evil");break;case"LN":traits.value.push("lawful");break;case"CN":traits.value.push("chaotic");break}if(source.type==="npc"){if(traits.value.includes("celestial")&&traits.value.includes("good")){traits.value.push("holy");for(const item of source.items.filter(i=>i.type==="melee"))item.system.traits.value.includes("holy")||(item.system.traits.value.push("holy"),item.system.traits.value.sort())}else if(["fiend","rakshasa","undead"].some(t=>traits.value.includes(t))&&traits.value.includes("evil")&&(traits.value.push("unholy"),traits.value.includes("fiend")||traits.value.includes("rakshasa")))for(const item of source.items.filter(i=>i.type==="melee"))item.system.traits.value.includes("unholy")||(item.system.traits.value.push("unholy"),item.system.traits.value.sort())}traits.value=uniq(traits.value.sort())}"alignment"in details&&(details["-=alignment"]=null)}async updateItem(source){if(source.system.rules=source.system.rules.flatMap(r=>this.#migrateRule(r)),source.type==="deity"){const system=source.system;if("alignment"in system){const{alignment}=system;if(isObject$1(alignment)&&"follower"in alignment&&Array.isArray(alignment.follower)){const followers=alignment.follower.filter(a=>typeof a=="string"),modal=system.category==="philosophy"?null:["asmodeus","iomedae","rovagug","urgathoa"].includes(system.slug??"")?"must":"can",what=modal===null||system.slug==="pharasma"?null:system.slug==="gorum"?["holy","unholy"]:followers.some(f=>f.includes("G"))?followers.some(f=>f.includes("E"))?["holy","unholy"]:["holy"]:followers.some(f=>f.includes("E"))?["unholy"]:null;system.sanctification=modal===null||what===null?null:{modal,what}}system["-=alignment"]=null}"ability"in system&&(system.attribute=Array.isArray(system.ability)?uniq(system.ability.filter(a=>setHasElement(ATTRIBUTE_ABBREVIATIONS,a)).sort()):[],system["-=ability"]=null)}else if(source.type==="feat"&&["the-tenets-of-evil","the-tenets-of-good"].includes(source.system.slug??"")){const rule={key:"ActorTraits",add:source.system.slug==="the-tenets-of-good"?["holy"]:["unholy"]};source.system.rules=[rule]}}}class Migration884UnifiedSpellcasting extends MigrationBase{static{__name(this,"Migration884UnifiedSpellcasting")}static{__name2(this,"Migration884UnifiedSpellcasting")}static version=.884;async updateActor(source){if(source.type!=="character")return;const profs=source.system.proficiencies??null;profs?.traditions&&(profs["-=traditions"]=null)}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,value=>value.replace(/^system\.proficiencies\.traditions\.(.*)\.(\w+)$/,"system.proficiencies.spellcasting.$2"))}}class Migration885ConvertAlignmentDamage extends MigrationBase{static{__name(this,"Migration885ConvertAlignmentDamage")}static{__name2(this,"Migration885ConvertAlignmentDamage")}static version=.885;#ALIGNMENTS=new Set(["good","evil","lawful","chaotic"]);#ALIGNMENT_VERSATILE_TRAITS=Array.from(this.#ALIGNMENTS).map(dt=>`versatile-${dt}`);#migrateRule(rule){if("type"in rule){if(rule.key==="Immunity"&&typeof rule.type=="string"&&this.#ALIGNMENTS.has(rule.type))return[];if(["Weakness","Resistance"].includes(String(rule.key))&&typeof rule.type=="string"){if(["lawful","chaotic"].includes(rule.type))return[];Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>typeof s!="string"||!/^self:trait:(?:good|evil|lawful|chaotic)$/.test(s))),rule.type==="good"&&(rule.type="holy"),rule.type==="evil"&&(rule.type="unholy")}else Array.isArray(rule.type)&&(rule.type=rule.type.flatMap(t=>["lawful","chaotic"].includes(t)?[]:t==="good"?"holy":t==="evil"?"unholy":t))}return"deactivatedBy"in rule&&Array.isArray(rule.deactivatedBy)&&(rule.deactivatedBy=rule.deactivatedBy.flatMap(db=>["lawful","chaotic"].includes(db)?[]:db==="good"?"holy":db==="evil"?"unholy":db)),"damageType"in rule&&typeof rule.damageType=="string"&&(rule.damageType=this.#ALIGNMENTS.has(rule.damageType)?"spirit":rule.damageType),rule}async updateActor(source){const traits=source.type==="character"?{value:[]}:source.system.traits??{value:[]},iwrKeys=["immunities","weaknesses","resistances"],iwr=pick(source.system.attributes,iwrKeys);for(const key of iwrKeys){iwr[key]=iwr[key]?.filter(i=>!["chaotic","lawful"].includes(i.type));for(const obj of[...iwr[key]??[]])obj.type=obj.type.replace("good","holy").replace("evil","unholy"),obj.exceptions=obj.exceptions?.filter(e=>isObject(e)||!["chaotic","lawful"].includes(e)).map(e=>e==="evil"?"unholy":e==="good"?"holy":e),obj.type==="holy"?(traits.value.push(key==="immunities"?"holy":"unholy"),key==="immunities"&&iwr.immunities?.splice(iwr.immunities.indexOf(obj),1)):obj.type==="unholy"&&(traits.value.push(key==="immunities"?"unholy":"holy"),key==="immunities"&&iwr.immunities?.splice(iwr.immunities.indexOf(obj),1))}foundry.utils.mergeObject(source.system.attributes,iwr),traits.value=uniq(traits.value.sort()),traits.value.includes("holy")&&traits.value.includes("unholy")&&(traits.value=traits.value.filter(t=>!["holy","unholy"].includes(t)))}async updateItem(source,actorSource){if(source.system.rules=source.system.rules.flatMap(r=>this.#migrateRule(r)),source.type==="weapon"){const traits=source.system.traits;traits.value=compact(traits.value.map(t=>this.#ALIGNMENT_VERSATILE_TRAITS.includes(t)?"versatile-spirit":t)),this.#ALIGNMENTS.has(source.system.damage.damageType)&&(source.system.damage.damageType="spirit"),traits.value=traits.value.map(t=>t==="sanctified"?traits.value.includes("good")?"holy":"unholy":t),traits.value=uniq(traits.value.sort())}else if(source.type==="melee"){const traits=source.system.traits,actorTraits=actorSource?.system.traits??{value:[]};traits.value=compact(traits.value.map(t=>this.#ALIGNMENT_VERSATILE_TRAITS.includes(t)?"versatile-spirit":t)),traits.value.some(t=>t==="good")?(traits.value.push("holy"),actorTraits.value.push("holy")):traits.value.some(t=>t==="evil")&&(traits.value.push("unholy"),actorTraits.value.push("unholy"));const partials=source.system.damageRolls;for(const[key,partial]of Object.entries(partials)){if(!isObject(partial))continue;const damageType=partial.damageType;["chaotic","lawful"].includes(damageType)?partial.damageType="spirit":damageType==="good"?(actorTraits.value.push("holy"),/^\d+$/.test(partial.damage)?partials[`-=${key}`]=null:partial.damageType="spirit"):damageType==="evil"&&(traits.value.push("unholy"),/^\d+$/.test(partial.damage)?partials[`-=${key}`]=null:partial.damageType="spirit")}traits.value=uniq(traits.value.sort()),actorTraits.value=uniq(actorTraits.value.sort())}else if(source.type==="spell"){const damage=Object.values(source.system.damage).filter(d=>isObject(d)&&typeof d.type=="string"),traits=source.system.traits;for(const partial of damage){const damageType=partial.type;this.#ALIGNMENTS.has(damageType)&&(partial.type="spirit"),damageType==="good"?traits.value.push("holy"):damageType==="evil"&&traits.value.push("unholy")}if(traits.value=uniq(traits.value.sort()),source.system.slug==="divine-decree"){const system=source.system,damage2=Object.values(system.damage).shift();isObject(damage2)&&(damage2.type="spirit"),system["-=overlays"]=null}else try{const overlayPartials=compact(Object.values(source.system.overlays??{}).filter(o=>isObject(o)&&o.overlayType==="override").map(o=>(o.system??={})?.damage).flatMap(p=>isObject(p)?Object.values(p):[]).flat());for(const partial of overlayPartials)this.#ALIGNMENTS.has(partial.type??"")&&(partial.type="spirit")}catch(error){error instanceof Error&&console.error(error.message)}}const{description}=source.system;if(actorSource?.type==="npc"&&source.type==="action"&&source.system.actionType.value!=="passive"){const hasGoodInlineRoll=/\[good\b/.test(description.value)||/\bgood\]/.test(description.value),hasEvilInlineRoll=/\[evil\b/.test(description.value)||/\bevil\]/.test(description.value);hasGoodInlineRoll&&actorSource.system.traits.value.includes("holy")?source.system.traits.value.push("holy"):hasEvilInlineRoll&&actorSource.system.traits.value.includes("unholy")&&source.system.traits.value.push("unholy"),source.system.traits.value=uniq(source.system.traits.value.sort())}description.value=description.value.replace(/\[(?:good|evil|lawful|chaotic)\b/g,"[spirit").replace(/\b(?:good|evil|lawful|chaotic)\]/g,"spirit]").replace(/\b(\dd\d) (?:good|evil|lawful|chaotic)\b/g,"$1 spirit")}}class Migration886CrossbowGroup extends MigrationBase{static{__name(this,"Migration886CrossbowGroup")}static{__name2(this,"Migration886CrossbowGroup")}static version=.886;async updateItem(source){if(source.type==="weapon"&&source.system.group==="bow"){const otherTags=source.system.traits.otherTags??[],slug=source.system.slug??sluggify(source.name);(otherTags.includes("crossbow")||slug.includes("crossbow"))&&(source.system.group="crossbow",otherTags.includes("crossbow")&&otherTags.splice(otherTags.indexOf("crossbow"),1))}source.system.rules=recursiveReplaceString(source.system.rules,s=>s.replace(/\btag:crossbow\b/,"group:crossbow"))}}class Migration887RedirectSpellLinks extends MigrationBase{static{__name(this,"Migration887RedirectSpellLinks")}static{__name2(this,"Migration887RedirectSpellLinks")}static version=.887;#spells=[{from:{_id:"kl2q6JvBZwed4B6v",name:"Dancing Lights"},to:{_id:"WBmvzNDfpwka3qT4",name:"Light"}},{from:{_id:"hkfH9Z53hPzcOwNB",name:"Veil"},to:{_id:"i35dpZFI7jZcRoBo",name:"Illusory Disguise"}},{from:{_id:"l4LFwY7iuzX6sDXr",name:"Commune with Nature"},to:{_id:"7DN13ILADW2N9Z1t",name:"Commune"}},{from:{_id:"OyFCwQuw8XRazsNr",name:"Remove Curse"},to:{_id:"SUKaxVZW2TlM8lu0",name:"Cleanse Affliction"}},{from:{_id:"RneiyehRO6f7LP44",name:"Remove Disease"},to:{_id:"SUKaxVZW2TlM8lu0",name:"Cleanse Affliction"}},{from:{_id:"c2bTWBNO1BYX4Zfg",name:"Misdirection"},to:{_id:"PRrZ7anETWPm90YY",name:"Disguise Magic"}}];async updateItem(source){for(const spell of this.#spells){const{from,to}=spell;if("game"in globalThis){const isolatedUUID=new RegExp(String.raw`^Compendium\.pf2e\.spells-srd\.(?:Item\.)?${from._id}$`);source.system=recursiveReplaceString(source.system,s=>s.replace(isolatedUUID,`Compendium.pf2e.spells-srd.Item.${to._id}`));const{description}=source.system;description.value=description.value.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`),description.gm&&=description.gm.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`)}else{const isolatedUUID=new RegExp(String.raw`^Compendium\.pf2e\.spells-srd\.Item\.${from.name}$`);source.system=recursiveReplaceString(source.system,s=>s.replace(isolatedUUID,`Compendium.pf2e.spells-srd.Item.${to.name}`));const{description}=source.system;description.value=description.value.replaceAll(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`),description.gm&&=description.gm.replaceAll(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`)}}}async updateJournalEntry(source){for(const spell of this.#spells){const{from,to}=spell;for(const page of source.pages)page.text.content&&=page.text.content.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`),page.text.content&&=page.text.content.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`)}}}class Migration888RemasterLanguagesHeritages extends MigrationBase{static{__name(this,"Migration888RemasterLanguagesHeritages")}static{__name2(this,"Migration888RemasterLanguagesHeritages")}static version=.888;#LANGUAGE_RENAMES={abyssal:"chthonian",celestial:"empyrean",gnoll:"kholo",infernal:"diabolic"};#TRAITS_RENAMES={aasimar:"nephilim","half-elf":"aiuvarin","half-orc":"dromaar",gnoll:"gnoll",ifrit:"naari",tiefling:"nephilim"};async updateActor(source){if(source.type==="character"||source.type==="npc"){const traits=source.system.traits;traits.value=traits.value.map(t=>this.#TRAITS_RENAMES[t]??t).sort();const{languages}=traits;isObject(languages)&&Array.isArray(languages.value)&&(languages.value=languages.value.map(l=>this.#LANGUAGE_RENAMES[l]??l).sort())}}async updateItem(source){if(source.system.slug==="bloodline-genie")return;source.system=recursiveReplaceString(source.system,s=>this.#TRAITS_RENAMES[s]??this.#LANGUAGE_RENAMES[s]??s);const traits=source.system.traits??{value:[]};if(traits.value=traits.value?.map(t=>t==="kholo"?"gnoll":t),source.type==="ancestry"){const languages=source.system.languages,additionalLanguages=source.system.languages;languages.value=languages.value.map(l=>l==="gnoll"?"kholo":l),languages.value.sort(),additionalLanguages.value=additionalLanguages.value.map(l=>l==="gnoll"?"kholo":l),additionalLanguages.value.sort()}}}class Migration889RemoveFocusMaxIncreases extends MigrationBase{static{__name(this,"Migration889RemoveFocusMaxIncreases")}static{__name2(this,"Migration889RemoveFocusMaxIncreases")}static version=.889;async updateItem(source){source.type==="feat"&&["clarity-of-focus","psi-cantrips-and-amps","psychic-dedication","psi-development"].includes(source.system.slug??"")||(source.system.rules=source.system.rules.filter(r=>!("path"in r&&r.path==="system.resources.focus.max")))}}class Migration890RMClassItemClassDC extends MigrationBase{static{__name(this,"Migration890RMClassItemClassDC")}static{__name2(this,"Migration890RMClassItemClassDC")}static version=.89;async updateItem(source){if(source.type==="class"&&"classDC"in source.system){const system=source.system;system["-=classDC"]=null}}}class Migration891DruidicToWildsong extends MigrationBase{static{__name(this,"Migration891DruidicToWildsong")}static{__name2(this,"Migration891DruidicToWildsong")}static version=.891;async updateActor(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/^druidic$/,"wildsong").replace(/^Druidic$/,"Wildsong"))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/^druidic$/,"wildsong").replace(/^Druidic$/,"Wildsong")),source.system.traits?.value?.sort()}}class Migration892ChoiceSetREAdjustNameValue extends MigrationBase{static{__name(this,"Migration892ChoiceSetREAdjustNameValue")}static{__name2(this,"Migration892ChoiceSetREAdjustNameValue")}static version=.892;async updateItem(source){for(const rule of source.system.rules)rule.key==="ChoiceSet"&&"adjustName"in rule&&typeof rule.adjustName=="string"&&(rule.adjustName=rule.adjustName==="true")}}class Migration893NoHBPrefixSettings extends MigrationBase{static{__name(this,"Migration893NoHBPrefixSettings")}static{__name2(this,"Migration893NoHBPrefixSettings")}static version=.893;async migrate(){for(const key of HOMEBREW_TRAIT_KEYS){const tags=game.settings.get("pf2e",`homebrew.${key}`);if(tags.length===0)continue;const updatedTags=tags.flatMap(tag=>isObject$1(tag)&&typeof tag.id=="string"?(tag.id=tag.id.replace(/^hb_/,""),tag):[]);await game.settings.set("pf2e",`homebrew.${key}`,updatedTags)}}}class Migration894NoLayOnHandsVsUndead extends MigrationBase{static{__name(this,"Migration894NoLayOnHandsVsUndead")}static{__name2(this,"Migration894NoLayOnHandsVsUndead")}static version=.894;async updateActor(source){source.items=source.items.filter(i=>i.type!=="spell"||(i.system.slug??sluggify(i.name))!=="lay-on-hands-vs-undead")}async updateItem(source){const{description}=source.system;source.type==="effect"?description.value=description.value.replace(/@UUID\[Compendium\.pf2e\.spells-srd\.Item\.(?:Lay on Hands \(Vs\. Undead\)|IxyD7YdRbSSucxZp)\]/g,"game"in globalThis?"@UUID[Compendium.pf2e.spells-srd.Item.zNN9212H2FGfM7VS]":"@UUID[Compendium.pf2e.spells-srd.Item.Lay on Hands]"):description.value=description.value.replace(/<p>(?:<em>)?@UUID\[Compendium.pf2e.spells-srd\.(?:Item\.)?(?:Lay on Hands \(Vs\. Undead\)|IxyD7YdRbSSucxZp)\](?:<\/em>)?<\/p>\n?/g,""),source.type==="spell"&&source.system.slug==="lay-on-hands"&&(source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}},source.system.overlays?.uLuOg62dVyxvbW66?.overlayType==="override"&&source.system.overlays.uLuOg62dVyxvbW66.system?.damage?.b39tbePoPlJSzLku&&(source.system.overlays.uLuOg62dVyxvbW66.system.damage.b39tbePoPlJSzLku.kinds=["healing"]))}}class Migration895FixVariantSpellTraits extends MigrationBase{static{__name(this,"Migration895FixVariantSpellTraits")}static{__name2(this,"Migration895FixVariantSpellTraits")}static version=.895;async updateItem(source){if(source.type==="spell")switch(source.system.slug){case"harm":case"heal":this.#fixHarmHeal(source);break;case"elemental-annihilation-wave":case"horizon-thunder-sphere":this.#removeOverlayTraits(source);break;default:this.#fixOtherVariants(source)}}#fixHarmHeal(source){const damage=source.system.damage[0];isObject$1(damage)&&(damage.kinds=["damage","healing"]),source.system.slug==="heal"?source.system.traits.value=["healing","manipulate","vitality"]:source.system.traits.value=["manipulate","void"];const variants=isObject$1(source.system.overlays)?Object.values(source.system.overlays).filter(o=>isObject$1(o)&&isObject$1(o.system?.traits)&&Array.isArray(o.system?.traits.value)):[];for(const variant of variants){if(!variant.system?.traits)continue;const system=variant.system;system.time?.value==="1"?system["-=traits"]=null:(system.traits=source.system.slug==="heal"?{value:["concentrate","healing","manipulate","vitality"]}:{value:["concentrate","manipulate","void"]},system.damage?.["0"]?.formula?.includes("+")?(system.damage[0].kinds=["healing"],system.defense=null):system.time?.value==="2"&&!system.damage?.["0"]&&(system.damage={0:{kinds:["damage"]}}))}}#removeOverlayTraits(source){source.system.traits.value=uniq([...source.system.traits.value,"concentrate","manipulate"]).sort();for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};overlaySystem["-=traits"]=null}}#fixOtherVariants(source){for(const partial of Object.values(source.system.damage).filter(p=>isObject$1(p)))typeof partial.type=="string"&&(partial.type==="healing"||partial.type,partial.type||="untyped");for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};if(overlaySystem.traits?.value&&Array.isArray(overlaySystem.traits.value)){if(!compact(overlaySystem.traits.value).every(t=>["concentrate","manipulate"].includes(t)))continue;overlaySystem.traits.value=uniq([...overlaySystem.traits.value,...source.system.traits.value].sort()),equals(overlaySystem.traits.value,uniq(source.system.traits.value.sort()))&&(overlaySystem["-=traits"]=null)}}}}class Migration896HealingDomains extends MigrationBase{static{__name(this,"Migration896HealingDomains")}static{__name2(this,"Migration896HealingDomains")}static version=.896;async updateItem(source){if(["effect","feat"].includes(source.type))switch(source.system.slug){case"harming-hands":case"healing-hands":{const rule={key:"DamageDice",override:{dieSize:"d10"},predicate:[source.system.slug==="healing-hands"?"item:slug:heal":"item:slug:harm"],selector:["spell-damage","spell-healing"]};source.system.rules=[rule];break}case"effect-curse-of-outpouring-life":{const rule=source.system.rules.find(r=>r.key==="DamageDice");rule&&(rule.selector="spell-healing")}}}}class Migration897ClearLayOnHandsDamage extends MigrationBase{static{__name(this,"Migration897ClearLayOnHandsDamage")}static{__name2(this,"Migration897ClearLayOnHandsDamage")}static version=.897;async updateItem(source){if(source.type!=="spell"||!["lay-on-hands","touch-of-corruption"].includes(source.system.slug??""))return;if(source.system.defense=null,"heightening"in source.system){const system=source.system;system["-=heightening"]=null}const damage=source.system.damage;if(Object.keys(damage).length>0)for(const[key,partial]of Object.entries(damage))partial&&(damage[`-=${key}`]=null);for(const overlay of Object.values(source.system.overlays??{})){if(!isObject$1(overlay)||!isObject$1(overlay.system?.damage))continue;const damagePartials=Object.values(overlay.system?.damage??{});for(const partial of damagePartials.filter(p=>isObject$1(p)))partial?.formula==="6"?partial.kinds=["healing"]:partial.kinds=["damage"]}source.system.slug==="lay-on-hands"?source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}}:source.system.overlays??={"2a6Vm4mIjBgrzlO2":{_id:"2a6Vm4mIjBgrzlO2",name:"Touch of Corruption (Vs. Living)",overlayType:"override",sort:2,system:{damage:{Esn7klJ9WRsIFnrE:{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"void"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{Esn7klJ9WRsIFnrE:"1d6"},interval:1,type:"interval"}}},gHIOzknAtexc6GUE:{_id:"gHIOzknAtexc6GUE",name:"Touch of Corruption (Healing)",overlayType:"override",sort:1,system:{damage:{cM137DAlBX1LcWAX:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"untyped"}},heightening:{damage:{cM137DAlBX1LcWAX:"6"},interval:1,type:"interval"}}}}}}class Migration898NoHBAgain extends MigrationBase{static{__name(this,"Migration898NoHBAgain")}static{__name2(this,"Migration898NoHBAgain")}static version=.898;async updateActor(source){source.system.attributes&&=recursiveReplaceString(source.system.attributes,s=>s.replace(/\bhb_/g,""))}async updateItem(source){source.system.rules=source.system.rules.filter(r=>isObject$1(r)).map(r=>recursiveReplaceString(r,s=>s.replace(/\bhb_/g,"")))}}class Migration899ArmorShieldToShieldShield extends MigrationBase{static{__name(this,"Migration899ArmorShieldToShieldShield")}static{__name2(this,"Migration899ArmorShieldToShieldShield")}static version=.899;#KEYS_TO_REMOVE=["category","checkPenalty","dexCap","group","potencyRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4","resiliencyRune","strength","unequippedBulk"];#BASE_SHIELD_TYPES=new Set(["buckler","casters-targe","dart-shield","fortress-shield","gauntlet-buckler","harnessed-shield","heavy-rondache","hide-shield","klar","meteor-shield","razor-disc","salvo-shield","steel-shield","swordstealer-shield","tower-shield","wooden-shield"]);#SPECIFIC_BASE_ITEMS={"amaranthine-pavise":"tower-shield","arrow-catching-shield":"wooden-shield","broadleaf-shield-greater":null,"broadleaf-shield-major":null,"broadleaf-shield-true":null,"broadleaf-shield":null,"burr-shield":"wooden-shield","clockwork-shield-greater":"steel-shield","clockwork-shield":"steel-shield","cursebreak-bulwark":"tower-shield","dragonslayers-shield":"steel-shield","duelists-beacon":"buckler","exploding-shield":"wooden-shield","floating-shield-greater":"buckler","floating-shield":"buckler","force-shield":"steel-shield","forge-warden":"steel-shield","glamorous-buckler":"buckler","guardian-shield":"steel-shield","helmsmans-recourse-greater":"meteor-shield","helmsmans-recourse-major":"meteor-shield","helmsmans-recourse":"meteor-shield","highhelm-war-shield-greater":"razor-disc","highhelm-war-shield-lesser":"razor-disc","highhelm-war-shield-moderate":"razor-disc","jawbreaker-shield":null,"krakens-guard":"steel-shield","limestone-shield":"tower-shield","lions-shield":"steel-shield","martyrs-shield":"steel-shield","medusas-scream-greater":"steel-shield","medusas-scream":"steel-shield","nethysian-bulwark":"steel-shield","pillow-shield":"steel-shield","rampart-shield":"tower-shield","reflecting-shield":"buckler","reforging-shield":"steel-shield","sanguine-klar-greater":"klar","sanguine-klar":"klar","sapling-shield-greater":"buckler","sapling-shield-lesser":"buckler","sapling-shield-major":"buckler","sapling-shield-minor":"buckler","sapling-shield-moderate":"buckler","sapling-shield-true":"buckler","scale-of-igroon":null,"shining-shield":"wooden-shield","silkspinners-shield":"buckler","spellguard-shield":"steel-shield","spined-shield":"steel-shield","staff-storing-shield-greater":"wooden-shield","staff-storing-shield-major":"wooden-shield","staff-storing-shield-true":"wooden-shield","staff-storing-shield":"wooden-shield","starfall-shield":"heavy-rondache","sturdy-shield-greater":"steel-shield","sturdy-shield-lesser":"steel-shield","sturdy-shield-major":"steel-shield","sturdy-shield-minor":"steel-shield","sturdy-shield-moderate":"steel-shield","sturdy-shield-supreme":"steel-shield","turnabout-shield":"salvo-shield","warding-escutcheon-greater":"tower-shield","warding-escutcheon":"tower-shield","wovenwood-shield-greater":"wooden-shield","wovenwood-shield-lesser":"wooden-shield","wovenwood-shield-major":"wooden-shield","wovenwood-shield-minor":"wooden-shield","wovenwood-shield-moderate":"wooden-shield","wovenwood-shield-true":"wooden-shield"};async updateItem(source){if(isPhysicalData(source)&&source.type!=="backpack"){const system2=source.system;"negateBulk"in system2&&(system2["-=negateBulk"]=null)}if(this.#migrateRules(source),source.type!=="armor")return;const category=source.system.category;category!=="shield"&&(source.system.checkPenalty||=0,source.system.dexCap||=0),source.system.speedPenalty||=0;const system=source.system;if("potency"in system&&(system["-=potency"]=null),category==="shield"){source.img=source.img.replace(/\barmor\.svg$/,"shield.svg"),system.baseItem=this.#BASE_SHIELD_TYPES.has(source.system.slug??"")?source.system.slug:null,system.traits.value=system.traits.value.map(t=>t==="hefty-14"?"hefty-2":t),system.traits.integrated=system.traits.value.some(t=>t.startsWith("integrated"))?{runes:{potency:0,striking:0,property:[]},versatile:null}:null,system.usage={value:"held-in-one-hand"},system.runes={reinforcing:0},this.#validateOrRemoveMaterial(system),this.#setSpecificShieldData(system),source.type="shield";for(const key of this.#KEYS_TO_REMOVE)key in system&&(system[`-=${key}`]=null)}}#migrateRules(source){const shieldAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&r.itemType==="armor"&&Array.isArray(r.predicate)&&r.predicate.includes("item:category:shield"));for(const rule of shieldAlterations)rule.itemType="shield",rule.predicate=rule.predicate.filter(s=>s!=="item:category:shield")}#validateOrRemoveMaterial(system){if(!system.material.type){system.material.grade=null;return}if(!system.material.grade){system.material.type=null;return}const baseItem=system.baseItem??"",{type}=system.material,BUCKLERS=["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"],bucklerMaterials=["abysium","adamantine","cold-iron","darkwood","djezet","inubrix","mithral","noqual","orichalcum","siccatite","silver"],MATERIALS={buckler:bucklerMaterials,towerShield:["darkwood"],shield:[...bucklerMaterials,"keep-stone"]};["tower-shield","fortress-shield"].includes(baseItem)&&!MATERIALS.towerShield.includes(type)||BUCKLERS.includes(baseItem)&&!MATERIALS.buckler.includes(type)?(system.material.type=null,system.material.grade=null):MATERIALS.shield.includes(type)||(system.material.type=null,system.material.grade=null)}#setSpecificShieldData(system){if(system.baseItem||!system.slug)return;const setSpecific=__name2(()=>{system.specific={material:foundry.utils.deepClone(system.material),runes:{reinforcing:0},integrated:system.traits.integrated?foundry.utils.deepClone({runes:system.traits.integrated.runes}):null}},"setSpecific");switch(system.slug){case"indestructible-shield":system.baseItem="steel-shield",system.material={type:"adamantine",grade:"high"},setSpecific();break;case"kizidhars-shield":system.baseItem="wooden-shield",system.material={type:"duskwood",grade:"standard"},setSpecific();break;case"lodestone-shield":system.baseItem="steel-shield",system.material={type:"cold-iron",grade:"standard"},setSpecific();break;default:system.baseItem=this.#SPECIFIC_BASE_ITEMS[system.slug??""]??null,system.slug in this.#SPECIFIC_BASE_ITEMS&&setSpecific()}}}class Migration900ClassSpellcastingProficiency extends MigrationBase{static{__name(this,"Migration900ClassSpellcastingProficiency")}static{__name2(this,"Migration900ClassSpellcastingProficiency")}static version=.9;async updateActor(source){if(source.type==="character"&&source.system.proficiencies){const proficiencies=source.system.proficiencies;"spellcasting"in proficiencies&&(proficiencies["-=spellcasting"]=null)}}async updateItem(source){if(source.type==="class"){const aeLikeIncrease=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="system.proficiencies.spellcasting.rank");aeLikeIncrease?(source.system.spellcasting=Math.max(1,source.system.spellcasting??0),source.system.rules.splice(source.system.rules.indexOf(aeLikeIncrease),1)):["sorcerer","summoner","witch"].includes(source.system.slug??"")?source.system.spellcasting=1:source.system.spellcasting=Math.max(0,source.system.spellcasting??0)}if(source.type==="feat"){const baseRule={key:"ActiveEffectLike",mode:"upgrade",path:"system.proficiencies.spellcasting.rank"};switch(source.system.slug){case"bloodline":case"patron":source.system.rules=source.system.rules.filter(r=>r.path!=="system.proficiencies.spellcasting.rank");break;case"expert-spellcaster":source.system.rules=[{...baseRule,value:2}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"expert-spellcasting":source.system.rules=[{...baseRule,value:2}];break;case"master-spellcaster":source.system.rules=[{...baseRule,value:3}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"master-spellcasting":source.system.rules=[{...baseRule,value:3}];break;case"legendary-spellcaster":source.system.rules=[{...baseRule,value:4}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break}}}}class Migration901ReorganizeBulkData extends MigrationBase{static{__name(this,"Migration901ReorganizeBulkData")}static{__name2(this,"Migration901ReorganizeBulkData")}static version=.901;async updateItem(source){if(this.#migrateRules(source),!isPhysicalData(source))return;const system=source.system;if(system.bulk??={value:0},"equippedBulk"in system&&(["armor","backpack"].includes(source.type)&&(system.bulk.value=this.#bulkStringToNumber(system.equippedBulk)),system["-=equippedBulk"]=null,system.slug==="sack"?(system.usage={value:"held-in-one-hand"},system.bulk.value=.1):/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(system.slug??"")?system.bulk.value=1:system.slug==="sleeves-of-storage"&&(system.bulk.value=.1)),"weight"in system){if(source.type==="backpack"){const usage=system.usage?.value??"";source.system.bulk.heldOrStowed=["held-in-one-hand","held-in-two-hands"].includes(usage)?Math.max(system.bulk.value,this.#bulkStringToNumber(system.weight)):this.#bulkStringToNumber(system.weight)}else source.type!=="armor"&&(source.system.bulk.value=this.#bulkStringToNumber(system.weight));system["-=weight"]=null}"bulkCapacity"in system&&(source.type==="backpack"&&(source.system.bulk.capacity=isObject$1(system.bulkCapacity)&&Math.floor(Math.abs(Number(system.bulkCapacity.value)))||0),system["-=bulkCapacity"]=null),"negateBulk"in system&&(source.type==="backpack"&&(source.system.bulk.ignored=isObject$1(system.negateBulk)&&Math.floor(Math.abs(Number(system.negateBulk.value)))||0),system["-=negateBulk"]=null)}#migrateRules(source){const itemAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string");for(const rule of itemAlterations)(rule.itemType==="armor"&&rule.property==="bulk-worn"||rule.itemType!=="armor"&&rule.property==="bulk-value")&&(rule.property="bulk");source.system.rules=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string"?!["bulk-worn","bulk-value"].includes(r.property):!0)}#bulkStringToNumber(bulkObject){if(!isObject$1(bulkObject))return 0;const bulkString=String(bulkObject.value||"-").toLocaleUpperCase("en");switch(bulkString){case"-":return 0;case"L":return .1;default:{const numericValue=Number(bulkString);return Number.isInteger(numericValue)?Math.abs(numericValue):0}}}}class Migration902DuskwoodDawnsilver extends MigrationBase{static{__name(this,"Migration902DuskwoodDawnsilver")}static{__name2(this,"Migration902DuskwoodDawnsilver")}static version=.902;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bdarkwood\b/g,"duskwood").replace(/Darkwood\b/g,"Duskwood").replace(/\bmithral\b/g,"dawnsilver").replace(/Mithral\b/g,"Dawnsilver").replace(/\bdawnsilver(.)tree\b/g,"mithral$1tree").replace(/\bDawnsilver Tree\b/g,"Mithral Tree").replace(/\bdawnsilver(.)golem/g,"mithral$1golem").replace(/\bDawnsilver(.)golem/g,"Mithral$1golem"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration903PhysicalNumericData extends MigrationBase{static{__name(this,"Migration903PhysicalNumericData")}static{__name2(this,"Migration903PhysicalNumericData")}static version=.903;async updateItem(source){if(source.type==="armor")source.system.dexCap||=0,source.system.strength||=source.system.category==="unarmored"?null:0;else if(source.type==="backpack"){const slug=source.system.slug??"";/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(slug)&&(source.system.bulk.value||=1)}}}class Migration904UndercommonToSakvroth extends MigrationBase{static{__name(this,"Migration904UndercommonToSakvroth")}static{__name2(this,"Migration904UndercommonToSakvroth")}static version=.904;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bundercommon\b/g,"sakvroth").replace(/\bUndercommon\b/g,"Sakvroth"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration905UnpersistUsage extends MigrationBase{static{__name(this,"Migration905UnpersistUsage")}static{__name2(this,"Migration905UnpersistUsage")}static version=.905;async updateItem(source){if(!isPhysicalData(source)){"usage"in source.system&&(source.system["-=usage"]=null);return}itemIsOfType(source,"armor","shield","treasure")&&"usage"in source.system?source.system["-=usage"]=null:source.system.usage?.value===""&&(source.system.usage.value="carried")}}const CONSUMABLE_CATEGORIES=new Set(["ammo","catalyst","drug","elixir","fulu","gadget","mutagen","oil","other","poison","potion","scroll","snare","talisman","toolkit","wand"]),DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES=new Set(["ammo","elixir","oil","other","poison","potion","snare"]),DAMAGE_ONLY_CONSUMABLE_CATEGORIES=new Set(["ammo","snare"]),AMMO_STACK_GROUPS=new Set(["arrows","blowgunDarts","bolts","rounds5","rounds10","slingBullets","sprayPellets","woodenTaws"]);class Migration906LimitStackGroup extends MigrationBase{static{__name(this,"Migration906LimitStackGroup")}static{__name2(this,"Migration906LimitStackGroup")}static version=.906;async updateItem(source){if((!isPhysicalData(source)||!itemIsOfType(source,"consumable","treasure"))&&"stackGroup"in source.system)source.system["-=stackGroup"]=null;else if(source.type==="consumable"){const category="consumableType"in source.system&&isObject$1(source.system.consumableType)?String(source.system.consumableType.value):source.system.category;source.system.stackGroup=category==="ammo"&&setHasElement(AMMO_STACK_GROUPS,source.system.stackGroup)?source.system.stackGroup:null}else source.type==="treasure"&&(source.system.stackGroup=["coins","gems"].includes(source.system.stackGroup??"")?source.system.stackGroup:null);!("game"in globalThis)&&"stackGroup"in source.system&&!source.system.stackGroup&&(source.system["-=stackGroup"]=null)}}class Migration907RestructureArmorWeaponRunes extends MigrationBase{static{__name(this,"Migration907RestructureArmorWeaponRunes")}static{__name2(this,"Migration907RestructureArmorWeaponRunes")}static version=.907;#RESILIENT_RUNE_CONVERSION=new Map([["resilient",1],["greaterResilient",2],["majorResilient",3]]);#STRIKING_RUNE_CONVERSION=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]);#RUNE_DELETIONS=["potencyRune","resiliencyRune","strikingRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4"];#cleanupSpecificData(system){const specificData=system.specific;isObject$1(specificData)&&("price"in specificData&&(specificData["-=price"]=null),specificData.value===!0?(specificData["-=value"]=null,specificData.runes=foundry.utils.deepClone(system.runes),isObject$1(specificData.material)&&"precious"in specificData.material?(specificData.material["-=precious"]=null,specificData.material=foundry.utils.mergeObject(specificData.material,foundry.utils.deepClone(system.material))):specificData.material=foundry.utils.deepClone(system.material)):"value"in specificData&&(system.specific=null))}#getRuneValue(system,key){if(!isObject$1(system))throw ErrorPF2e("Unexpected system data");const runeObject=system[key];return isObject$1(runeObject)?runeObject.value:null}async updateItem(source){if(itemIsOfType(source,"armor","weapon")&&(source.type==="armor"?source.system.runes??={potency:0,resilient:0,property:[]}:source.type==="weapon"&&(source.system.runes??={potency:0,striking:0,property:[]}),"potencyRune"in source.system&&isObject$1(source.system.potencyRune))){const potencyRune=Number(source.system.potencyRune.value)||0;source.system.runes.potency=tupleHasValue([1,2,3,4],potencyRune)?potencyRune:0}if(source.type==="armor"){if("resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)){const resilientRune=String(source.system.resiliencyRune.value),numericValue=this.#RESILIENT_RUNE_CONVERSION.get(resilientRune)??0;source.system.runes.resilient=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(ARMOR_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}else if(source.type==="weapon"){if("strikingRune"in source.system&&isObject$1(source.system.strikingRune)){const strikingRune=String(source.system.strikingRune.value),numericValue=this.#STRIKING_RUNE_CONVERSION.get(strikingRune)??0;source.system.runes.striking=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(WEAPON_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}for(const deletion of this.#RUNE_DELETIONS)deletion in source.system&&(source.system[`-=${deletion}`]=null)}}class Migration908TrueGangUp extends MigrationBase{static{__name(this,"Migration908TrueGangUp")}static{__name2(this,"Migration908TrueGangUp")}static version=.908;async updateItem(source){if((source.system.slug??"")==="gang-up"&&source.type==="feat"){const rule={key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:!0};source.system.rules=[rule]}}}class Migration909RefineConsumableData extends MigrationBase{static{__name(this,"Migration909RefineConsumableData")}static{__name2(this,"Migration909RefineConsumableData")}static version=.909;async updateItem(source){if(source.type!=="consumable")return;const system=source.system,autoDestroy=isObject$1(system.autoDestroy)?!!system.autoDestroy.value:system.uses?.autoDestroy??!0;if("autoDestroy"in system&&(system["-=autoDestroy"]=null),"charges"in system){if(isObject$1(system.charges)){const value=Math.min(Math.max(Math.floor(Number(system.charges.value)||0),0),9999),max=Math.min(Math.max(Math.floor(Number(system.charges.max)||0),0),9999);system.uses={value,max,autoDestroy},system.uses.max===0&&(system.uses.value=1,system.uses.max=1)}system["-=charges"]=null}if("consumableType"in system){if(isObject$1(system.consumableType)){const category=system.consumableType.value==="tool"?"toolkit":system.consumableType.value;system.category=setHasElement(CONSUMABLE_CATEGORIES,category)?category:"other"}system["-=consumableType"]=null}if(system.slug==="fang-snare"&&(system.category="snare"),"consume"in system){if(isObject$1(system.consume)){const traits=source.system.traits.value,formula=typeof system.consume.value=="string"&&system.consume.value.trim()||null,type=formula?this.#determineDamageType(system.category,traits,system.description.value):null,kind=DAMAGE_ONLY_CONSUMABLE_CATEGORIES.has(system.category)||!["vitality","void","untyped"].includes(type??"")?"damage":"healing";system.damage=formula===null||type===null?null:{formula,kind,type}}system["-=consume"]=null}DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES.has(system.category)||(system.damage=null)}#determineDamageType(category,traits,description){const damageTypes2=Array.from(DAMAGE_TYPES),fromTraits=damageTypes2.find(t=>traits.includes(t)),fromDescription=!fromTraits&&category==="snare"?damageTypes2.find(t=>new RegExp(String.raw`\b${t}\b`).test(description)):null;return fromTraits??fromDescription??"untyped"}}class Migration910EdictsAnathemaArrays extends MigrationBase{static{__name(this,"Migration910EdictsAnathemaArrays")}static{__name2(this,"Migration910EdictsAnathemaArrays")}static version=.91;async updateActor(source){if(source.type!=="character")return;const biography=source.system.details.biography;biography.edicts=compact(typeof biography.edicts=="string"?[biography.edicts]:biography.edicts??[]),biography.anathema=compact(typeof biography.anathema=="string"?[biography.anathema]:biography.anathema??[])}}class Migration911CoinBulk extends MigrationBase{static{__name(this,"Migration911CoinBulk")}static{__name2(this,"Migration911CoinBulk")}static version=.911;async updateItem(source){source.type==="treasure"&&source.system.stackGroup==="coins"&&(source.system.bulk.value=1)}}const Migrations=Object.freeze(Object.defineProperty({__proto__:null,Migration634PurgeMartialItems,Migration635NumifyACAndQuantity,Migration636NumifyArmorData,Migration637CleanMeleeItems,Migration638SpellComponents,Migration639NormalizeLevelAndPrice,Migration640CantripsAreNotZeroLevel,Migration641SovereignSteelValue,Migration642TrackSchemaVersion,Migration643HazardLevel,Migration644SpellcastingCategory,Migration645TokenImageSize,Migration646UpdateInlineLinks,Migration647FixPCSenses,Migration648RemoveInvestedProperty,Migration649FocusToActor,Migration650StringifyWeaponProperties,Migration651EphemeralFocusPool,Migration652KillHalcyonTradition,Migration653AEstoREs,Migration654ActionTypeAndCount,Migration655CreatureTokenSizes,Migration656OtherFocusPoolSources,Migration657RemoveSetProperty,Migration658MonkUnarmoredProficiency,Migration659MultipleDamageRows,Migration660DerivedSpellTraits,Migration661NumifyVehicleDimensions,Migration662LinkToActorSizeDefaults,Migration663FixSpellDamage,Migration664DeleteCUBConditions,Migration665HandwrapsCorrections,Migration666UsageAndStowingContainers,Migration667HPSubProperties,Migration668ArmorSpeedPenalty,Migration669NPCAttackEffects,Migration670AncestryVision,Migration670NoCustomTrait,Migration671NoPCItemsOnNonPCs,Migration672RemoveNPCBaseProperties,Migration673RemoveBulwarkREs,Migration674StableHomebrewTagIDs,Migration675FlatModifierAEsToREs,Migration676ReplaceItemsWithRELikeAEs,Migration677RuleValueDataRefs,Migration678SeparateNPCAttackTraits,Migration679TowerShieldSpeedPenalty,Migration680SetWeaponHands,Migration681GiantLanguageToJotun,Migration682BiographyFields,Migration683FlavorTextToPublicNotes,Migration684RationsToConsumable,Migration685FixMeleeUsageTraits,Migration686HeroPointsToResources,Migration687FamiliarityAEsToREs,Migration688ClampSpellLevel,Migration689EncumberanceActiveEffects,Migration690InitiativeTiebreakItems,Migration691WeaponRangeAbilityCategoryGroup,Migration692CraftingEntryFeatReplacement,Migration693ArmorCategoryGroup,Migration694RetireSystemTokenSettings,Migration695SummonToSummoned,Migration696FlatAbilityModifiers,Migration697WeaponReachTrait,Migration698RemoveDerivedActorTraits,Migration699ItemDescriptionEmptyString,Migration700SingleClassFeatures,Migration701ModifierNameToSlug,Migration702REFormulasAtInstanceLevel,Migration703SpellDamageStructure,Migration704MartialProficiencyRE,Migration705GunslingerCatchUp,Migration706FormulasAtInstanceLevelEverythingElse,Migration707BracketedFormulasAtInstanceLevel,Migration708SpecificRuleLabel,Migration709REFormulasAtInstanceLevelRedux,Migration710RarityToString,Migration711HeritageItems,Migration712ActorShieldStructure,Migration713FistToStrikeRE,Migration714RangeIncrementREs,Migration715DangerousSorcery,Migration716StrikeDamageSelector,Migration717TakeFeatLimits,Migration718CarryType,Migration719ShrugFlanking,Migration720UpdateSpellDescriptions,Migration721SetReloadValues,Migration722CraftingSystemData,Migration723CumulativeItemBonuses,Migration724CraftingMaxItemLevel,Migration725QuickClimbREs,Migration726JournalSetting,Migration727TrimSelfRollOptions,Migration728FlattenPhysicalProperties,Migration729CumulativeItemBonusCleanup,Migration730DeruneHandwraps,Migration731TogglePropertyToRollOption,Migration732FixDedicationFeatTypes,Migration733ItemBonusFromEquipment,Migration734SpellLocationPropsAndSignature,Migration735FirearmAmmoAlchemical,Migration736RemoveBrokenThreshold,Migration737NormalizeRuleElementKeys,Migration738UpdateLaughingShadow,Migration739RecoveryCheckDC,Migration740MaxTakable,Migration741RollOptionToggleToItem,Migration742RMAbilityBoostLevels,Migration743FixWeaknessStructure,Migration744MigrateSpellHeighten,Migration745EffectTargetToChoiceSet,Migration746StandardizePricing,Migration747FixedHeightening,Migration748BatchConsumablePricing,Migration749AssuranceREs,Migration750FixCorruptedPrice,Migration751ResetRollOptions,Migration752StrikeVsWeaponTraits,Migration753WeaponReloadTimes,Migration754MightyBulwarkAdjustModifiers,Migration755GrantIdsToData,Migration756RMStoredResourceMaxes,Migration757HillockHalfling,Migration758PrunePCAttributes,Migration759CritSpecRE,Migration760SeparateNoteTitle,Migration761ShotRules,Migration762UpdateBackgroundItems,Migration763RestoreAnimalStrikeOptions,Migration764PanacheVivaciousREs,Migration765ChoiceOwnedItemTypes,Migration766WipeURLSources,Migration767ConvertVoluntaryFlaws,Migration768AddNewAuras,Migration769NoUniversalistFocusPool,Migration770REDataToSystem,Migration771SpellVariantsToSystem,Migration772V10EmbeddedSpellData,Migration773ReligiousSymbolUsage,Migration774UnpersistCraftingEntries,Migration775AgileFinesseRanged,Migration776SlugifyConditionOverrides,Migration777HandOfTheApprentice,Migration778RenameRetiredPackRefs,Migration779EliteWeak,Migration780NumifySpeeds,Migration781SuppressNoCrowbar,Migration782UnnestActorTraits,Migration783RemoveClassSkillAELikes,Migration784CompBrowserPackSetting,Migration785ABCKitItemUUIDs,Migration786RemoveIdentifiedData,Migration787ResolvablesToSystem,Migration788UpdateTanglefootBags,Migration789UpdatePreciseStrike,Migration790MultipleClassDCs,Migration791RuffianHands,Migration792RemoveTokenAELikes,Migration793MakePredicatesArrays,Migration794AddWildShapeChoices,Migration795CleanupFlatFootedToggle,Migration796ItemGrantsToObjects,Migration797MetagameSetting,Migration798WeaponToItemStatements,Migration799RMRecallKnowledgeDuplicates,Migration800SelfEffectPanacheRage,Migration801ColorDarkvision,Migration802StripFeatActionCategory,Migration803NormalizeSpellArea,Migration804RemoveConsumableProperties,Migration805InlineDamageRolls,Migration806TorchImprovisedOtherTags,Migration807RMActivatedEffectFields,Migration808CountDamageDice,Migration809AutomatonEnhancements,Migration810LootDescriptionValue,Migration811InlineDamageRollsPersistent,Migration812RestructureIWR,Migration813NormalizeColdIron,Migration814CalculatedExpandedSplash,Migration815ConsumableDataCleanup,Migration816AlchemistResearchFields,Migration817FieldDiscoveryPredicates,Migration818BasicUndeadNegativeHealing,Migration819SpinTaleAdventureSpecific,Migration820RemoveUnusedTraitsData,Migration821InlineDamageRolls,Migration822BladeAllyConsolidation,Migration823HeritageAncestrySlug,Migration824SneakAttackDamageSource,Migration825KhakkharaFengHuoLun,Migration826GutConditionData,Migration827FixTVShieldTraits,Migration828PruneInvalidTraits,Migration829RMRitualEntries,Migration830BarbarianRework,Migration831ClericDoctrines,Migration832ChoiceSetFlags,Migration833AddRogueToysFixPrecision,Migration834FeatCategories,Migration835InitiativeLongform,Migration836EnergizingConsolidation,Migration837MoveHazardBookSources,Migration838StrikeAttackRollSelector,Migration839ActionCategories,Migration840ArrayWrapPredicates,Migration841V11UUIDFormat,Migration842NumifyNumericSettings,Migration843RMArmorCustomModifiers,Migration844DeityDomainUUIDs,Migration845EmptySpellConsumables,Migration846SpellSchoolOptional,Migration847TempHPRuleEvents,Migration848NumericArmorProperties,Migration849DeleteBrokenThreshold,Migration850FlatFootedToOffGuard,Migration851JustInnovationId,Migration852AbilityScoresToModifiers,Migration853RemasterLanguages,Migration854BracketedAbilityScoresToModifiers,Migration855ApexEquipmentSystemData,Migration856NoSystemDotCustom,Migration857WeaponSpecializationRE,Migration858FakeWeaponSpecialization,Migration859MaterialTypeGrade,Migration860RMGroup,Migration861AuraColorsToAppearance,Migration862SpecificMagicArmor,Migration863FixMisspelledOrganaizationsProperty,Migration864RemoveWeaponMAP,Migration865VitalityVoid,Migration866LinkToActorSizeAgain,Migration867DamageRollDomainFix,Migration868StrikeRERange,Migration869RefreshMightyBulwark,Migration870MartialToProficiencies,Migration871MigrateRollActionMacroParams,Migration872MoveSchemaProperty,Migration873RemoveBonusBulkLimit,Migration874MoveStaminaStuff,Migration875SetInnovationIdEarly,Migration876FeatLevelTaken,Migration877PublicationData,Migration878TakeABreather,Migration879DeviseAStratagemAndFriends,Migration880SplitShowDialogsSettings,Migration881NoHBPrefix,Migration882SpellDataReorganization,Migration883BanishAlignment,Migration884UnifiedSpellcasting,Migration885ConvertAlignmentDamage,Migration886CrossbowGroup,Migration887RedirectSpellLinks,Migration888RemasterLanguagesHeritages,Migration889RemoveFocusMaxIncreases,Migration890RMClassItemClassDC,Migration891DruidicToWildsong,Migration892ChoiceSetREAdjustNameValue,Migration893NoHBPrefixSettings,Migration894NoLayOnHandsVsUndead,Migration895FixVariantSpellTraits,Migration896HealingDomains,Migration897ClearLayOnHandsDamage,Migration898NoHBAgain,Migration899ArmorShieldToShieldShield,Migration900ClassSpellcastingProficiency,Migration901ReorganizeBulkData,Migration902DuskwoodDawnsilver,Migration903PhysicalNumericData,Migration904UndercommonToSakvroth,Migration905UnpersistUsage,Migration906LimitStackGroup,Migration907RestructureArmorWeaponRunes,Migration908TrueGangUp,Migration909RefineConsumableData,Migration910EdictsAnathemaArrays,Migration911CoinBulk},Symbol.toStringTag,{value:"Module"}));class MigrationList{static{__name(this,"MigrationList")}static{__name2(this,"MigrationList")}static#list=Object.values(Migrations);static get latestVersion(){return Math.max(...this.#list.map(M=>M.version))}static constructAll(){return this.#list.map(M=>new M)}static constructFromVersion(version){const minVersion=Number(version)||MigrationRunner.RECOMMENDED_SAFE_VERSION;return this.#list.filter(M=>M.version>minVersion).map(M=>new M)}static constructRange(min,max=1/0){return this.#list.filter(M=>M.version>=min&&M.version<=max).map(M=>new M)}}class WeaponDamagePF2e{static{__name(this,"WeaponDamagePF2e")}static{__name2(this,"WeaponDamagePF2e")}static async fromNPCAttack({attack,actor,context}){const{baseDamage}=attack,secondaryInstances=Object.values(attack.system.damageRolls).map(this.npcDamageToWeaponDamage).filter(d=>!equals(d,baseDamage)),damageDice=[],modifiers=[],labelFromCategory={null:"",persistent:"",precision:"PF2E.Damage.Precision",splash:"PF2E.WeaponSplashDamageLabel"};for(const instance of secondaryInstances){const{damageType}=instance;instance.dice>0&&instance.die&&damageDice.push(new DamageDicePF2e({slug:"base",label:labelFromCategory[instance.category??"null"],selector:"damage",diceNumber:instance.dice,dieSize:instance.die,damageType:instance.damageType,category:instance.category})),instance.modifier&&modifiers.push(new ModifierPF2e({label:labelFromCategory[instance.category??"null"],modifier:instance.modifier,damageType,damageCategory:instance.category}))}return WeaponDamagePF2e.calculate({weapon:attack,actor,damageDice,modifiers,context})}static async calculate({weapon,actor,damageDice=[],modifiers=[],weaponPotency=null,context}){const{baseDamage}=weapon,{options}=context,domains=context.domains;if(baseDamage.die===null&&baseDamage.modifier>0)baseDamage.dice=0;else if(!weapon.dealsDamage)return null;const weaponTraits2=weapon.system.traits.value,materialTraits=weapon.isOfType("melee")?weapon.system.traits.value.filter(t=>t in CONFIG.PF2E.materialDamageEffects):[];for(const trait of weaponTraits2)options.add(trait);const isMelee=!!weapon.isMelee;if(options.add(isMelee?"melee":"ranged"),actor.isOfType("character")&&weapon.isOfType("weapon")){const attributeDomains=ATTRIBUTE_ABBREVIATIONS.map(a=>`${a}-damage`),domain=domains.find(d=>attributeDomains.has(d)),strengthModValue=actor.abilities.str.mod,modifierValue=domain==="str-damage"?strengthModValue<0||!weaponTraits2.some(t=>t==="propulsive")?strengthModValue:Math.floor(strengthModValue/2):null;if(typeof modifierValue=="number"){const strModifier=createAttributeModifier({actor,attribute:"str",domains,max:modifierValue});modifiers.push(strModifier)}}for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const splashDamage=weapon.isOfType("weapon")?Number(weapon.system.splashDamage?.value):0;if(splashDamage>0){const modifier=new ModifierPF2e({slug:"splash",label:"PF2E.WeaponSplashDamageLabel",modifier:splashDamage,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"splash")});modifiers.push(modifier)}if(weapon.isOfType("weapon")){weaponTraits2.includes("kickback")&&modifiers.push(new ModifierPF2e({slug:"kickback",label:CONFIG.PF2E.weaponTraits.kickback,modifier:1,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"kickback")}));const handsHeld=weapon.system.equipped.handsHeld??0,baseDieFaces=Number(baseDamage.die?.replace("d","")??"NaN"),twoHandSize=weaponTraits2.find(t=>t.startsWith("two-hand-"))?.replace("two-hand-",""),twoHandFaces=Number(twoHandSize?.replace("d","")??"NaN");if(handsHeld===2&&setHasElement(DAMAGE_DIE_FACES,twoHandSize)&&twoHandFaces>baseDieFaces&&(baseDamage.die=twoHandSize),weaponTraits2.find(t=>t.startsWith("scatter-"))&&baseDamage.die){const modifier=new ModifierPF2e({slug:"scatter",label:"PF2E.Damage.Scatter",modifier:baseDamage.dice,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"scatter")});modifiers.push(modifier)}const bonusDamage=Number(weapon.system.bonusDamage?.value);bonusDamage>0&&modifiers.push(new ModifierPF2e({label:"PF2E.WeaponBonusDamageLabel",modifier:bonusDamage}));const customDamage=weapon.system.property1,normalDice=customDamage.dice??0;if(normalDice>0){const damageType=customDamage.damageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom",label:"PF2E.WeaponCustomDamageLabel",diceNumber:normalDice,dieSize:customDamage.die,damageType}))}const critDice=customDamage.critDice??0;if(critDice>0){const damageType=customDamage.critDamageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom-critical",label:"PF2E.WeaponCustomDamageLabel",diceNumber:critDice,dieSize:customDamage.critDie,damageType,critical:!0}))}}const potency=weaponPotency?.bonus??0,strikingSynthetic=domains.flatMap(key=>actor.synthetics.striking[key]??[]).filter(wp=>wp.predicate.test(options)).reduce((highest,current)=>highest&&highest.bonus>current.bonus?highest:current,null);strikingSynthetic&&baseDamage.die&&(weapon.isOfType("melee")||strikingSynthetic.bonus>weapon.system.runes.striking)&&(damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"striking",label:strikingSynthetic.label,diceNumber:strikingSynthetic.bonus})),weapon.isOfType("weapon")&&(weapon.system.damage.dice-=weapon.system.runes.striking,weapon.system.runes.striking=0));const critSpecEffect=(()=>{const critSpecs=actor.synthetics.criticalSpecalizations,standard=critSpecs.standard.reduceRight((result,cs)=>result??cs?.(weapon,options),null),alternate=critSpecs.alternate.reduceRight((result,cs)=>result??cs?.(weapon,options),null);return standard?alternate??standard:[]})();critSpecEffect.length>0&&options.add("critical-specialization"),modifiers.push(...critSpecEffect.filter(e=>e instanceof ModifierPF2e)),damageDice.push(...critSpecEffect.filter(e=>e instanceof DamageDicePF2e));const propertyRunes=weapon.system.runes.property;damageDice.push(...getPropertyRuneDice(propertyRunes,options));const propertyRuneAdjustments=getPropertyRuneModifierAdjustments(propertyRunes),ignoredResistances=propertyRunes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.ignoredResistances??[]);if(weaponTraits2.some(t=>t==="backstabber")&&options.has("target:condition:off-guard")){const modifier=new ModifierPF2e({label:CONFIG.PF2E.weaponTraits.backstabber,slug:"backstabber",modifier:potency>2?2:1,damageCategory:"precision",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"backstabber")});modifiers.push(modifier)}const traitLabels=CONFIG.PF2E.weaponTraits,deadlyTraits=weaponTraits2.filter(t=>t.startsWith("deadly-")),strikingDice=(()=>{if(weapon.isOfType("weapon")){const weaponStrikingDice=weapon.system.damage.dice-weapon._source.system.damage.dice;return strikingSynthetic&&strikingSynthetic.bonus>weaponStrikingDice?strikingSynthetic.bonus:weaponStrikingDice}else return strikingSynthetic?.bonus??0})();for(const slug of deadlyTraits){const diceNumber=(()=>{const baseNumber=Number(/-(\d)d\d{1,2}$/.exec(slug)?.at(1))||1;return strikingDice>1?strikingDice*baseNumber:baseNumber})();damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug,label:traitLabels[slug],damageType:baseDamage.damageType,diceNumber,dieSize:/-\d?(d\d{1,2})$/.exec(slug)?.at(1)??baseDamage.die,critical:!0}))}for(const trait of weaponTraits2.filter(t=>t.startsWith("fatal-d"))){const dieSize=trait.substring(trait.indexOf("-")+1);damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:trait,label:traitLabels[trait],damageType:baseDamage.damageType,diceNumber:1,dieSize,critical:!0,enabled:!0,override:{dieSize}}))}const runeNotes=propertyRunes.flatMap(r=>(RUNE_DATA.weapon.property[r].damage?.notes??[]).map(d=>new RollNotePF2e({selector:"strike-damage",...d})));context.notes=[runeNotes,critSpecEffect.filter(e=>e instanceof RollNotePF2e)].flat();const material=objectHasKey(CONFIG.PF2E.materialDamageEffects,weapon.system.material.type)?weapon.system.material.type:null,materials=new Set([materialTraits,material??[]].flat());for(const adjustment of actor.synthetics.strikeAdjustments)adjustment.adjustDamageRoll?.(weapon,{materials});for(const option of Array.from(materials).map(m=>`item:material:${m}`))options.add(option);for(const modifier of modifiers){const propRuneAdjustments=propertyRuneAdjustments.filter(a=>a.slug===modifier.slug);modifier.adjustments.push(...propRuneAdjustments)}const baseUncategorized=(()=>{const diceNumber=baseDamage.die?baseDamage.dice:0;return diceNumber>0||baseDamage.modifier>0?{diceNumber,dieSize:baseDamage.die,modifier:baseDamage.modifier,damageType:baseDamage.damageType,category:"category"in baseDamage&&baseDamage.category==="persistent"?"persistent":null,materials:Array.from(materials)}:null})(),basePersistent=(()=>baseDamage.persistent?.faces?{diceNumber:baseDamage.persistent.number,dieSize:`d${baseDamage.persistent.faces}`,damageType:baseDamage.persistent.type,category:"persistent"}:baseDamage.persistent?.number?{modifier:baseDamage.persistent.number,damageType:baseDamage.persistent.type,category:"persistent"}:null)();if(!(baseUncategorized||basePersistent||splashDamage))return null;const base=compact([baseUncategorized,basePersistent]),extractOptions={test:options,resolvables:{weapon,target:context.target?.actor??null},injectables:{weapon}},extracted=processDamageCategoryStacking(base,{modifiers:[modifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options}),testedModifiers=extracted.modifiers;damageDice.push(...extracted.dice);const formulaData={base,dice:damageDice,maxIncreases:1,modifiers:testedModifiers,ignoredResistances};formulaData.base[0].diceNumber||formulaData.base[0].modifier||(formulaData.dice=formulaData.dice.filter(d=>![null,"precision"].includes(d.category)),formulaData.modifiers=formulaData.modifiers.filter(m=>![null,"precision"].includes(m.category)));const excludeFrom=weapon.isOfType("weapon")?weapon:null;if(this.#excludeDamage({actor,weapon:excludeFrom,modifiers:[...testedModifiers,...damageDice],options}),!context.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const computedFormulas={criticalFailure:null,failure:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.FAILURE),success:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.SUCCESS),criticalSuccess:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)};return{name:`${game.i18n.localize("PF2E.DamageRoll")}: ${weapon.name}`,materials:Array.from(materials),modifiers:[...modifiers,...damageDice],damage:{...formulaData,formula:mapValues(computedFormulas,formula=>formula?.formula??null),breakdown:mapValues(computedFormulas,formula=>formula?.breakdown??[])}}}static#excludeDamage({actor,modifiers,weapon,options}){if(!weapon)return;const notIgnored=modifiers.filter(modifier=>!modifier.ignored);for(const rule of actor.rules)rule.applyDamageExclusion?.(weapon,notIgnored);for(const modifier of notIgnored)modifier.ignored=!modifier.predicate.test(options)}static npcDamageToWeaponDamage(instance){const terms=parseTermsFromSimpleFormula(instance.damage),die=terms.find(t=>t.dice)?.dice,modifier=terms.find(t=>t.modifier)?.modifier??0;return{dice:die?.number??0,die:die?.faces?`d${die.faces}`:null,modifier,damageType:instance.damageType,persistent:null,category:instance.category}}}async function resetActors(actors,options={}){actors??=[game.actors.contents,game.scenes.contents.flatMap(s=>s.tokens.contents).flatMap(t=>t.actor??[])].flat(),actors=uniq(Array.from(actors));for(const actor of actors)actor.reset(),options.sheets&&actor.render();if(game.pf2e.effectPanel.refresh(),game.settings.get("pf2e","automation.effectExpiration")&&!game.settings.get("pf2e","automation.removeExpiredEffects")){const scenes=uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!1,!0)).flatMap(t=>t.scene));for(const scene of scenes)scene.reset(),scene.isView&&canvas.perception.update({initializeVision:!0},!0)}if(options.tokens)for(const token of uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!0,!0))))token.simulateUpdate()}__name(resetActors,"resetActors"),__name2(resetActors,"resetActors");function userColorForActor(actor){return(game.users.find(u=>u.character===actor)??game.users.players.find(u=>actor.testUserPermission(u,"OWNER"))??actor.primaryUpdater)?.color??"#43dfdf"}__name(userColorForActor,"userColorForActor"),__name2(userColorForActor,"userColorForActor");async function migrateActorSource(source){source.effects=[],["flags","items","system"].some(k=>k in source)||(source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}});const lowestSchemaVersion=Math.min(source.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION,...(source.items??[]).map(i=>i?.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION)),tokenDefaults=foundry.utils.deepClone(game.settings.get("core","defaultToken")),actor=new ActorProxyPF2e(foundry.utils.mergeObject({prototypeToken:tokenDefaults},source));return await MigrationRunner.ensureSchemaVersion(actor,MigrationList.constructFromVersion(lowestSchemaVersion)),actor.toObject()}__name(migrateActorSource,"migrateActorSource"),__name2(migrateActorSource,"migrateActorSource");async function checkAreaEffects(){if(!canvas.ready||game.user!==this.primaryUpdater||this.isOfType("party"))return;const thisTokens=this.getActiveTokens(!0,!0),toDelete2=[],toKeep=[];for(const effect of this.itemTypes.effect){const auraData=effect.flags.pf2e.aura;if(!auraData?.removeOnExit)continue;const auraActor=await fromUuid(auraData.origin),aura=(auraActor?.getActiveTokens(!0,!0).shift()??null)?.auras.get(auraData.slug),auraEffectData=auraActor?.auras.get(auraData.slug)?.effects.find(e=>e.uuid===effect.sourceId&&auraAffectsActor(e,auraActor,this));for(const token of thisTokens)auraEffectData&&aura?.containsToken(token)?toKeep.push(effect.id):toDelete2.push(effect.id);thisTokens.length===0&&toDelete2.push(effect.id)}const finalToDelete=toDelete2.filter(id=>!toKeep.includes(id));finalToDelete.length>0&&await this.deleteEmbeddedDocuments("Item",finalToDelete)}__name(checkAreaEffects,"checkAreaEffects"),__name2(checkAreaEffects,"checkAreaEffects");function auraAffectsActor(data,origin,actor){return data.includesSelf&&origin===actor||data.affects==="allies"&&actor.isAllyOf(origin)||data.affects==="enemies"&&actor.isEnemyOf(origin)||data.affects==="all"&&actor!==origin}__name(auraAffectsActor,"auraAffectsActor"),__name2(auraAffectsActor,"auraAffectsActor");function setHitPointsRollOptions(actor){const hp=actor.hitPoints;if(!hp)return;actor.flags.pf2e.rollOptions.all[`hp-remaining:${hp.value}`]=!0;const percentRemaining=Math.floor(hp.value/hp.max*100);actor.flags.pf2e.rollOptions.all[`hp-percent:${percentRemaining}`]=!0}__name(setHitPointsRollOptions,"setHitPointsRollOptions"),__name2(setHitPointsRollOptions,"setHitPointsRollOptions");function calculateMAPs(item,{domains,options}){const slugAndLabel={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty"},baseMap=item.isOfType("action","melee","weapon")&&item.traits.has("agile")?{...slugAndLabel,map1:-4,map2:-8}:{...slugAndLabel,map1:-5,map2:-10},optionSet=options instanceof Set?options:new Set(options),maps=item.actor?.synthetics.multipleAttackPenalties??{},fromSynthetics=domains.flatMap(d=>maps[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)}__name(calculateMAPs,"calculateMAPs"),__name2(calculateMAPs,"calculateMAPs");function createEncounterRollOptions(actor){const encounter=game.ready?game.combat:null;if(!encounter?.started)return{};const participants=encounter.combatants.contents.filter(c=>typeof c.initiative=="number").sort((a,b)=>b.initiative-a.initiative),participant=actor.combatant;if(typeof participant?.initiative!="number"||!participants.includes(participant))return{};const initiativeRoll=Math.trunc(participant.initiative),initiativeRank=participants.indexOf(participant)+1,{initiativeStatistic}=participant.flags.pf2e,threat=encounter.metrics?.threat,numericThreat={trivial:0,low:1,moderate:2,severe:3,extreme:4}[threat??"trivial"],entries=[["encounter",!0],[`encounter:threat:${numericThreat}`,!!threat],[`encounter:threat:${threat}`,!!threat],[`encounter:round:${encounter.round}`,!0],[`encounter:turn:${Number(encounter.turn)+1}`,!0],["self:participant:own-turn",encounter.combatant===participant],[`self:participant:initiative:roll:${initiativeRoll}`,!0],[`self:participant:initiative:rank:${initiativeRank}`,!0],[`self:participant:initiative:stat:${initiativeStatistic}`,!!initiativeStatistic]].filter(([,value])=>!!value);return Object.fromEntries(entries)}__name(createEncounterRollOptions,"createEncounterRollOptions"),__name2(createEncounterRollOptions,"createEncounterRollOptions");function isOffGuardFromFlanking(target,origin,originRollOptions){if(!target.isOfType("creature"))return!1;const{flanking}=target.attributes;return flanking.flankable&&(typeof flanking.offGuardable=="number"?origin.level>flanking.offGuardable:flanking.offGuardable)&&!target.attributes.immunities.some(i=>i.test(["item:type:condition","item:slug:off-guard",...originRollOptions]))}__name(isOffGuardFromFlanking,"isOffGuardFromFlanking"),__name2(isOffGuardFromFlanking,"isOffGuardFromFlanking");function getStrikeAttackDomains(weapon,proficiencyRank,baseRollOptions){const unarmedOrWeapon=weapon.category==="unarmed"?"unarmed":"weapon",meleeOrRanged=weapon.isMelee?"melee":"ranged",weaponSlug=weapon.slug??sluggify(weapon.name),domains=[weapon.baseType?`${weapon.baseType}-base-attack-roll`:[],weapon.group?`${weapon.group}-group-attack-roll`:[],weapon.system.traits.otherTags.map(t=>`${t}-tag-attack-roll`),`${weapon.id}-attack`,`${weaponSlug}-attack`,`${weaponSlug}-attack-roll`,`${unarmedOrWeapon}-attack-roll`,`${meleeOrRanged}-attack-roll`,`${meleeOrRanged}-strike-attack-roll`,"strike-attack-roll","attack-roll","attack","check","all"].flat();if(typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-attack`)}const{actor}=weapon;if(actor.isOfType("character","npc")){const defaultAttributeModifier=createAttributeModifier({actor,attribute:weapon.defaultAttribute,domains}),rollOptions=[...baseRollOptions,actor.getRollOptions(domains),weapon.getRollOptions("item")].flat(),weaponTraits2=weapon.traits,alternativeAttributeModifier=actor.isOfType("character")?weaponTraits2.has("finesse")?createAttributeModifier({actor,attribute:"dex",domains}):weaponTraits2.has("brutal")||weaponTraits2.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null:null,attributeModifier=compact([defaultAttributeModifier,alternativeAttributeModifier,...extractModifiers(weapon.actor.synthetics,domains,{resolvables:{weapon},test:rollOptions})]).filter(m=>m.type==="ability"&&m.enabled).reduce((best,candidate)=>candidate.modifier>best.modifier?candidate:best);domains.push(`${attributeModifier.ability}-attack`,`${attributeModifier.ability}-based`)}return uniq(domains)}__name(getStrikeAttackDomains,"getStrikeAttackDomains"),__name2(getStrikeAttackDomains,"getStrikeAttackDomains");function getStrikeDamageDomains(weapon,proficiencyRank){const meleeOrRanged=weapon.isMelee?"melee":"ranged",slug=weapon.slug??sluggify(weapon.name),{actor,traits}=weapon,unarmedOrWeapon=traits.has("unarmed")?"unarmed":"weapon",domains=[`${weapon.id}-damage`,`${slug}-damage`,`${meleeOrRanged}-strike-damage`,`${meleeOrRanged}-damage`,`${unarmedOrWeapon}-damage`,"attack-damage","strike-damage","damage"];if(weapon.group&&domains.push(`${weapon.group}-weapon-group-damage`),weapon.baseType&&domains.push(`${weapon.baseType}-base-type-damage`),typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-damage`)}const baseType=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType;if(baseType&&!domains.includes(`${baseType}-damage`)&&domains.push(`${baseType}-damage`),actor.isOfType("character","npc")){const attributeModifier=[weapon.isMelee||weapon.isThrown&&!traits.has("splash")||traits.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null,...extractModifiers(actor.synthetics,domains,{resolvables:{weapon},test:[...actor.getRollOptions(domains),...weapon.getRollOptions("item")]}).filter(m=>!m.ignored&&m.type==="ability")].reduce((best,candidate)=>candidate&&best?candidate.value>best.value?candidate:best:candidate??best);attributeModifier&&domains.push(`${attributeModifier.ability}-damage`)}return uniq(domains)}__name(getStrikeDamageDomains,"getStrikeDamageDomains"),__name2(getStrikeDamageDomains,"getStrikeDamageDomains");function strikeFromMeleeItem(item){const{actor,isMelee}=item;if(!actor.isOfType("npc","hazard"))throw ErrorPF2e("Attempted to create melee-item strike statistic for non-NPC/hazard");const meleeOrRanged=isMelee?"melee":"ranged",baseOptions=new Set(compact(["self:action:slug:strike",meleeOrRanged,...item.system.traits.value])),domains=getStrikeAttackDomains(item,actor.isOfType("npc")?1:null,baseOptions),{synthetics}=actor,modifiers=[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:item.attackModifier,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,"base")})];modifiers.push(...extractModifiers(synthetics,domains)),modifiers.push(...AttackTraitHelpers.createAttackModifiers({item}));const attackEffects=CONFIG.PF2E.attackEffects,additionalEffects=item.attackEffects.map(tag=>{const items=actor.items.contents,label=attackEffects[tag]??items.find(i=>(i.slug??sluggify(i.name))===tag)?.name??tag;return{tag,label}});for(const adjustment of synthetics.strikeAdjustments)adjustment.adjustWeapon?.(item);const initialRollOptions=new Set([...baseOptions,...actor.getRollOptions(domains),...item.getRollOptions("item")]),attackSlug=item.slug??sluggify(item.name),statistic=new StatisticModifier(attackSlug,modifiers,initialRollOptions),actionTraits2=compact(["attack",item.baseType==="alchemical-bomb"?"manipulate":null]),strikeAdjustments=[actor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(item.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(item,actionTraits2);const strike=foundry.utils.mergeObject(statistic,{label:item.name,type:"strike",glyph:getActionGlyph({type:"action",value:1}),description:item.description,sourceId:item.id,attackRollType:item.isRanged?"PF2E.NPCAttackRanged":"PF2E.NPCAttackMelee",additionalEffects,item,weapon:item,options:Array.from(baseOptions),traits:[actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits))].flat(),variants:[],ready:!0,success:"",criticalSuccess:""});strike.breakdown=strike.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.value)}`).join(", ");const maps=calculateMAPs(item,{domains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,maps.slug)}),"createMapModifier"),labels=[`${game.i18n.localize("PF2E.WeaponStrikeLabel")} ${signedInteger(strike.totalModifier)}`,...["map1","map2"].map(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],baseOptions);const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(strike.totalModifier+penalty),penalty})})];strike.variants=[null,...["map1","map2"].map(createMapModifier)].map((map2,mapIncreases)=>({label:labels[mapIncreases],roll:async(params={})=>{params.options??=[];const context=await actor.getCheckContext({item,viewOnly:params.getFormula??!1,statistic:strike,target:{token:params.target??game.user.targets.first()??null},defense:"armor",domains,options:new Set([...baseOptions,...params.options]),traits:actionTraits2});if(context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}const otherModifiers=[map2??[],context.self.modifiers].flat(),title=game.i18n.format(item.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:item.name}),notes=[actor.isOfType("npc")?await actor.getAttackEffects(item):[],extractNotes(context.self.actor.synthetics.rollNotes,domains)].flat(),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,domains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,domains,context.options),dosAdjustments=extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,domains),check=new CheckModifier("strike",context.self.statistic??strike,otherModifiers),checkContext={type:"attack-roll",identifier:`${item.id}.${attackSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,item:context.self.item,target:context.target,damaging:context.self.item.dealsDamage,domains,options:context.options,traits:context.traits,notes,dc:params.dc??context.dc,mapIncreases,rollTwice,substitutions,dosAdjustments},roll=await CheckPF2e.roll(check,checkContext,params.event);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains,rollOptions:context.options});return roll}})),strike.roll=strike.attack=strike.variants[0].roll;const damageRoll=__name2(outcome=>async(params={})=>{const domains2=getStrikeDamageDomains(item,actor.isOfType("npc")?1:null),targetToken=params.target??game.user.targets.first()??null,context=await actor.getDamageRollContext({item,statistic:strike,target:{token:targetToken},viewOnly:params.getFormula??!1,domains:domains2,checkContext:params.checkContext,outcome,traits:actionTraits2,options:new Set([...baseOptions,...params.options??[]])});if(!context.self.item.dealsDamage&&!params.getFormula)return ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null;const{self,target}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options:context.options,domains:domains2,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.fromNPCAttack({attack:context.self.item,actor:context.self.actor,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)},"damageRoll");return strike.damage=damageRoll("success"),strike.critical=damageRoll("criticalSuccess"),strike}__name(strikeFromMeleeItem,"strikeFromMeleeItem"),__name2(strikeFromMeleeItem,"strikeFromMeleeItem");function getRangeIncrement(attackItem,distance){if(!attackItem.isOfType("action","melee","weapon"))return null;const{increment}=attackItem.range??{};return increment&&typeof distance=="number"?Math.max(Math.ceil(distance/increment),1):null}__name(getRangeIncrement,"getRangeIncrement"),__name2(getRangeIncrement,"getRangeIncrement");function calculateRangePenalty(actor,increment,selectors,rollOptions){if(!increment||increment===1)return null;const slug="range-penalty",modifier=new ModifierPF2e({label:"PF2E.RangePenalty",slug,type:"untyped",modifier:Math.max((increment-1)*-2,-12),predicate:[{nor:["ignore-range-penalty",{gte:["ignore-range-penalty",increment]}]}],adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,selectors,slug)});return modifier.test(rollOptions),modifier}__name(calculateRangePenalty,"calculateRangePenalty"),__name2(calculateRangePenalty,"calculateRangePenalty");function isReallyPC(actor){const traits=actor.traits;return actor.isOfType("character")&&!(traits.has("minion")||traits.has("eidolon"))}__name(isReallyPC,"isReallyPC"),__name2(isReallyPC,"isReallyPC");function findMatchingCheckContext(actor,params){if(params.viewOnly||!params.target?.token)return null;const paramsItem=params.item;return paramsItem?.isOfType("melee","weapon")?game.messages.contents.slice(-3).reverse().find(message=>{if(!message.rolls.some(r=>r instanceof CheckRoll)||message.actor?.uuid!==actor.uuid||params.target?.token!==message.target?.token.object)return!1;const messageItem=message.item;if(!messageItem?.isOfType("melee","weapon"))return!1;const paramsItemSlug=paramsItem.slug??sluggify(paramsItem.name),messageItemSlug=messageItem.slug??sluggify(messageItem.name);return paramsItemSlug===messageItemSlug&¶msItem.uuid===messageItem.uuid&¶msItem.isMelee===messageItem.isMelee})?.flags.pf2e.context??null:null}__name(findMatchingCheckContext,"findMatchingCheckContext"),__name2(findMatchingCheckContext,"findMatchingCheckContext");class Statistic extends BaseStatistic{static{__name(this,"Statistic")}static{__name2(this,"Statistic")}attribute=null;rank=null;proficient=!0;base=null;lore;config;#check;#dc;constructor(actor,data,config={}){data.modifiers??=[];const domains=data.domains??=[],attributeModifier=actor.isOfType("character")&&data.attribute?data.modifiers.find(m=>m.type==="ability"&&m.ability===data.attribute)??createAttributeModifier({actor,attribute:data.attribute,domains}):null;data.attribute&&domains.push(`${data.attribute}-based`);const proficiencyModifier=actor.isOfType("character")?typeof data.rank=="number"?createProficiencyModifier({actor,rank:data.rank,domains}):data.rank==="untrained-level"?createProficiencyModifier({actor,rank:0,domains,addLevel:!0}):null:null,baseModifiers=compact([attributeModifier,proficiencyModifier]),activeSlugs=new Set(baseModifiers.map(m=>m.slug));data.modifiers=data.modifiers.filter(m=>!activeSlugs.has(m.slug)),data.modifiers.unshift(...baseModifiers),super(actor,data),this.attribute=data.attribute??null,typeof data.lore=="boolean"&&(this.lore=data.lore),this.rank=data.rank==="untrained-level"?0:data.rank??null,this.config=config,this.proficient=data.proficient===void 0?this.rank===null||this.rank>0:!!data.proficient,data.filter&&(this.modifiers=this.modifiers.filter(data.filter)),this.data.dc??={domains:[`${this.slug}-dc`]}}get attributeModifier(){return this.actor.isOfType("npc")?this.attribute?createAttributeModifier({actor:this.actor,attribute:this.attribute,domains:this.domains}):null:this.modifiers.find(m=>m.type==="ability"&&m.enabled&&m.ability===this.attribute)??null}get check(){return this.#check??=new StatisticCheck(this,this.data,this.config)}get dc(){return this.#dc??=new StatisticDifficultyClass(this,this.data,this.config)}get mod(){return this.check.mod}get ability(){return foundry.utils.logCompatibilityWarning("`Statistic#ability` is deprecated. Use `Statistic#attribute` instead.",{since:"5.5.0",until:"6.0.0"}),this.attribute}createRollOptions(domains=this.domains,args={}){const{item,extraRollOptions,origin,target}=args,rollOptions=[];return domains.length>0&&rollOptions.push(...super.createRollOptions(domains)),typeof this.rank=="number"&&rollOptions.push(PROFICIENCY_RANK_OPTION[this.rank]),this.data.rollOptions&&rollOptions.push(...this.data.rollOptions),item&&(rollOptions.push(...item.getRollOptions("item")),item.actor&&item.actor.uuid!==this.actor.uuid&&rollOptions.push(...item.actor.getSelfRollOptions("origin")),(item.system.traits?.value??[]).includes("attack")&&rollOptions.push("trait:attack")),origin?rollOptions.push(...origin.getSelfRollOptions("origin")):target&&rollOptions.push(...target.getSelfRollOptions("target")),extraRollOptions&&rollOptions.push(...extraRollOptions),new Set(rollOptions)}withRollOptions(options){const newOptions=foundry.utils.mergeObject(this.config??{},options??{},{inplace:!1});return new Statistic(this.actor,foundry.utils.deepClone(this.data),newOptions)}extend(data){function maybeMergeArrays(arr1,arr2){if(!(!arr1&&!arr2))return[...new Set([arr1??[],arr2??[]].flat())]}__name(maybeMergeArrays,"maybeMergeArrays"),__name2(maybeMergeArrays,"maybeMergeArrays");const result=foundry.utils.mergeObject(foundry.utils.deepClone(this.data),data);result.domains=maybeMergeArrays(this.domains,data.domains),result.modifiers=maybeMergeArrays(this.data.modifiers,data.modifiers),result.rollOptions=maybeMergeArrays(this.data.rollOptions,data.rollOptions),result.check&&this.data.check&&(result.check.domains=maybeMergeArrays(this.data.check.domains,data.check?.domains),result.check.modifiers=maybeMergeArrays(this.data.check.modifiers,data.check?.modifiers)),result.dc&&this.data.dc&&(result.dc.domains=maybeMergeArrays(this.data.dc.domains,data.dc?.domains),result.dc.modifiers=maybeMergeArrays(this.data.dc.modifiers,data.dc?.modifiers));const extended=new Statistic(this.actor,result,this.config);return extended.base=this,extended}roll(args={}){return this.check.roll(args)}getChatData(options={}){const{check,dc}=this.withRollOptions(options),{map1,map2}=options.item?calculateMAPs(options.item,{domains:check?.domains??[],options:check?.createRollOptions(options)??[]}):{map1:-5,map2:-10};return{slug:this.slug,label:this.label,rank:this.rank,check:{mod:check.mod,breakdown:check.breakdown,label:check.label,map1,map2},dc:{value:dc.value,breakdown:dc.breakdown}}}getTraceData(options={}){const{check,dc}=this,valueProp=options.value??"mod",[label,value,totalModifier,breakdown,modifiers]=valueProp==="mod"?[this.label,check.mod,check.mod,check.breakdown,check.modifiers]:[dc.label||this.label,dc.value,dc.value-10,dc.breakdown,dc.modifiers];return{slug:this.slug,label,value,totalModifier,dc:dc.value,breakdown,modifiers:modifiers.map(m=>m.toObject())}}}class StatisticCheck{static{__name(this,"StatisticCheck")}static{__name2(this,"StatisticCheck")}parent;type;label;domains;mod;modifiers;constructor(parent,data,config={}){this.parent=parent,this.type=data.check?.type??"check",data.check=foundry.utils.mergeObject(data.check??{},{type:this.type});const checkDomains=new Set(compact(["check",data.check.domains].flat()));this.type==="attack-roll"?(checkDomains.add("attack"),checkDomains.add("attack-roll"),checkDomains.add(`${this.parent.slug}-attack-roll`)):(checkDomains.add(`${this.parent.slug}-check`),this.type==="flat-check"&&(checkDomains.delete("check"),checkDomains.add("flat-check"))),data.check.domains=Array.from(checkDomains),this.domains=uniq(compact([data.domains,data.check.domains].flat())),this.label=this.#determineLabel(data);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.check?.domains??[],clone.slug)),clone}),checkOnlyModifiers=[data.check?.modifiers??[],extractModifiers(parent.actor.synthetics,data.check?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier)),rollOptions=parent.createRollOptions(this.domains,config);this.modifiers=[...parentModifiers,...checkOnlyModifiers.map(modifier=>modifier.clone({test:rollOptions}))],this.type==="flat-check"&&this.modifiers.length>0&&(console.error(ErrorPF2e("Flat checks cannot have modifiers.").message),this.modifiers=[]),this.mod=new StatisticModifier(this.label,this.modifiers,rollOptions).totalModifier}get actor(){return this.parent.actor}#determineLabel(data){const parentLabel=this.parent.label;if(data.check?.label)return game.i18n.localize(data.check?.label);if(this.domains.includes("spell-attack-roll"))return game.i18n.format("PF2E.SpellAttackWithTradition",{tradition:parentLabel});switch(this.type){case"skill-check":return game.i18n.format("PF2E.SkillCheckWithName",{skillName:parentLabel});case"saving-throw":return game.i18n.format("PF2E.SavingThrowWithName",{saveName:parentLabel});case"perception-check":return game.i18n.format("PF2E.PerceptionCheck");default:return parentLabel}}createRollOptions(args={}){return this.parent.createRollOptions(this.domains,args)}async roll(args={}){args.dc=typeof args.dc=="number"?{value:Math.trunc(args.dc)||0}:args.dc??null;const{rollMode,skipDialog}=(()=>{if(isObject(args)){const event2=args.event?.originalEvent??args.event;if(event2 instanceof MouseEvent){const{rollMode:rollMode2,skipDialog:skipDialog2}=args;return foundry.utils.mergeObject({rollMode:rollMode2,skipDialog:skipDialog2},eventToRollParams(event2,{type:"check"}))}}return args})(),{domains}=this,token=args.token??this.actor.getActiveTokens(!1,!0).shift(),item=args.item??null,{origin}=args,targetToken=origin?null:(args.target?.getActiveTokens()??Array.from(game.user.targets)).find(t=>t.actor?.isOfType("army","creature","hazard"))??null,rollContext=await(()=>{const isValidAttacker=targetToken?.actor?.isOfType("army")?this.actor.isOfType("army"):this.actor.isOfType("creature","hazard"),isTargetedCheck=this.domains.includes("spell-attack-roll")&&item?.isOfType("spell")||!["flat-check","saving-throw"].includes(this.type)&&!!(args.dc?.slug||"statistic"in(args.dc??{}))&&(!item||item.isOfType("action","campaignFeature","feat","weapon"));return isValidAttacker&&isTargetedCheck?this.actor.getCheckContext({item:item?.isOfType("action","melee","spell","weapon")?item:null,domains,statistic:this,target:targetToken,defense:args.dc?.slug??"armor",melee:args.melee,options:new Set(args.extraRollOptions??[])}):null})(),selfActor=rollContext?.self.actor??this.actor,targetActor=origin?null:rollContext?.target?.actor??args.target??null,dc=typeof args.dc?.value=="number"?args.dc:rollContext?.dc??null,extraModifiers=this.type==="flat-check"?[]:compact([args.modifiers,rollContext?.self.modifiers].flat()),extraRollOptions=[...args.extraRollOptions??[],...rollContext?.options??[],`check:statistic:${this.parent.slug}`,`check:type:${this.type.replace(/-check$/,"")}`];this.parent.base&&extraRollOptions.push(`check:statistic:base:${this.parent.base.slug}`);const options=this.createRollOptions({...args,origin,target:targetActor,extraRollOptions}),notes=[...extractNotes(selfActor.synthetics.rollNotes,domains),...args.extraRollNotes??[]];for(const rule of selfActor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const dosAdjustments=dc?extractDegreeOfSuccessAdjustments(selfActor.synthetics,domains):[];if((options.has("incapacitation")||options.has("item:trait:incapacitation"))&&dc){const effectLevel=item?.isOfType("spell")?2*item.rank:item?.isOfType("physical")?item.level:origin?.level??selfActor.level,amount=this.type==="saving-throw"&&selfActor.level>effectLevel?DEGREE_ADJUSTMENT_AMOUNTS.INCREASE:targetActor&&targetActor.level>effectLevel&&["attack-roll","spell-attack-roll","skill-check"].includes(this.type)?DEGREE_ADJUSTMENT_AMOUNTS.LOWER:null;amount&&dosAdjustments.push({adjustments:{all:{label:"PF2E.TraitIncapacitation",amount}}})}const mapIncreases=Math.clamped((args.attackNumber??1)-1,0,2);if(mapIncreases!==0)if(!item)console.warn("Missing item argument while calculating MAP during check");else{const maps=calculateMAPs(item,{domains,options}),penalty=maps[`map${mapIncreases}`];extraModifiers.push(new ModifierPF2e(maps.label,penalty,"untyped"))}const traits=args.traits?.map(t=>typeof t=="string"?t:t.name).filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const trait of traits)options.add(trait);if(args.action){options.add(`self:action:slug:${sluggify(args.action)}`);for(const trait of traits)options.add(`self:action:trait:${trait}`)}const context={actor:selfActor,token,item,type:this.type,identifier:args.identifier,domains,target:rollContext?.target??null,dc,notes,options,action:args.action,damaging:args.damaging,rollMode,skipDialog,rollTwice:args.rollTwice||extractRollTwice(selfActor.synthetics.rollTwice,domains,options),substitutions:extractRollSubstitutions(selfActor.synthetics.rollSubstitutions,domains,options),dosAdjustments,traits,title:args.title?.trim()||args.label?.trim()||this.label,createMessage:args.createMessage??!0};typeof args.attackNumber=="number"&&(context.mapIncreases=mapIncreases,context.options?.add(`map:increases:${mapIncreases}`));const check=new CheckModifier(this.parent.slug,{modifiers:this.modifiers},extraModifiers),roll=await CheckPF2e.roll(check,context,null,args.callback);if(roll)for(const rule of selfActor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context,domains,rollOptions:options});return roll}get breakdown(){return this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ")}}class StatisticDifficultyClass{static{__name(this,"StatisticDifficultyClass")}static{__name2(this,"StatisticDifficultyClass")}parent;domains;label;modifiers;options;constructor(parent,data,options={}){this.parent=parent,this.domains=uniq(compact([data.domains,data.dc?.domains].flat())),this.label=data.dc?.label,this.options=parent.createRollOptions(this.domains,options);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.dc?.domains??[],clone.slug)),clone}),dcOnlyModifiers=[data.dc?.modifiers??[],extractModifiers(parent.actor.synthetics,data.dc?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier));this.modifiers=[...new StatisticModifier("",[...parentModifiers,...dcOnlyModifiers.map(m=>m.clone())],this.options).modifiers]}get value(){return 10+new StatisticModifier("",this.modifiers.map(m=>m.clone()),this.options).totalModifier}get breakdown(){const enabledMods=this.modifiers.filter(m=>m.enabled);return[game.i18n.localize("PF2E.DCBase")].concat(enabledMods.map(m=>`${m.label} ${signedInteger(m.modifier)}`)).join(", ")}toString(){return String(this.value)}}class ArmorStatistic extends Statistic{static{__name(this,"ArmorStatistic")}static{__name2(this,"ArmorStatistic")}details;get item(){return this.actor.isOfType("character")?this.actor.wornArmor:null}constructor(actor,data={}){data.rank??=1;const attribute=actor.isOfType("creature")?data.attribute??"dex":null,domains=attribute?["all",`${attribute}-based`]:["all"],fullData={...data,label:"TYPES.Item.armor",slug:"armor",attribute,domains,proficient:data.rank>0,dc:{label:"PF2E.ArmorClassLabel",domains:["ac"],modifiers:[]}};super(actor,fullData),this.details=data.details??"";const dcModifiers=[...this.dc.modifiers,...this.#createBonusesAndPenalties()].map(m=>m.clone());this.dc.modifiers=[...new StatisticModifier("",dcModifiers,this.dc.options).modifiers]}#createBonusesAndPenalties(){const{actor}=this,armor=actor.isOfType("character")?actor.wornArmor:null,armorSlug=armor?.baseType??armor?.slug??sluggify(armor?.name??""),itemBonus=armor?new ModifierPF2e({label:armor.name,type:"item",slug:armorSlug,modifier:armor.acBonus,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","ac"],armorSlug)}):null;return compact([itemBonus,createShoddyPenalty(actor,armor,this.dc.domains),this.#createShieldBonus()])}#createShieldBonus(){const{actor}=this;if(!actor.isOfType("character","npc"))return null;const shieldData=actor.system.attributes.shield,slug="raised-shield";return shieldData.raised&&!shieldData.broken?new ModifierPF2e({label:shieldData.name,slug,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","dex-based","ac"],slug),type:"circumstance",modifier:shieldData.ac}):null}getTraceData(){return{...super.getTraceData({value:"dc"}),details:this.details,breakdown:this.dc.breakdown}}}class HitPointsStatistic extends BaseStatistic{static{__name(this,"HitPointsStatistic")}static{__name2(this,"HitPointsStatistic")}value;max;#baseMax;temp;negativeHealing;unrecoverable;details;constructor(actor,{baseMax=0}={}){const modifiers=actor.isOfType("character")?[createAttributeModifier({actor,attribute:"con",domains:["hp","con-based"]})]:[];super(actor,{slug:"hp",label:"PF2E.HitPointsHeader",domains:actor.isOfType("character","npc")?["con-based","hp"]:["hp"],modifiers}),this.#baseMax=baseMax,this.max=baseMax+new StatisticModifier("",this.modifiers.map(m=>m.clone())).totalModifier,this.value=Math.clamped(actor.system.attributes.hp.value,0,this.max),this.temp=actor.system.attributes.hp.temp,this.negativeHealing=actor.system.attributes.hp.negativeHealing,this.unrecoverable=actor.system.attributes.hp.unrecoverable,this.details=actor.system.attributes.hp.details||""}get breakdown(){return compact([this.#baseMax>0?game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base:this.#baseMax}):null,...this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)]).join(", ")}getTraceData(){return{slug:this.slug,label:this.label,value:this.value,max:this.max,temp:this.temp,breakdown:this.breakdown,negativeHealing:this.negativeHealing,unrecoverable:this.unrecoverable,details:this.details,modifiers:this.modifiers.map(m=>m.toObject())}}}const TRICK_MAGIC_SKILLS=["arcana","nature","occultism","religion"],TrickMagicTradition={arcana:"arcane",nature:"primal",occultism:"occult",religion:"divine"},traditionSkills={arcane:"arcana",divine:"religion",occult:"occultism",primal:"nature"};class TrickMagicItemEntry{static{__name(this,"TrickMagicItemEntry")}static{__name2(this,"TrickMagicItemEntry")}id;actor;skill;statistic;attribute;get ability(){return foundry.utils.logCompatibilityWarning("`TrickMagicItemEntry#ability` is deprecated. Use `TrickMagicItemEntry#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}tradition;constructor(actor,skill){if(!actor.isOfType("character"))throw ErrorPF2e("Trick magic entries may only be constructed with PCs");this.actor=actor,this.skill=skill,this.id=`trick-${this.skill}`;const attributes=actor.abilities,{attribute}=["int","wis","cha"].map(attribute2=>({attribute:attribute2,mod:attributes[attribute2].mod})).reduce((highest,next)=>next.mod>highest.mod?next:highest);this.attribute=attribute;const tradition=this.tradition=TrickMagicTradition[skill],selectors=[`${attribute}-based`,"all","spell-attack-dc"],attackSelectors=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],saveSelectors=[`${tradition}-spell-dc`,"spell-dc"],skillRank=actor.skills[skill].rank,trickRank=skillRank===4?2:skillRank===3?1:0;this.statistic=new Statistic(actor,{slug:`trick-${tradition}`,label:CONFIG.PF2E.magicTraditions[tradition],attribute,rank:trickRank||"untrained-level",modifiers:extractModifiers(actor.synthetics,selectors),domains:selectors,check:{type:"attack-roll",modifiers:extractModifiers(actor.synthetics,attackSelectors),domains:attackSelectors},dc:{modifiers:extractModifiers(actor.synthetics,saveSelectors),domains:saveSelectors}})}get name(){return game.i18n.localize("PF2E.TrickMagicItemPopup.Title")}get sort(){return 0}get category(){return"items"}get spells(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!1}get isSpontaneous(){return!1}canCast(){return!0}async cast(spell,options={}){const{rollMode,message}=options,castLevel=spell.computeCastRank(spell.rank);if(message!==!1)try{spell.trickMagicEntry=this,await spell.toMessage(void 0,{rollMode,data:{castLevel}})}finally{spell.trickMagicEntry=null}}async getSheetData(){return{id:this.id,name:this.name,statistic:this.statistic.getChatData(),tradition:this.tradition,category:"items",hasCollection:!1,sort:0,levels:[],usesSpellProficiency:!1,spellPrepList:null}}}const CANTRIP_DECK_ID="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(type,heightenedLevel){switch(type){case"cantripDeck5":return CANTRIP_DECK_ID;case"scroll":return scrollCompendiumIds[heightenedLevel]??null;default:return wandCompendiumIds[heightenedLevel]??null}}__name(getIdForSpellConsumable,"getIdForSpellConsumable"),__name2(getIdForSpellConsumable,"getIdForSpellConsumable");function getNameForSpellConsumable(type,spellName,heightenedLevel){const templateId=SPELL_CONSUMABLE_NAME_TEMPLATES[type]||`${type} of {name} (Level {level})`;return game.i18n.format(templateId,{name:spellName,level:heightenedLevel})}__name(getNameForSpellConsumable,"getNameForSpellConsumable"),__name2(getNameForSpellConsumable,"getNameForSpellConsumable");function isSpellConsumable(itemId){return itemId===CANTRIP_DECK_ID||Object.values(scrollCompendiumIds).includes(itemId)||Object.values(wandCompendiumIds).includes(itemId)}__name(isSpellConsumable,"isSpellConsumable"),__name2(isSpellConsumable,"isSpellConsumable");async function createConsumableFromSpell(spell,{type,heightenedLevel=spell.baseRank,mystified=!1}){const pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd"),itemId=getIdForSpellConsumable(type,heightenedLevel),consumable=await pack?.getDocument(itemId??"");if(!(consumable instanceof ConsumablePF2e))throw ErrorPF2e("Failed to retrieve consumable item");const consumableSource={...consumable.toObject(),_id:null},{traits}=consumableSource.system;traits.value=uniq([...traits.value,...spell.traits]),traits.rarity=spell.rarity,traits.value.includes("magical")&&traits.value.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&traits.value.splice(traits.value.indexOf("magical"),1),traits.value.sort(),consumableSource.name=getNameForSpellConsumable(type,spell.name,heightenedLevel);const description=consumableSource.system.description.value;return consumableSource.system.description.value=(()=>{const paragraphElement=document.createElement("p");paragraphElement.append(spell.sourceId?`@UUID[${spell.sourceId}]{${spell.name}}`:spell.description);const containerElement=document.createElement("div"),hrElement=document.createElement("hr");return containerElement.append(paragraphElement,hrElement),hrElement.insertAdjacentHTML("afterend",description),containerElement.innerHTML})(),type!=="cantripDeck5"&&(consumableSource.system.spell=spell.clone({"system.location.heightenedLevel":heightenedLevel}).toObject()),mystified&&(consumableSource.system.identification.status="unidentified"),consumableSource}__name(createConsumableFromSpell,"createConsumableFromSpell"),__name2(createConsumableFromSpell,"createConsumableFromSpell");function calculateTrickMagicItemCheckDC(item,options={pwol:!1}){const level=Number(item.level),saveDC=calculateDC(level,options),traditions=item.system.spell?.system.traits.traditions??[],skills=[...item.system.traits.value,...traditions].filter(t=>setHasElement(MAGIC_TRADITIONS,t)).map(tradition=>[traditionSkills[tradition],saveDC]);return Object.fromEntries(skills)}__name(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC"),__name2(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC");async function preImportJSON(document2,json2){const source=JSON.parse(json2);if(!isObject(source)||("data"in source&&("items"in source?ActorPF2e.migrateData(source):ItemPF2e.migrateData(source)),!isObject(source.system)))return null;const sourceSchemaVersion=Number(source.system?._migration?.version)||0,worldSchemaVersion=MigrationRunnerBase.LATEST_SCHEMA_VERSION;if(foundry.utils.isNewerVersion(sourceSchemaVersion,worldSchemaVersion))return ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.CantImportTooHighVersion",{sourceName:game.i18n.localize("DOCUMENT.Actor"),sourceSchemaVersion,worldSchemaVersion})),null;const newDoc=new document2.constructor(source,{parent:document2.parent}),migrations=MigrationList.constructFromVersion(newDoc.schemaVersion);return await MigrationRunner.ensureSchemaVersion(newDoc,migrations),JSON.stringify(newDoc.toObject())}__name(preImportJSON,"preImportJSON"),__name2(preImportJSON,"preImportJSON");function combatantAndTokenDoc(document2){return document2 instanceof CombatantPF2e?{combatant:document2,tokenDoc:document2.token}:{combatant:document2.combatant,tokenDoc:document2}}__name(combatantAndTokenDoc,"combatantAndTokenDoc"),__name2(combatantAndTokenDoc,"combatantAndTokenDoc");async function processGrantDeletions(item,pendingItems){const{actor}=item,granter=actor.items.get(item.flags.pf2e.grantedBy?.id??""),parentGrant=Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===item.id),grants=Object.values(item.flags.pf2e.itemGrants);if(granter&&parentGrant?.onDelete==="restrict"&&!pendingItems.includes(granter)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:granter.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}for(const grant of grants){const grantee=actor.items.get(grant.id);if(grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="restrict"&&!pendingItems.includes(grantee)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:grantee.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}}granter&&parentGrant?.onDelete==="cascade"&&!pendingItems.includes(granter)&&(pendingItems.push(granter),await processGrantDeletions(granter,pendingItems));for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="cascade"&&!pendingItems.includes(grantee)&&(pendingItems.push(grantee),await processGrantDeletions(grantee,pendingItems))}const[key]=Object.entries(granter?.flags.pf2e.itemGrants??{}).find(([,g])=>g===parentGrant)??[null];granter&&key&&!pendingItems.includes(granter)&&await granter.update({[`flags.pf2e.itemGrants.-=${key}`]:null},{render:!1});for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="detach"&&!pendingItems.includes(grantee)&&await grantee.update({"flags.pf2e.-=grantedBy":null},{render:!1})}}__name(processGrantDeletions,"processGrantDeletions"),__name2(processGrantDeletions,"processGrantDeletions");class ItemPF2e extends Item{static{__name(this,"ItemPF2e")}static{__name2(this,"ItemPF2e")}static getDefaultArtwork(itemData){return{img:`systems/pf2e/icons/default-icons/${itemData.type}.svg`}}get slug(){return this.system.slug}get sourceId(){return this.flags.core?.sourceId??null}get schemaVersion(){return Number(this.system._migration?.version??this.system.schema?.version)||null}get description(){return this.system.description.value.trim()}get grantedBy(){return this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"")??null}get inMemoryOnly(){return!this.collection.has(this.id)}static fromDropData(data,options){if("uuid"in data&&UUIDUtils.isItemUUID(data.uuid)){const item=fromUuidSync(data.uuid);item instanceof ItemPF2e&&item.parent&&!item.sourceId&&(item._source.flags=foundry.utils.mergeObject(item._source.flags,{core:{sourceId:item.uuid}}),item.flags=foundry.utils.mergeObject(item.flags,{core:{sourceId:item.uuid}}))}return super.fromDropData(data,options)}isOfType(...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,this.type):this.type===t)}async delete(context={}){return this.actor?(await this.actor.deleteEmbeddedDocuments("Item",[this.id],context),this):super.delete(context)}getRollOptions(prefix=this.type){if(prefix.length===0)throw ErrorPF2e("`prefix` must be at least one character long");const slug=this.slug??sluggify(this.name),{value:traits=[],otherTags}=this.system.traits,traitOptions=(()=>{const damageType=Object.keys(CONFIG.PF2E.damageTypes).join("|"),diceOrNumber=/-(?:[0-9]*d)?[0-9]+(?:-min)?$/,versatile=new RegExp(`-(?:b|p|s|${damageType})$`),deannotated=traits.filter(t=>diceOrNumber.test(t)||versatile.test(t)).map(t=>t.replace(diceOrNumber,"").replace(versatile,""));return[traits,deannotated].flat().map(t=>`trait:${t}`)})(),options=[`${prefix}:id:${this.id}`,`${prefix}:${slug}`,`${prefix}:slug:${slug}`,...traitOptions.map(t=>`${prefix}:${t}`),...otherTags.map(t=>`${prefix}:tag:${t}`)];(this.isOfType("spell")||traits.some(t=>["magical",...MAGIC_TRADITIONS].includes(t)))&&options.push(`${prefix}:magical`);const level=this.isOfType("spell")?this.rank:this.system.level?.value??null;typeof level=="number"&&options.push(`${prefix}:level:${level}`);const itemType=this.isOfType("feat")&&this.isFeature?"feature":this.type;return prefix!==itemType&&options.unshift(`${prefix}:type:${itemType}`),options}getRollData(){return{...this.actor?.getRollData()??{actor:null},item:this}}async toMessage(event2,options={}){if(!this.actor)throw ErrorPF2e(`Cannot create message for unowned item ${this.name}`);const template=`systems/pf2e/templates/chat/${sluggify(this.type)}-card.hbs`,token=this.actor.token,nearestItem=htmlClosest(event2?.target,".item"),rollOptions=options.data??{...nearestItem?.dataset??{}},templateData={actor:this.actor,tokenId:token?`${token.parent?.id}.${token.id}`:null,item:this,data:await this.getChatData(void 0,rollOptions)},originalEvent=event2 instanceof MouseEvent?event2:event2?.originalEvent,rollMode=options.rollMode??eventToRollMode(originalEvent),chatData=ChatMessagePF2e.applyRollMode({type:CONST.CHAT_MESSAGE_TYPES.OTHER,speaker:ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.actor.getActiveTokens(!1,!0).at(0)}),content:await renderTemplate(template,templateData),flags:{pf2e:{origin:this.getOriginData()}}},rollMode);return options.create??!0?ChatMessagePF2e.create(chatData,{rollMode,renderSheet:!1}):new ChatMessagePF2e(chatData,{rollMode})}async toChat(event2){return this.toMessage(event2,{create:!0})}_initialize(options){this.rules=[],super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){super.prepareBaseData();const{flags}=this;flags.pf2e=foundry.utils.mergeObject(flags.pf2e??{},{rulesSelections:{}}),this.system.slug||=null,isObject(flags.pf2e.grantedBy)&&(flags.pf2e.grantedBy.onDelete??=this.isOfType("physical")?"detach":"cascade");const grants=flags.pf2e.itemGrants??={};for(const grant of Object.values(grants))isObject(grant)&&(grant.onDelete??="detach")}prepareRuleElements(options={}){if(!this.actor)throw ErrorPF2e("Rule elements may only be prepared from embedded items");return this.rules=this.actor.canHostRuleElements?RuleElements.fromOwnedItem({...options,parent:this}):[]}async refreshFromCompendium(options={name:!0,notify:!0}){if(!this.isOwned)throw ErrorPF2e("This utility may only be used on owned items");if(!this.sourceId?.startsWith("Compendium."))throw ErrorPF2e(`Item "${this.name}" has no compendium source.`);options.name??=!0,options.notify??=!0;const currentSource=this.toObject();if(currentSource.system.rules.some(r=>typeof r.key=="string"&&["ChoiceSet","GrantItem"].includes(r.key))){ui.notifications.warn("PF2E.Item.RefreshFromCompendium.Tooltip.Disabled",{localize:!0});return}const latestSource=(await fromUuid(this.sourceId))?.toObject();if(latestSource){if(latestSource.type!==this.type){ui.notifications.error(`The compendium source for "${this.name}" is of a different type than what is present on this actor.`);return}}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:this.name,sourceId:this.sourceId}));return}const updates={name:options.name?latestSource.name:currentSource.name,img:latestSource.img,system:foundry.utils.deepClone(latestSource.system)};if(updates.system.level&¤tSource.type==="feat"&&(updates.system.level={value:updates.system.level.value,taken:currentSource.system.level.taken}),isPhysicalData(currentSource)){if(foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.containerId":currentSource.system.containerId,"system.equipped":currentSource.system.equipped,"system.material":currentSource.system.material,"system.quantity":currentSource.system.quantity,"system.size":currentSource.system.size})),itemIsOfType(currentSource,"armor","shield","weapon")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.runes":currentSource.system.runes})),currentSource.type==="consumable"&¤tSource.system.spell?.system?.traits&&tupleHasValue(["scroll","wand"],currentSource.system.category)&&latestSource.type==="consumable"&&!latestSource.system.spell){const spellSourceId=currentSource.system.spell.flags.core?.sourceId??"",refreshedSpell=await fromUuid(currentSource.system.spell.flags.core?.sourceId??"");if(refreshedSpell instanceof ItemPF2e&&refreshedSpell.isOfType("spell")){const spellConsumableData=await createConsumableFromSpell(refreshedSpell,{type:currentSource.system.category,heightenedLevel:currentSource.system.spell.system.location.heightenedLevel});foundry.utils.mergeObject(updates,{name:spellConsumableData.name,system:{spell:spellConsumableData.system.spell}})}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:currentSource.system.spell.name,sourceId:spellSourceId}));return}}}else itemIsOfType(currentSource,"campaignFeature","feat","spell")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.location":currentSource.system.location}));currentSource.type==="feat"&¤tSource.system.level.taken&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.level.taken":currentSource.system.level.taken})),await this.update(updates,{diff:!1,recursive:!1}),options.notify&&ui.notifications.info(`Item "${this.name}" has been refreshed.`)}getOriginData(){return{actor:this.actor?.uuid,uuid:this.uuid,type:this.type}}async processChatData(htmlOptions={},data){if(data.properties=data.properties?.filter(property=>property!==null)??[],isItemSystemData(data)){const chatData=foundry.utils.duplicate(data);return htmlOptions.rollData=foundry.utils.mergeObject(this.getRollData(),htmlOptions.rollData??{}),chatData.description.value=await TextEditor.enrichHTML(chatData.description.value,{...htmlOptions,async:!0}),chatData}return data}async getChatData(htmlOptions={},_rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned item ${this.name}`);const systemData={...this.system,traits:this.traitChatData()};return this.processChatData(htmlOptions,foundry.utils.deepClone(systemData))}traitChatData(dictionary={},traits=this.system.traits.value??[]){return traits.map(trait=>{const label=game.i18n.localize(dictionary[trait]??trait),traitDescriptions2=CONFIG.PF2E.traitsDescriptions;return{value:trait,label,description:traitDescriptions2[trait]}}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang))}static async createDialog(data={},context={}){const omittedTypes=["condition","spellcastingEntry","lore"];omittedTypes.push("affliction","book"),game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("campaignFeature");const original=game.system.documentTypes.Item;try{return game.system.documentTypes.Item=difference(original,omittedTypes),super.createDialog(data,{...context,classes:[...context.classes??[],"dialog-item-create"]})}finally{game.system.documentTypes.Item=original}}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}toDragData(){return{...super.toDragData(),itemType:this.type}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ItemPF2e?d.toObject():d);for(const source of[...sources]){if(source.effects=[],!Object.keys(source).some(k=>k.startsWith("flags")||k.startsWith("system"))){source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}};continue}const item=new CONFIG.Item.documentClass(source);await MigrationRunner.ensureSchemaVersion(item,MigrationList.constructFromVersion(item.schemaVersion)),data.splice(data.indexOf(source),1,item.toObject())}const actor=context.parent;if(!actor)return super.createDocuments(sources,context);if(sources.some(s=>!actor.checkItemValidity(s)))return[];const effectSources=sources.filter(s=>["affliction","condition","effect"].includes(s.type));for(const source of effectSources){const effect=new CONFIG.PF2E.Item.documentClasses[source.type](foundry.utils.deepClone(source),{parent:actor}),isUnaffected=effect.isOfType("condition")&&!actor.isAffectedBy(effect),isImmune=actor.isImmuneTo(effect);if((isUnaffected||isImmune)&&(sources.splice(sources.indexOf(source),1),!(effect.isOfType("effect")&&effect.fromAura))){const locKey=isUnaffected?"PF2E.Damage.IWR.ActorIsUnaffected":"PF2E.Damage.IWR.ActorIsImmune",message=game.i18n.format(locKey,{actor:actor.name,effect:effect.name});ui.notifications.info(message)}}const preCreateDeletions=["ancestry","background","class","heritage","deity"].filter(type=>sources.some(s=>s.type===type)).flatMap(type=>actor.itemTypes[type]);if(preCreateDeletions.length){const idsToDelete=preCreateDeletions.map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",idsToDelete,{render:!1})}const items=await(async()=>{async function getSimpleGrants(item){const granted=await item.createGrantedItems?.({size:context.parent?.size})??[];if(!granted.length)return[];const reparented=granted.map(i=>i.parent?i:new CONFIG.Item.documentClass(i._source,{parent:actor}));return[...reparented,...(await Promise.all(reparented.map(getSimpleGrants))).flat()]}__name(getSimpleGrants,"getSimpleGrants"),__name2(getSimpleGrants,"getSimpleGrants");const items2=sources.map(source=>(context.keepId||context.keepEmbeddedIds||(source._id=foundry.utils.randomID()),new CONFIG.Item.documentClass(source,{parent:actor})));for(const item of[...items2]){const grants=await getSimpleGrants(item);grants.length&&(context.keepId=!0,items2.push(...grants))}return items2})(),outputSources=items.map(i=>i._source);for(const item of items){item.prepareActorData?.();const itemSource=item._source,rules=item.prepareRuleElements({suppressWarnings:!0});for(const rule of rules){const ruleSource=itemSource.system.rules[rules.indexOf(rule)];await rule.preCreate?.({itemSource,ruleSource,pendingItems:outputSources,tempItems:items,context})}}if(outputSources.some(i=>i.type==="class")){const classFeatures=outputSources.filter(i=>i.type==="feat"&&typeof i.system?.level?.value=="number"&&i.system.category==="classfeature"&&!i.flags?.pf2e?.grantedBy);for(const feature of classFeatures)feature.sort=classFeatures.indexOf(feature)*100*(feature.system.level?.value??1)}const nonKits=outputSources.filter(source=>source.type!=="kit");return super.createDocuments(nonKits,context)}static async deleteDocuments(ids=[],context={}){ids=Array.from(new Set(ids));const actor=context.parent;if(actor){const items=ids.flatMap(id=>actor.items.get(id)??[]),containers=items.filter(i=>i.isOfType("backpack"));for(const container of containers)await container.ejectContents();for(const item of[...items]){for(const rule of item.rules)await rule.preDelete?.({pendingItems:items,context});await processGrantDeletions(item,items)}ids=Array.from(new Set(items.map(i=>i.id))).filter(id=>actor.items.has(id))}return super.deleteDocuments(ids,context)}async _preCreate(data,options,user){if(this._source.system.traits.value?.sort(),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const hpMaxDifference=this.actor.clone({items:[...this.actor.items.toObject(),data]}).hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}return this._source.system.rules=this._source.system.rules.filter(r=>!r.removeUponCreate),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(changed.system?.description?.value===null&&(changed.system.description.value=""),changed.system?.level&&"value"in changed.system.level&&(changed.system.level.value=Math.max(0,Math.trunc(Number(changed.system.level.value)||0))),typeof changed.system?.slug=="string"&&(changed.system.slug=sluggify(changed.system.slug)||null),changed.system?.traits&&(Array.isArray(changed.system.traits.value)&&changed.system.traits.value.sort(),Array.isArray(changed.system.traits.otherTags)&&(changed.system.traits.otherTags=changed.system.traits.otherTags.map(t=>sluggify(t)).sort())),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const actorClone=this.actor.clone();actorClone.items.get(this.id,{strict:!0}).updateSource(changed,options),actorClone.reset();const hpMaxDifference=actorClone.hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}for(const rule of this.rules)await rule.preUpdate?.(changed);return super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.actor&&game.user.id===userId))return;this.actor.reset();const actorUpdates={};for(const rule of this.rules)rule.onCreate?.(actorUpdates);const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}_onUpdate(data,options,userId){super._onUpdate(data,options,userId),game.ready&&game.items.get(this.id)===this&&ui.items.render()}_onDelete(options,userId){if(super._onDelete(options,userId),!(this.actor&&game.user.id===userId)||!(this.actor.isOfType("creature")&&this.canUserModify(game.user,"update")))return;const actorUpdates={};for(const rule of this.rules)rule.onDelete?.(actorUpdates);if(this.actor.isOfType("npc")&&["action","consumable"].includes(this.type)){const slug=this.slug??sluggify(this.name);if(this.actor.isToken){const promises=[];for(const item of this.actor.itemTypes.melee){const attackEffects=item.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);promises.push(item.update({"system.attackEffects.value":updatedEffects}))}}promises.length>0&&Promise.allSettled(promises)}else{const itemUpdates=[];for(const attack of this.actor.itemTypes.melee){const attackEffects=attack.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);itemUpdates.push({_id:attack.id,system:{attackEffects:{value:updatedEffects}}})}}itemUpdates.length>0&&foundry.utils.mergeObject(actorUpdates,{items:itemUpdates})}}const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}}const ItemProxyPF2e=new Proxy(ItemPF2e,{construct(_target,args){const type=args[0]?.type==="armor"&&args[0].system?.category==="shield"?"shield":args[0]?.type,ItemClass=CONFIG.PF2E.Item.documentClasses[type]??ItemPF2e;return new ItemClass(...args)}}),DURATION_UNITS={rounds:6,minutes:60,hours:3600,days:86400};function calculateRemainingDuration(effect,durationData){if(durationData.unit==="encounter"){const isExpired=effect.system.expired;return{expired:!!isExpired,remaining:isExpired?0:1/0}}else if(durationData.unit==="unlimited"||!("start"in effect.system))return{expired:!1,remaining:1/0};const start=effect.system.start.value,{combatant}=game.combat??{},{unit,expiry}=durationData,duration=durationData.value*(DURATION_UNITS[durationData.unit]??0),addend=!combatant&&duration===0&&unit==="rounds"&&["turn-end","round-end"].includes(expiry??"")?1:0,remaining=start+duration+addend-game.time.worldTime,result={remaining,expired:remaining<=0};if(remaining===0&&combatant?.actor){const startInitiative=effect.system.start.initiative??0,currentInitiative=combatant.initiative??0,fightyActor=effect.actor?.isOfType("familiar")?effect.actor.master??effect.actor:effect.actor,atTurnStart=__name2(()=>startInitiative===currentInitiative&&combatant.actor===(effect.origin??fightyActor),"atTurnStart");result.expired=expiry==="turn-start"?atTurnStart():expiry==="turn-end"?currentInitiative<startInitiative:expiry==="round-end"?remaining<=0&&game.time.worldTime>start:!1}return result}__name(calculateRemainingDuration,"calculateRemainingDuration"),__name2(calculateRemainingDuration,"calculateRemainingDuration");class AbstractEffectPF2e extends ItemPF2e{static{__name(this,"AbstractEffectPF2e")}static{__name2(this,"AbstractEffectPF2e")}get origin(){const originUUID=this.system.context?.origin.actor;if(!originUUID||originUUID===this.actor?.uuid)return this.actor;if(originUUID.startsWith("Scene.")){const tokenUUID=originUUID.replace(/\.Actor\..+$/,""),tokenDoc=fromUuidSync(tokenUUID);if(!(tokenDoc instanceof TokenDocumentPF2e))return null;const descriptor=Object.getOwnPropertyDescriptor(tokenDoc,"delta");return descriptor?.value instanceof ActorDelta?descriptor.value.syntheticActor??null:null}const actor=fromUuidSync(originUUID);return actor instanceof ActorPF2e?actor:null}get isIdentified(){return!0}get isLocked(){return!1}get fromSpell(){return this.system.fromSpell}get totalDuration(){const{duration}=this.system;return["unlimited","encounter"].includes(duration.unit)?1/0:duration.value*(DURATION_UNITS[duration.unit]??0)}get remainingDuration(){return calculateRemainingDuration(this,this.system.duration)}getRollOptions(prefix=this.type){const{origin}=this,originRollOptions=!!origin?.flags?.pf2e?.rollOptions?origin.getSelfRollOptions("origin").map(o=>`${prefix}:${o}`)??[]:[],{badge}=this,itemOrigin=this.grantedBy?.getRollOptions(`${prefix}:granter`)??[];return[...super.getRollOptions(prefix),...itemOrigin,...Object.entries({[`badge:type:${badge?.type}`]:!!badge,[`badge:value:${badge?.value}`]:!!badge,"from-spell":this.fromSpell}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`),...originRollOptions]}prepareBaseData(){super.prepareBaseData();const slug=this.slug??sluggify(this.name);this.rollOptionSlug=slug.replace(/^(?:[a-z]+-)?(?:effect|stance)-/,""),this.system.fromSpell??=!1}prepareActorData(){const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}`]=!0;const badge=this.badge;if(typeof badge?.value=="number"){const values=actor.items.filter(i=>i instanceof AbstractEffectPF2e&&i.rollOptionSlug===this.rollOptionSlug).map(effect=>effect.badge?.value).filter(value=>typeof value=="number");badge.value>=Math.max(...values)&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:${badge.value}`]=!0)}}_preCreate(data,options,user){return data.system.fromSpell??=(()=>{if((this.slug??sluggify(this.name)).startsWith("spell-effect-"))return!0;const originItem=fromUuidSync(this.system.context?.origin.item??"");return originItem instanceof ItemPF2e&&(originItem.isOfType("spell")||originItem.isOfType("affliction","condition","effect")&&originItem.fromSpell)})(),super._preCreate(data,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.handleChange({create:this})}_onDelete(options,userId){super._onDelete(options,userId),this.handleChange({delete:{name:this._source.name}})}handleChange(change){const skipFloatyText=this.isOfType("condition")&&!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"),auraNotInCombat=this.flags.pf2e.aura&&!game.combat?.started,identified=game.user.isGM||this.isIdentified;if(!(skipFloatyText||!identified||auraNotInCombat)){if(this.isLocked||this.actor?.getActiveTokens().shift()?.showFloatyText(change),this.isOfType("condition"))for(const token of this.actor?.getActiveTokens()??[])token._onApplyStatusEffect(this.rollOptionSlug,!1);game.pf2e.StatusEffects.refresh()}}}var define_CONDITION_SOURCES_default=[{_id:"1wQY3JYyhMYeeV2G",img:"systems/pf2e/icons/conditions/observed.webp",name:"Observed",system:{description:{value:"<p>Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}, it can become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} or @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} instead of observed. If you have another precise sense besides sight, you might be able to observe a creature or object using that sense instead. You can observe a creature with only your precise senses. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than observed.</p>"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"observed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G"}},effects:[]},{_id:"3uh1r86TzbQvosxv",img:"systems/pf2e/icons/conditions/doomed.webp",name:"Doomed",system:{description:{value:`<p>Your soul has been gripped by a powerful force that calls you closer to death. Doomed always includes a value. The @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} value at which you die is reduced by your doomed value. If your maximum dying value is reduced to 0, you instantly die. When you die, you're no longer doomed.</p>
|
|
<p>Your doomed value decreases by 1 each time you get a full night's rest.</p>`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"doomed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.3uh1r86TzbQvosxv"}},effects:[]},{_id:"4D2KBtexWXa6oUMR",img:"systems/pf2e/icons/conditions/drained.webp",name:"Drained",system:{description:{value:`<p>Your health and vitality have been depleted as you've lost blood, life force, or some other essence. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you become drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.</p>
|
|
<p>Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.</p>`},duration:{value:0},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"con-based",slug:"drained",type:"status",value:"-1 * @item.badge.value"},{key:"FlatModifier",selector:"hp",slug:"drained",type:"status",value:"min(-1 * @actor.level,-1) * @item.badge.value"},{key:"LoseHitPoints",reevaluateOnUpdate:!0,value:"max(1,@actor.level) * @item.badge.value"}],value:{isValued:!0,value:1},slug:"drained",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR"}},effects:[]},{_id:"6dNUvdb1dhToNDj3",img:"systems/pf2e/icons/conditions/broken.webp",name:"Broken",system:{description:{value:`<p>Broken is a condition that affects only objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses\u2014with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: \u20131 for broken light armor, \u20132 for broken medium armor, or \u20133 for broken heavy armor.</p>
|
|
<p>A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth. If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.</p>`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"broken",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6dNUvdb1dhToNDj3"}},effects:[]},{_id:"6uEgoh53GbXuHpTF",img:"systems/pf2e/icons/conditions/paralyzed.webp",name:"Paralyzed",system:{description:{value:"<p>You're frozen in place. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition and can't act except to @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} and use actions that require only your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving, so you can't @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek}.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"paralyzed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6uEgoh53GbXuHpTF"}},effects:[]},{_id:"9evPzg9E6muFcoSk",img:"systems/pf2e/icons/conditions/unnoticed.webp",name:"Unnoticed",system:{description:{value:"<p>If you're unnoticed by a creature, that creature has no idea you're present. When you're unnoticed, you're also @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected}. This matters for abilities that can be used only against targets totally unaware of your presence.</p>"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unnoticed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9evPzg9E6muFcoSk"}},effects:[]},{_id:"9PR9y0bi4JPKnHPR",img:"systems/pf2e/icons/conditions/deafened.webp",name:"Deafened",system:{description:{value:"<p>You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a \u20132 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action that has the auditory trait, you must succeed at a @Check[type:flat|showDC:all|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects while deafened.</p>"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception-initiative",slug:"deafened",type:"status",value:-2},{key:"Immunity",type:"auditory"}],value:{isValued:!1,value:null},slug:"deafened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR"}},effects:[]},{_id:"9qGBRpbX9NEwtAAr",img:"systems/pf2e/icons/conditions/controlled.webp",name:"Controlled",system:{description:{value:"<p>You have been commanded, magically dominated, or otherwise had your will subverted. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay}. The controller usually doesn't have to spend their own actions when controlling you.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"controlled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9qGBRpbX9NEwtAAr"}},effects:[]},{_id:"AdPVz7rbaVSRxHFg",img:"systems/pf2e/icons/conditions/fascinated.webp",name:"Fascinated",system:{description:{value:"<p>You're compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a \u20132 status penalty to Perception and skill checks, and you can't use concentrate actions unless they (or their intended consequences) are related to the subject of your fascination, as determined by the GM. For instance, you might be able to @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} and @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["perception","skill-check"],slug:"fascinated",type:"status",value:-2}],value:{isValued:!1,value:null},slug:"fascinated",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AdPVz7rbaVSRxHFg"}},effects:[]},{_id:"AJh5ex99aV6VTggg",img:"systems/pf2e/icons/conditions/off-guard.webp",name:"Off-Guard",system:{active:!1,description:{value:`<p>You're distracted or otherwise unable to focus your full attention on defense. You take a \u20132 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them, such as "The target is off-guard."</p>`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"ac",slug:"off-guard",type:"circumstance",value:-2}],traits:{},value:{isValued:!1,value:null},slug:"off-guard",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}},effects:[]},{_id:"D5mg6Tc7Jzrj6ro7",img:"systems/pf2e/icons/conditions/encumbered.webp",name:"Encumbered",system:{description:{value:"<p>You are carrying more weight than you can manage. While you're encumbered, you're @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"speed",slug:"encumbered",value:-10},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}],value:{isValued:!1,value:null},slug:"encumbered",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.D5mg6Tc7Jzrj6ro7"}},effects:[]},{_id:"dfCMdR4wnpbYNTix",img:"systems/pf2e/icons/conditions/stunned.webp",name:"Stunned",system:{description:{value:`<p>You've become senseless. You can't act. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions, reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead, such as "stunned for 1 minute," causing you to lose all your actions for the duration.</p>
|
|
<p>Stunned overrides @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed}. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.</p>`},duration:{value:0},group:null,overrides:["slowed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"stunned",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix"}},effects:[]},{_id:"DmAIPqOBomZ7H95W",img:"systems/pf2e/icons/conditions/concealed.webp",name:"Concealed",system:{description:{value:"<p>You are difficult for one or more creatures to see due to thick fog or some other obscuring feature. You can be concealed to some creatures but not others. While concealed, you can still be @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|showDC:all|dc:5] when targeting you with an attack, spell, or other effect. If the check fails, you aren't affected. Area effects aren't subject to this flat check.</p>"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"concealed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W"}},effects:[]},{_id:"dTwPJuKgBQCMxixg",img:"systems/pf2e/icons/conditions/petrified.webp",name:"Petrified",system:{description:{value:"<p>You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When the petrified condition ends, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"petrified",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dTwPJuKgBQCMxixg"}},effects:[]},{_id:"e1XGnhKNSQIm5IXg",img:"systems/pf2e/icons/conditions/stupefied.webp",name:"Stupefied",system:{active:!1,description:{value:"<p>Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack modifiers, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to @UUID[Compendium.pf2e.actionspf2e.Item.aBQ8ajvEBByv45yz]{Cast a Spell} while stupefied, the spell is disrupted unless you succeed at a @Check[type:flat|showDC:all|dc:resolve(5+@item.badge.value)] with a DC equal to 5 + your stupefied value.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["cha-based","int-based","wis-based"],slug:"stupefied",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"stupefied",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg"}},effects:[]},{_id:"eIcWbB5o3pP6OIMe",img:"systems/pf2e/icons/conditions/immobilized.webp",name:"Immobilized",system:{description:{value:"<p>You are incapable of movement. You can't use any actions that have the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"immobilized",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}},effects:[]},{_id:"fBnFDH2MTzgFijKf",img:"systems/pf2e/icons/conditions/unconscious.webp",name:"Unconscious",system:{description:{value:`<p>You're sleeping or have been knocked out. You can't act. You take a \u20134 status penalty to AC, Perception, and Reflex saves, and you have the @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} and @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} conditions. When you gain this condition, you fall @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} and drop items you're holding unless the effect states otherwise or the GM determines you're positioned so you wouldn't.</p>
|
|
<p>If you're unconscious because you're @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying}, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more, you lose the dying and unconscious conditions and can act normally on your next turn.</p>
|
|
<p>If you are unconscious and at 0 Hit Points, but not dying, you return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you are healed, you lose the unconscious condition and can act normally on your next turn.</p>
|
|
<p>If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways.</p>
|
|
<ul>
|
|
<li>You take damage, though if the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.</li>
|
|
<li>You receive healing, other than the natural healing you get from resting.</li>
|
|
<li>Someone shakes you awake with an @UUID[Compendium.pf2e.actionspf2e.Item.pvQ5rY2zrtPI614F]{Interact} action.</li>
|
|
<li>Loud noise around you might wake you. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some effects make you sleep so deeply that they don't allow you this Perception check.</li>
|
|
<li>If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.</li>
|
|
</ul>`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","perception","reflex"],slug:"unconscious",type:"status",value:-4},{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{allowDuplicate:!1,key:"GrantItem",onDeleteActions:{grantee:"restrict",granter:"detach"},uuid:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}],value:{isValued:!1,value:null},slug:"unconscious",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}},effects:[]},{_id:"fesd1n5eVhpCSS18",img:"systems/pf2e/icons/conditions/sickened.webp",name:"Sickened",system:{description:{value:`<p>You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything\u2014including elixirs and potions\u2014while sickened.</p>
|
|
<p>You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).</p>`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"all",slug:"sickened",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"sickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fesd1n5eVhpCSS18"}},effects:[]},{_id:"fuG8dgthlDWfWjIA",img:"systems/pf2e/icons/conditions/indifferent.webp",name:"Indifferent",system:{description:{value:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.</p>"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"indifferent",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fuG8dgthlDWfWjIA"}},effects:[]},{_id:"HL2l2VRSaQHu9lUw",img:"systems/pf2e/icons/conditions/fatigued.webp",name:"Fatigued",system:{description:{value:`<p>You're tired and can't summon much energy. You take a \u20131 status penalty to AC and saving throws. You can't use exploration activities performed while traveling.</p>
|
|
<p>You recover from fatigue after a full night's rest.</p>`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","saving-throw"],slug:"fatigued",type:"status",value:-1}],value:{isValued:!1,value:null},slug:"fatigued",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.HL2l2VRSaQHu9lUw"}},effects:[]},{_id:"I1ffBVISxLr2gC4u",img:"systems/pf2e/icons/conditions/unfriendly.webp",name:"Unfriendly",system:{description:{value:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is unfriendly to a character dislikes and distrusts that character. The unfriendly creature won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.</p>"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unfriendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.I1ffBVISxLr2gC4u"}},effects:[]},{_id:"i3OJZU2nk64Df3xm",img:"systems/pf2e/icons/conditions/clumsy.webp",name:"Clumsy",system:{description:{value:"<p>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.</p>"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"dex-based",slug:"clumsy",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"clumsy",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}},effects:[]},{_id:"iU0fEDdBp3rXpTMC",img:"systems/pf2e/icons/conditions/hidden.webp",name:"Hidden",system:{description:{value:`<p>While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}. A creature you're hidden from is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you, and it must succeed at a @Check[type:flat|showDC:all|dc:11] when targeting you with an attack, spell, or other effect or it fails to affect you. Area effects aren't subject to this flat check.</p>
|
|
<p>A creature might be able to use the seek action to try to observe you.</p>`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hidden",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC"}},effects:[]},{_id:"j91X7x0XSomq8d60",img:"systems/pf2e/icons/conditions/prone.webp",name:"Prone",system:{description:{value:`<p>You're lying on the ground. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and take a \u20132 circumstance penalty to attack rolls. The only move actions you can use while you're prone are @UUID[Compendium.pf2e.actionspf2e.Item.Tj055UcNm6UEgtCg]{Crawl} and @UUID[Compendium.pf2e.actionspf2e.Item.OdIUybJ3ddfL7wzj]{Stand}. Standing up ends the prone condition. You can @UUID[Compendium.pf2e.actionspf2e.Item.ust1jJSCZQUhBZIz]{Take Cover} while prone to hunker down and gain greater cover against ranged attacks, even if you don't have an object to get behind, which grants you a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).</p>
|
|
<p>If you would be knocked prone while you're @UUID[Compendium.pf2e.actionspf2e.Item.pprgrYQ1QnIDGZiy]{Climbing} or @UUID[Compendium.pf2e.actionspf2e.Item.cS9nfDRGD83bNU1p]{Flying}, you fall. You can't be knocked prone when @UUID[Compendium.pf2e.actionspf2e.Item.c8TGiZ48ygoSPofx]{Swimming}.</p>`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"attack-roll",slug:"prone",type:"circumstance",value:-2},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"prone",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}},effects:[]},{_id:"kWc1fhmv9LBiTuei",img:"systems/pf2e/icons/conditions/grabbed.webp",name:"Grabbed",system:{description:{value:"<p>You're held in place by another creature, giving you the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|showDC:all|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"grabbed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei"}},effects:[]},{_id:"lDVqvLKA6eF3Df60",img:"systems/pf2e/icons/conditions/persistent-damage.webp",name:"Persistent Damage",system:{description:{value:'<p>You are taking damage from an ongoing effect, such as from being lit on fire. This appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Like normal damage, it can be doubled or halved based on the results of an attack roll or saving throw. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|showDC:all|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.</p>'},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"persistent-damage",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60"}},effects:[]},{_id:"MIRkyAjyBeXivMa7",img:"systems/pf2e/icons/conditions/enfeebled.webp",name:"Enfeebled",system:{active:!1,description:{value:"<p>You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["str-based","str-damage"],slug:"enfeebled",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"enfeebled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7"}},effects:[]},{_id:"nlCjDvLMf2EkV2dl",img:"systems/pf2e/icons/conditions/quickened.webp",name:"Quickened",system:{description:{value:"<p>You're able to act more quickly. You gain 1 additional action at the start of your turn each round. Many effects that make you quickened require you use this extra action only in certain ways. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"quickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.nlCjDvLMf2EkV2dl"}},effects:[]},{_id:"sDPxOjQ9kx2RZE8D",img:"systems/pf2e/icons/conditions/fleeing.webp",name:"Fleeing",system:{active:!1,description:{value:"<p>You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or creature that gave you the condition, though some effects might define something else as the source. You can't @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay} or @UUID[Compendium.pf2e.actionspf2e.Item.dLgAMt3TbkmLkUqE]{Ready} while fleeing.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"fleeing",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.sDPxOjQ9kx2RZE8D"}},effects:[]},{_id:"TBSHQspnbcqxsmjL",img:"systems/pf2e/icons/conditions/frightened.webp",name:"Frightened",system:{active:!1,description:{value:"<p>You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"all",slug:"frightened",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"frightened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL"}},effects:[]},{_id:"TkIyaNPgTZFBCCuh",img:"systems/pf2e/icons/conditions/dazzled.webp",name:"Dazzled",system:{active:!1,description:{value:"<p>Your eyes are overstimulated or your vision is swimming. If vision is your only precise sense, all creatures and objects are @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} from you.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"dazzled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh"}},effects:[]},{_id:"ud7gTLwPeklzYSXG",img:"systems/pf2e/icons/conditions/hostile.webp",name:"Hostile",system:{description:{value:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose on a PC. A creature hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.</p>"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","unfriendly"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hostile",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.ud7gTLwPeklzYSXG"}},effects:[]},{_id:"v44P3WUcU1j0115l",img:"systems/pf2e/icons/conditions/helpful.webp",name:"Helpful",system:{description:{value:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character (or one of their allies) uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.</p>"},duration:{value:0},group:"attitudes",overrides:["friendly","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"helpful",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v44P3WUcU1j0115l"}},effects:[]},{_id:"v66R7FdOf11l94im",img:"systems/pf2e/icons/conditions/friendly.webp",name:"Friendly",system:{description:{value:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is friendly to a character likes that character. It is likely to agree to @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character as long as they are simple, safe, and don't cost too much to fulfill. If the character (or one of their allies) uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.</p>"},duration:{value:0},group:"attitudes",overrides:["helpful","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"friendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v66R7FdOf11l94im"}},effects:[]},{_id:"VcDeM8A5oI6VqhbM",img:"systems/pf2e/icons/conditions/restrained.webp",name:"Restrained",system:{description:{value:"<p>You're tied up and can barely move, or a creature has you pinned. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions, and you can't use any attack or manipulate actions except to attempt to @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escape} or @UUID[Compendium.pf2e.actionspf2e.Item.SjmKHgI7a5Z9JzBx]{Force Open} your bonds. Restrained overrides @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.</p>"},duration:{value:0},group:null,overrides:["grabbed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"restrained",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM"}},effects:[]},{_id:"VRSef5y1LmL2Hkjf",img:"systems/pf2e/icons/conditions/undetected.webp",name:"Undetected",system:{description:{value:`<p>When you are undetected by a creature, that creature can't see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you.</p>
|
|
<p>A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} creature (requiring a @Check[type:flat|showDC:all|dc:11|traits:secret]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square. They can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to try to find you.</p>`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"undetected",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf"}},effects:[]},{_id:"XgEqL1kFApUbl5Z2",img:"systems/pf2e/icons/conditions/blinded.webp",name:"Blinded",system:{description:{value:"<p>You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a \u20134 status penalty to Perception checks. You are immune to visual effects. Blinded overrides @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.</p>"},duration:{value:0},group:"senses",overrides:["dazzled"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception",slug:"blinded",type:"status",value:-4},{key:"Immunity",type:"visual"}],value:{isValued:!1,value:null},slug:"blinded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"}},effects:[]},{_id:"xYTAsEpcJE1Ccni3",img:"systems/pf2e/icons/conditions/slowed.webp",name:"Slowed",system:{description:{value:"<p>You have fewer actions. Slowed always includes a value. When you regain your actions, reduce the number of actions regained by your slowed value. Because you regain actions at the start of your turn, you don't immediately lose actions if you become slowed during your turn.</p>"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"slowed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3"}},effects:[]},{_id:"yblD8fOR1J8rDwEQ",img:"systems/pf2e/icons/conditions/confused.webp",name:"Confused",system:{description:{value:`<p>You don't have your wits about you, and you attack wildly. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard}, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.</p>
|
|
<p>You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.</p>
|
|
<p>Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|showDC:all|dc:11] to recover from your confusion and end the condition.</p>`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"confused",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yblD8fOR1J8rDwEQ"}},effects:[]},{_id:"Yl48xTdMh3aeQYL2",img:"systems/pf2e/icons/conditions/wounded.webp",name:"Wounded",system:{active:!1,description:{value:`<p>You have been seriously injured. If you lose the @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.</p>
|
|
<p>The wounded condition ends if someone successfully restores Hit Points to you using @UUID[Compendium.pf2e.actionspf2e.Item.1kGNdIIhuglAjIp9]{Treat Wounds}, or if you are restored to full Hit Points by any means and rest for 10 minutes.</p>`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"wounded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2"}},effects:[]},{_id:"yZRUzMqrMmfLu0V1",img:"systems/pf2e/icons/conditions/dying.webp",name:"Dying",system:{description:{value:`<p>You are bleeding out or otherwise at death's door. While you have this condition, you are @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}. Dying always includes a value, and if it ever reaches dying 4, you die. When you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.</p>
|
|
<p>If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded 1} condition, or increase your wounded condition value by 1 if you already have that condition.</p>`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}],value:{isValued:!0,value:1},slug:"dying",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1"}},effects:[]},{_id:"zJxUflt9np0q4yML",img:"systems/pf2e/icons/conditions/invisible.webp",name:"Invisible",system:{active:!1,description:{value:"<p>You can't be seen. You're @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} to everyone. Creatures can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} to that creature until you @UUID[Compendium.pf2e.actionspf2e.Item.VMozDqMMuK5kpoX4]{Sneak} to become undetected again. If you become invisible while someone can already see you, you start out hidden to them (instead of undetected) until you successfully Sneak. You can't become @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed} while invisible except via special abilities or magic.</p>"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"invisible",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.zJxUflt9np0q4yML"}},effects:[]},{_id:"axtAzam8kiKbTD2c",img:"systems/pf2e/icons/conditions/malevolence.webp",name:"Malevolence",system:{active:!1,description:{value:`<p>As the malevolence begins to take its hold on creatures, their body, minds, and souls become increasingly haunted by the supernatural force infesting Xarwin Manor. Malevolence is a special condition that can affect PCs who play in this adventure. The malevolence condition always includes a value. You take a status penalty equal to this value to all saving throws against effects generated by haunts and against all curse and possession effects. The malevolence condition can be reduced by restoration.</p>
|
|
<p>The malevolence can never increase above a value of 4. If an effect would increase a creature's malevolence value higher than 4, the creature is instead @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} for 24 hours as the malevolence consumes a few of their random, short-term memories. A creature that has a malevolence 4 won't voluntarily leave the Xarwin Manor grounds.</p>
|
|
<p>Each time you get a full night's rest in a region not influenced by the malevolence condition, the value of your malevolence decreases by 1.</p>`},duration:{perpetual:!1,text:"",value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Adventure: Malevolence"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",predicate:[{or:["origin:trait:haunt","curse","possession"]}],selector:"saving-throw",slug:"malevolence",type:"status",value:"-@item.badge.value"}],value:{immutable:!1,isValued:!0,value:1},slug:"malevolence",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.campaign-effects.Item.axtAzam8kiKbTD2c"}},effects:[]}];class ConditionManager{static{__name(this,"ConditionManager")}static{__name2(this,"ConditionManager")}static#initialized=!1;static conditions=new Map;static CONDITION_SOURCES=define_CONDITION_SOURCES_default;static get conditionsSlugs(){return[...this.conditions.keys()].filter(k=>!k.startsWith("Compendium."))}static async initialize(force=!1){if(this.#initialized||(this.conditions=new Map(this.CONDITION_SOURCES?.flatMap(source=>{const condition=new ConditionPF2e(source,{pack:"pf2e.conditionitems"});return[[condition.slug,condition],[condition.uuid,condition]]})??[]),delete this.CONDITION_SOURCES),(!this.#initialized||force)&&game.i18n.lang!=="en"&&game.modules.get("babele")?.active){const localize=localizer("PF2E.condition");for(const condition of this.conditions.values())condition.name=condition._source.name=localize(`${condition.slug}.name`),condition.system.description.value=condition._source.system.description.value=localize(`${condition.slug}.rules`)}this.#initialized=!0}static getCondition(slug,modifications={}){if(slug=sluggify(slug),!setHasElement(CONDITION_SLUGS,slug))return null;const condition=ConditionManager.conditions.get(slug)?.clone(modifications);if(!condition)throw ErrorPF2e("Unexpected failure looking up condition");return condition}static async updateConditionValue(itemId,actorOrToken,value){const actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken.actor,condition=actor?.items.get(itemId);condition?.isOfType("condition")&&(value===0?await condition.delete():actor?.isOfType("creature")&&(tupleHasValue(["dying","wounded","doomed"],condition.slug)&&(value=Math.min(value,actor.attributes[condition.slug].max)),await condition.update({"system.value.value":value})))}}const EXPIRING_CONDITIONS=new Set(["frightened","sickened","drained","doomed","stunned","unconscious"]);class AfflictionPF2e extends AbstractEffectPF2e{static{__name(this,"AfflictionPF2e")}static{__name2(this,"AfflictionPF2e")}constructor(source,context){throw super(source,context),ErrorPF2e("Affliction items are not available in production builds")}get badge(){return{type:"counter",value:this.stage,min:1,max:this.maxStage,label:this.onset?game.i18n.localize("PF2E.Item.Affliction.OnsetLabel"):game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage})}}get stage(){return this.system.stage}get stageData(){return Object.values(this.system.stages).at(this.stage-1)??null}get maxStage(){return Object.keys(this.system.stages).length||1}async increase(){if(this.onset)await this.update({system:{"-=onset":null}});else if(this.stage!==this.maxStage){const stage=Math.min(this.maxStage,this.system.stage+1);await this.update({system:{stage}})}}async decrease(){const stage=this.system.stage-1;if(stage===0){await this.delete();return}await this.update({system:{stage}})}get onset(){return!!this.system.onset?.active}get onsetDuration(){return this.system.onset?this.system.onset.value*(DURATION_UNITS[this.system.onset.unit]??0):0}get remainingStageDuration(){const stageDuration=this.stageData?.duration??{unit:"unlimited"};return calculateRemainingDuration(this,{...stageDuration,expiry:"turn-end"})}prepareBaseData(){super.prepareBaseData(),this.system.stage=Math.clamped(this.system.stage,this.badge.min,this.maxStage);for(const stage of Object.values(this.system.stages))for(const condition of Object.values(stage.conditions))condition.linked??=!0}getStageDamage(stage){const stageData=Object.values(this.system.stages).at(stage-1),base=[];for(const data of Object.values(stageData?.damage??{})){const{formula,type:damageType,category}=data,terms=parseTermsFromSimpleFormula(formula);base.push({terms,damageType,category:category??null})}if(!base.length)return null;try{const{formula,breakdown}=createDamageFormula({base,modifiers:[],dice:[],ignoredResistances:[]}),roll=new DamageRoll(formula),stageLabel=game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage}),template={name:`${this.name} - ${stageLabel}`,damage:{roll,breakdown},materials:[],modifiers:[]},context={type:"damage-roll",sourceType:"save",outcome:"failure",domains:[],options:new Set,self:null,traits:this.system.traits.value};return{template,context}}catch(err){console.error(err)}return null}async handleStageChange(){const actor=this.actor;if(!actor)return;const itemsToDelete=this.getLinkedItems().map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",itemsToDelete);const currentStage=this.stageData;if(!currentStage)return;const conditionsToAdd=[],conditionsToUpdate={};for(const data of Object.values(currentStage.conditions??{})){const value=data.value??1,existing=(()=>{const allExisting=actor.conditions.bySlug(data.slug,{temporary:!1}),byAffliction=allExisting.find(i=>i.appliedBy===this);return byAffliction||(data.linked?null:maxBy(allExisting.filter(i=>!i.appliedBy&&!i.isLocked),c=>c.active?1/0:c.value??0))})();if(existing){existing.system.value.isValued&&(conditionsToUpdate[existing.id]={value,linked:!!data.linked});continue}const condition=ConditionManager.getCondition(data.slug);condition.updateSource({"flags.pf2e.grantedBy.id":this.id}),data.linked&&condition.updateSource({"system.references.parent.id":this.id}),condition.system.value.isValued&&value>1&&condition.updateSource({"system.value.value":data.value}),conditionsToAdd.push(condition)}const additions=conditionsToAdd.map(c=>c.toObject());await actor.createEmbeddedDocuments("Item",additions),await actor.updateEmbeddedDocuments("Item",Object.entries(conditionsToUpdate).map(([_id,data])=>({_id,"system.value.value":data.value,"flags.pf2e.grantedBy.id":this.id,...data.linked?{"system.references.parent.id":this.id}:{}}))),this.system.onset||await this.createStageMessage()}getLinkedItems(){return this.actor?this.actor.items.filter(i=>i.isOfType("condition")&&!EXPIRING_CONDITIONS.has(i.slug)&&i.flags.pf2e.grantedBy?.id===this.id&&i.system.references.parent?.id===this.id):[]}async createStageMessage(){if(!this.actor)return;const damage=this.getStageDamage(this.stage);if(damage){const{template,context}=damage;await DamagePF2e.roll(template,context)}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime+this.onsetDuration,initiative}}else data.system.stage=1,data.system.onset&&(data.system.onset.active=!0);return super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;return typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&duration.value===-1&&(duration.value=1),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user===this.actor?.primaryUpdater&&this.handleStageChange()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.stage&&game.user===this.actor?.primaryUpdater&&this.handleStageChange()}async rollRecovery(){if(!this.actor)return;const save=this.actor.saves?.[this.system.save.type];save&&(((await save.roll({dc:{value:this.system.save.value},extraRollOptions:this.getRollOptions("item")}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS?this.decrease():this.increase())}prepareActorData(){super.prepareActorData();const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");this.onset&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:onset`]=!0)}}class ConditionPF2e extends AbstractEffectPF2e{static{__name(this,"ConditionPF2e")}static{__name2(this,"ConditionPF2e")}get badge(){return this.system.persistent?{type:"formula",value:this.system.persistent.formula,label:null}:typeof this.system.value.value=="number"?{type:"counter",min:0,max:1/0,label:null,value:this.system.value.value}:null}get origin(){const grantingItem=this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"");return grantingItem?.isOfType("affliction","effect")?grantingItem.origin:null}get key(){return this.system.persistent?`persistent-damage-${this.system.persistent.damageType}`:this.slug}get appliedBy(){const appliedById=this.system.references.parent?.id??this.flags.pf2e.grantedBy?.id??"";return this.actor?.items.get(appliedById)??this.actor?.conditions.get(appliedById)??null}get value(){return this.system.value.value}get isLocked(){const parentId=this.system.references.parent?.id??"";if(this.actor?.items.has(parentId)||this.actor?.conditions.has(parentId)||super.isLocked)return!0;const granterId=this.flags.pf2e.grantedBy?.id??"",granter=this.actor?.items.get(granterId)??this.actor?.conditions.get(granterId);return Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===this.id)?.onDelete==="restrict"}get isInHUD(){return this.slug in CONFIG.PF2E.statusEffects.conditions}get breakdown(){if(!this.active)return null;const list=uniq(compact(this.actor?.conditions.bySlug(this.slug).map(condition=>{const{appliedBy}=condition;return!appliedBy?.isOfType("condition")||appliedBy?.active?appliedBy:null})??[])).map(p=>reduceItemName(p.name)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", ");return list?game.i18n.format("PF2E.EffectPanel.AppliedBy",{"condition-list":list}):null}get readonly(){return this.actor&&this.id?!this.actor.items.has(this.id):!1}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);if(this.system.persistent){const{damageType}=this.system.persistent;options.push(`damage:type:${damageType}`,`${prefix}:damage:type:${damageType}`);const category=DamageCategorization.fromDamageType(damageType);category&&options.push(`damage:category:${category}`,`${prefix}:damage:category:${category}`)}return options}async increase(){await this.actor?.increaseCondition(this)}async decrease(){await this.actor?.decreaseCondition(this)}async onEndTurn(options={}){const{actor}=this,token=options?.token??actor?.token;!this.active||!actor||this.system.persistent&&await this.system.persistent.damage.clone().toMessage({speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor:`<strong>${this.name}</strong>`},{rollMode:"roll"})}async rollRecovery(){if(this.actor&&this.system.persistent){const{dc,damageType}=this.system.persistent;((await new Statistic(this.actor,{slug:"pd-recovery",label:game.i18n.format("PF2E.Item.Condition.PersistentDamage.Chat.RecoverLabel",{name:this.name}),check:{type:"flat-check"},domains:[]}).roll({dc:{value:dc},extraRollOptions:this.getRollOptions("item"),skipDialog:!0}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS&&this.actor.decreaseCondition(`persistent-damage-${damageType}`)}}prepareBaseData(){super.prepareBaseData(),this.active=!0;const systemData=this.system;systemData.value.value=systemData.value.isValued?Number(systemData.value.value)||1:null,systemData.duration=foundry.utils.mergeObject(systemData.duration,{value:-1,unit:"unlimited",expiry:null}),typeof this.badge?.value=="number"&&(this.name=`${this.name} ${this.badge.value}`);const folder=CONFIG.PF2E.statusEffects.iconDir;if(this.img=`${folder}${this.slug}.webp`,systemData.persistent){const{formula,damageType}=systemData.persistent,fullFormula=`(${formula})[persistent,${damageType}]`,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",roll=new DamageRoll(fullFormula,{},{evaluatePersistent:!0,critRule}),dc=game.user.isGM&&systemData.persistent.dc!==15?systemData.persistent.dc:null,localizationKey=`PF2E.Item.Condition.PersistentDamage.${dc!==null?"NameWithDC":"Name"}`;this.name=game.i18n.format(localizationKey,{formula,damageType:game.i18n.localize(CONFIG.PF2E.damageRollFlavors[damageType]??damageType),dc}),systemData.persistent.damage=roll,systemData.persistent.expectedValue=roll.expectedValue,this.img=PERSISTENT_DAMAGE_IMAGES[damageType]??this.img}}prepareSiblingData(){if(!this.actor)throw ErrorPF2e("prepareSiblingData may only be called from an embedded item");if(!this.active)return;const deactivate=__name2(condition=>{condition.active=!1,condition.system.references.overriddenBy.push({id:this.id,type:"condition"})},"deactivate"),conditions=this.actor.conditions.active;if(this.system.overrides.length>0){const overridden=conditions.filter(c=>this.system.overrides.includes(c.key));for(const condition of overridden)deactivate(condition)}const ofSameType=conditions.filter(c=>c!==this&&c.key===this.key);for(const condition of ofSameType)if(condition.slug==="persistent-damage"){const thisValue=this.system.persistent?.expectedValue??0,otherValue=condition.system.persistent?.expectedValue??0;thisValue>=otherValue&&deactivate(condition)}else(this.value===condition.value&&(!this.isLocked||condition.isLocked)||this.value&&condition.value&&this.value>condition.value)&&deactivate(condition)}prepareActorData(){if(super.prepareActorData(),this.active&&this.system.persistent){const{damageType}=this.system.persistent;this.actor.rollOptions.all[`self:condition:persistent-damage:${damageType}`]=!0}}prepareRuleElements(options){return this.active?super.prepareRuleElements(options):[]}async _preUpdate(changed,options,user){return options.conditionValue=this.value,super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"))return;const[priorValue,newValue]=[options.conditionValue,this.value];if(!!priorValue&&!!newValue&&priorValue!==newValue&&!this.system.references.parent?.id){const change=newValue>priorValue?{create:this}:{delete:this};this.actor?.getActiveTokens().shift()?.showFloatyText(change)}game.pf2e.StatusEffects.refresh()}}class EffectPF2e extends AbstractEffectPF2e{static{__name(this,"EffectPF2e")}static{__name2(this,"EffectPF2e")}get badge(){return this.system.badge}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get isExpired(){return this.system.expired}get isAura(){return this.rules.some(r=>r.key==="Aura"&&!r.ignored)}get isIdentified(){return!this.system.unidentified}get fromAura(){return!!this.flags.pf2e.aura}prepareBaseData(){super.prepareBaseData();const{system}=this;["unlimited","encounter"].includes(system.duration.unit)?system.duration.expiry=null:system.duration.expiry||="turn-start",system.expired=this.remainingDuration.expired;const{badge}=this.system;badge&&(badge.type==="formula"?badge.label=null:(badge.min=badge.labels?1:badge.min??1,badge.max=badge.labels?.length??badge.max??1/0,badge.value=Math.clamped(badge.value,badge.min,badge.max),badge.label=badge.labels?.at(badge.value-1)?.trim()||null))}prepareRuleElements(options){if(game.settings.get("pf2e","automation.effectExpiration")&&this.isExpired&&this.actor?.items.has(this.id))for(const rule of this.system.rules)rule.ignored=!0;return super.prepareRuleElements(options)}async increase(){const badge=this.system.badge;if(badge?.type==="counter"&&!this.isExpired){const value=badge.value+1;await this.update({system:{badge:{value}}})}}async decrease(){if(this.system.badge?.type!=="counter"||this.isExpired){await this.delete();return}const value=this.system.badge.value-1;await this.update({system:{badge:{value}}})}getRollOptions(prefix=this.type){const slug=this.slug??sluggify(this.name),trimmedSlug=slug.replace(/^(?:spell-)?(?:effect|stance)-/,""),options=super.getRollOptions(prefix);return options.findSplice(o=>o===`${prefix}:${slug}`,`${prefix}:${trimmedSlug}`),options}async evaluateFormulaBadge(badge){const{actor}=this;if(!actor)throw ErrorPF2e("A formula badge can only be evaluated if part of an embedded effect");const roll=await new Roll(badge.value,this.getRollData()).evaluate({async:!0}),reevaluate=badge.reevaluate?{formula:badge.value,event:badge.reevaluate}:null,token=actor.getActiveTokens(!1,!0).shift(),speaker=ChatMessagePF2e.getSpeaker({actor,token});return roll.toMessage({flavor:reduceItemName(this.name),speaker}),{type:"value",value:roll.total,labels:badge.labels,reevaluate}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime,initiative}}const badge=data.system.badge;return this.actor&&badge?.type==="formula"&&badge.evaluate&&(this._source.system.badge=await this.evaluateFormulaBadge(badge)),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;duration?.unit==="unlimited"?duration.expiry=null:typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&(duration.expiry||="turn-start",duration.value===-1&&(duration.value=1));const currentBadge=this.system.badge,badgeChange=changed.system?.badge??null;if(badgeChange){const badgeTypeChanged=badgeChange?.type&&badgeChange.type!==currentBadge?.type,labels="labels"in badgeChange&&Array.isArray(badgeChange.labels)?badgeChange.labels:currentBadge?.labels;if(badgeTypeChanged)badgeChange.value=1;else if(currentBadge?.type==="counter"){const[minValue,maxValue]=(()=>{const configuredMin=Number(badgeChange.min??currentBadge.min),configuredMax=Number(badgeChange.max??currentBadge.max);return labels?[1,Math.min(labels.length,configuredMax)]:[configuredMin,configuredMax]})();if(typeof badgeChange.value=="number"&&badgeChange.value<minValue&&this.actor)return await this.actor.deleteEmbeddedDocuments("Item",[this.id]),!1;const currentValue=Number(badgeChange.value??currentBadge.value??1);badgeChange.value=Math.clamped(currentValue,minValue,maxValue)}(badgeTypeChanged||labels||badgeChange.min===null)&&(delete badgeChange.min,"min"in(this._source.system.badge??{})&&(badgeChange["-=min"]=null)),(badgeTypeChanged||labels||badgeChange.max===null)&&(delete badgeChange.max,"max"in(this._source.system.badge??{})&&(badgeChange["-=max"]=null))}return super._preUpdate(changed,options,user)}_onDelete(options,userId){this.actor&&game.pf2e.effectTracker.unregister(this),super._onDelete(options,userId)}async onTurnStartEnd(event2){const{badge}=this;if(badge?.type==="value"&&badge.reevaluate?.event===`turn-${event2}`){const newBadge=await this.evaluateFormulaBadge({type:"formula",value:badge.reevaluate.formula,reevaluate:badge.reevaluate.event,labels:badge.labels});await this.update({"system.badge":newBadge})}}}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");class PhysicalItemPF2e extends ItemPF2e{static{__name(this,"PhysicalItemPF2e")}static{__name2(this,"PhysicalItemPF2e")}get level(){return this.system.level.value}get rarity(){return this.system.traits.rarity}get traits(){return new Set(this.system.traits.value)}get quantity(){return Number(this.system.quantity??1)}get size(){return this.system.size}get hitPoints(){return foundry.utils.deepClone(this.system.hp)}get hardness(){return this.system.hardness}get isEquipped(){return isEquipped(this.system.usage,this.system.equipped)}get carryType(){return this.system.equipped.carryType}get isHeld(){return this.handsHeld>0}get handsHeld(){return this.system.equipped.carryType==="held"?this.system.equipped.handsHeld??1:0}get isWorn(){return this.system.equipped.carryType==="worn"}get price(){return this.system.price}get assetValue(){return CoinsPF2e.fromPrice(this.price,this.quantity)}get identificationStatus(){return this.system.identification.status}get isIdentified(){return this.system.identification.status==="identified"}get isAlchemical(){return this.traits.has("alchemical")}get isMagical(){const traits=this.traits;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get isInvested(){return this.traits.has("invested")?this.isEquipped&&this.isIdentified&&this.system.equipped.invested===!0:null}get isCursed(){return this.traits.has("cursed")}get isTemporary(){return this.system.temporary}get isShoddy(){return this.system.traits.otherTags.includes("shoddy")}get isDamaged(){return this.system.hp.value>0&&this.system.hp.value<this.system.hp.max}get isBroken(){const{hitPoints}=this;return hitPoints.max>0&&!this.isDestroyed&&hitPoints.value<=hitPoints.brokenThreshold}get isDestroyed(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0}get material(){return foundry.utils.deepClone(this.system.material)}get isSpecific(){return!1}get isInContainer(){return!!this.container}get isStowed(){return!!this.container?.system.stowing}get container(){return this.system.containerId===null?this._container=null:this._container??=this.actor?.itemTypes.backpack.find(c=>c.id===this.system.containerId)??null}get bulk(){const{per}=this.system.bulk,bulkRelevantQuantity=Math.floor(this.quantity/per),actorSize=this.actor?.isOfType("creature")?this.actor.size:null;return new Bulk(this.system.bulk.value).convertToSize(this.size,actorSize??this.size).times(bulkRelevantQuantity)}get activations(){return Object.values(this.system.activations??{}).map(action2=>{const components=[];return action2.components.cast&&components.push(game.i18n.localize("PF2E.Item.Activation.Cast")),action2.components.command&&components.push(game.i18n.localize("PF2E.Item.Activation.Command")),action2.components.envision&&components.push(game.i18n.localize("PF2E.Item.Activation.Envision")),action2.components.interact&&components.push(game.i18n.localize("PF2E.Item.Activation.Interact")),{componentsLabel:components.join(", "),...action2}})}getRollOptions(prefix=this.type){const rollOptions=super.getRollOptions(prefix),{material}=this.system;return rollOptions.push(...Object.entries({equipped:this.isEquipped,[`hands-held:${this.handsHeld}`]:this.handsHeld>0,[`rarity:${this.rarity}`]:!0,uninvested:this.isInvested===!1,[`material:${material.type}`]:!!material.type}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}_initialize(options){this._container=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.containerId||=null,this.system.material.type||=null,this.system.material.grade||=null,this.system.material.effects??=[],this.system.stackGroup??=null,this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2),typeof this.system.price.value=="string"&&(this.system.price.value=CoinsPF2e.fromString(this.system.price.value)),this.system.traits.value.includes("infused")&&(this.system.temporary=!0),this.system.price.value=new CoinsPF2e(this.system.temporary?{}:this.system.price.value),this.system.price.per=Math.max(1,this.system.price.per??1),this.system.usage=getUsageDetails(this.system.usage?.value??"carried");const{equipped,usage}=this.system;equipped.handsHeld??=0,equipped.carryType??="worn",usage.type==="worn"&&usage.where&&(equipped.inSlot??=!1),this.actor?.isOfType("loot")&&(equipped.carryType="worn",equipped.inSlot=!1),this.system.bulk=prepareBulkData(this),this._container?.id!==this.system.containerId&&(this._container=null)}prepareDerivedData(){super.prepareDerivedData(),this.name=game.pf2e.system.generateItemName(this),this.system.identification.identified??={name:this.name,img:this.img,data:{description:{value:this.description}}};const{level,rarity,price}=computeLevelRarityPrice(this);this.system.level.value=level,this.system.traits.rarity=rarity,this.system.price.value=price;const mystifiedData=this.getMystifiedData(this.identificationStatus);this.name=mystifiedData.name,this.img=mystifiedData.img,this.system.description.value=mystifiedData.data.description.value,this.system.identification.unidentified=this.getMystifiedData("unidentified"),this.isEmbedded||(this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max))}prepareSiblingData(){this.actor&&(this.isStowed&&(this.system.equipped.carryType="stowed",delete this.system.equipped.inSlot),this._container&&!this.actor.items.has(this._container.id)&&(this._container=this.system.containerId=null))}onPrepareSynthetics(){this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max)}isStackableWith(item){if(!(this!==item&&this.type===item.type&&this.name===item.name&&this.isIdentified===item.isIdentified&&![this,item].some(i=>i.isHeld||i.isOfType("backpack"))))return!1;const thisData=this.toObject().system,otherData=item.toObject().system;return thisData.quantity=otherData.quantity,thisData.equipped=otherData.equipped,thisData.containerId=otherData.containerId,thisData._migration=otherData._migration,thisData.identification=otherData.identification,equals(thisData,otherData)}async stackWith(targetItem){if(this.isStackableWith(targetItem)){const stackQuantity=this.quantity+targetItem.quantity;await this.delete({render:!1})&&await targetItem.update({"system.quantity":stackQuantity})}}async move({relativeTo,sortBefore,toContainer,toStack,render=!0}){if(!this.actor)throw ErrorPF2e("Tried to move an unonwned item!");if(toStack)return this.stackWith(toStack);const containerResolved=toContainer??relativeTo?.container,mainContainerUpdate=(()=>{if(containerResolved&&!isCycle(this,containerResolved)){const equipped={carryType:containerResolved.stowsItems?"stowed":"worn",handsHeld:0,inSlot:!1};return{system:{containerId:containerResolved?.id,equipped}}}return!containerResolved&&this.isInContainer?{system:{containerId:null,equipped:{carryType:"worn",handsHeld:0,inSlot:!1}}}:null})(),inventory=this.actor.inventory,siblings=(containerResolved?.contents.contents??inventory.contents).sort((a,b)=>a.sort-b.sort);if(!sortBefore&&!siblings.length&&mainContainerUpdate){await this.update(mainContainerUpdate);return}const updates=SortingHelpers.performIntegerSort(this,{target:relativeTo,siblings,sortBefore}).map(s=>{const baseUpdate={_id:s.target.id,...s.update};return mainContainerUpdate&&s.target.id===this.id?foundry.utils.mergeObject(baseUpdate,mainContainerUpdate):baseUpdate}),stowedOrUnstowed=!this.container&&!!containerResolved||this.container&&!containerResolved;await this.actor.updateEmbeddedDocuments("Item",updates,{render:stowedOrUnstowed||render})}getMystifiedData(status,_options){const mystifiedData=this.system.identification[status],name2=mystifiedData.name||this.generateUnidentifiedName(),img=mystifiedData.img||getUnidentifiedPlaceholderImage(this),description=mystifiedData.data.description.value||(()=>{if(status==="identified")return this.description;const itemType=this.generateUnidentifiedName({typeOnly:!0}),caseCorrect=__name2(noun=>game.i18n.lang.toLowerCase()==="de"?noun:noun.toLowerCase(),"caseCorrect");return game.i18n.format("PF2E.identification.UnidentifiedDescription",{item:caseCorrect(itemType)})})();return{name:name2,img,data:{description:{value:description}}}}async getChatData(){const{type,grade}=this.system.material,material=type&&grade?game.i18n.format("PF2E.Item.Weapon.MaterialAndRunes.MaterialOption",{type:game.i18n.localize(CONFIG.PF2E.preciousMaterials[type]),grade:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}):null;return{rarity:{name:this.rarity,label:CONFIG.PF2E.rarityTraits[this.rarity],description:CONFIG.PF2E.traitsDescriptions[this.rarity]},description:{value:this.description},material}}async setIdentificationStatus(status){this.identificationStatus!==status&&await this.update({"system.identification.status":status,"system.identification.unidentified":this.getMystifiedData("unidentified")})}generateUnidentifiedName({typeOnly=!1}={}){const itemType=game.i18n.localize(`TYPES.Item.${this.type}`);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}traitChatData(dictionary){const traitData=super.traitChatData(dictionary);for(const trait of traitData)if(trait.mystified=!this.isIdentified&&MystifiedTraits.has(trait.value),trait.excluded=trait.mystified&&!game.user.isGM,trait.excluded)delete trait.description;else if(trait.mystified){const gmNote=game.i18n.localize("PF2E.identification.TraitGMNote");trait.description=trait.description?`${gmNote}
|
|
|
|
${game.i18n.localize(trait.description)}`:gmNote}return traitData}async _preCreate(data,options,user){return this._source.system.equipped={carryType:"worn"},this.system.usage.type==="worn"&&!!this.system.usage.where&&this.actor?.isOfType("character")&&(this._source.system.equipped.inSlot=!1),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);for(const property of["quantity","hardness"])if(changed.system[property]!==void 0){const max=property==="quantity"?999999:999;changed.system[property]=Math.clamped(Math.trunc(Number(changed.system[property])),0,max)||0}if(handleHPChange(this,changed),isObject(changed.system.price)){const price=changed.system.price;if(isObject(price.value)){const coins=price.value;for(const denomination of DENOMINATIONS)coins[denomination]===0&&(coins[`-=${denomination}`]=null)}"per"in price&&(!price.per||Number(price.per)<=1)&&(price["-=per"]=null)}const equipped=changed.system.equipped??{};equipped.carryType==="dropped"&&this.system.equipped.invested&&(equipped.invested=!1),String(equipped.carryType??this.system.equipped.carryType).startsWith("held")||(equipped.handsHeld=0);const newUsage=getUsageDetails(String(changed.system.usage?.value??this.system.usage.value)),hasSlot=newUsage.type==="worn"&&newUsage.where,isSlotted=!!(equipped.inSlot??this.system.equipped.inSlot);return hasSlot?equipped.inSlot=isSlotted:"inSlot"in this._source.system.equipped&&(equipped["-=inSlot"]=null),super._preUpdate(changed,options,user)}}class PhysicalItemSheetPF2e extends ItemSheetPF2e{static{__name(this,"PhysicalItemSheetPF2e")}static{__name2(this,"PhysicalItemSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("physical"),{...options,hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),{item}=this,bulkAdjustment=getAdjustment(item.system.bulk.value,item._source.system.bulk.value,{better:"lower"}),basePrice=new CoinsPF2e(item._source.system.price.value),priceAdjustment=getAdjustment(item.system.price.value.copperValue,basePrice.copperValue),{actionTraits:actionTraits2}=CONFIG.PF2E,rollData={...item.getRollData(),...this.actor?.getRollData()};sheetData.enrichedContent.unidentifiedDescription=await TextEditor.enrichHTML(sheetData.item.system.identification.unidentified.data.description.value,{rollData,async:!0});const activations=[];for(const action2 of item.activations){const description=await TextEditor.enrichHTML(action2.description.value,{rollData,async:!0});activations.push({action:action2,id:action2.id,base:`system.activations.${action2.id}`,description,traits:createSheetTags(actionTraits2,action2.traits??{value:[]})})}const adjustedLevelHint=(()=>{const hintText=AutomaticBonusProgression.isEnabled(this.actor)?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",levelLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.LevelLabel"):game.i18n.localize("PF2E.LevelLabel").toLocaleLowerCase(game.i18n.lang);return item.level!==item._source.system.level.value?game.i18n.format(hintText,{property:levelLabel,value:item.level}):null})(),adjustedPriceHint=(()=>{if(!priceAdjustment)return null;const baseData=item._source,basePrice2=new CoinsPF2e(baseData.system.price.value).scale(baseData.system.quantity).copperValue,derivedPrice=item.assetValue.copperValue,priceLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.PriceLabel"):game.i18n.localize("PF2E.PriceLabel").toLocaleLowerCase(game.i18n.lang);return basePrice2!==derivedPrice?game.i18n.format(game.i18n.localize("PF2E.Item.Weapon.FromMaterialAndRunes"),{property:priceLabel,value:item.price.value.toString()}):null})(),localizeBulk=localizer("PF2E.Item.Physical.Bulk"),bulks=[0,.1,...Array.fromRange(50,1)].map(value=>value===0?{value,label:localizeBulk("Negligible.Label")}:value===.1?{value,label:localizeBulk("Light.Label")}:{value,label:value.toString()});return{...sheetData,itemType:game.i18n.localize("PF2E.ItemTitle"),sidebarTemplate:"systems/pf2e/templates/items/physical-sidebar.hbs",bulkAdjustment,adjustedLevelHint,basePrice,priceAdjustment,adjustedPriceHint,actionTypes:CONFIG.PF2E.actionTypes,bulks,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,sizes:omit(CONFIG.PF2E.actorSizes,["sm"]),usages:CONFIG.PF2E.usages,isPhysical:!0,activations,bulkDisabled:!!sheetData.data?.stackGroup?.trim()}}render(force,options){return!this.item.isIdentified&&!game.user.isGM?(ui.notifications.warn(this.item.description),this):super.render(force,options)}getMaterialSheetData(item,valuationData){const preciousMaterials2=CONFIG.PF2E.preciousMaterials,isSpecificMagicItem=item.isSpecific,materials=Object.entries(valuationData).reduce((result,[materialKey,materialData])=>{const validGrades=[...PRECIOUS_MATERIAL_GRADES].filter(grade=>!!materialData[grade]&&(!isSpecificMagicItem||item.system.material.type===materialKey));return validGrades.length&&(result[materialKey]={label:game.i18n.localize(preciousMaterials2[materialKey]),grades:Object.fromEntries(validGrades.map(grade=>[grade,{value:JSON.stringify({type:materialKey,grade}),label:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}]))}),result},{});return{value:JSON.stringify(pick(this.item.material,["type","grade"])),materials}}activateListeners($html){super.activateListeners($html),$html.find("[data-action=activation-add]").on("click",event2=>{event2.preventDefault();const id=foundry.utils.randomID(16),action2={id,actionCost:{value:1,type:"action"},components:{command:!1,envision:!1,interact:!1,cast:!1},description:{value:""},traits:{value:[],custom:""}};this.item.update({[`system.activations.${id}`]:action2})}),$html.find("[data-action=activation-delete]").on("click",event2=>{event2.preventDefault();const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");Object.values(this.item.system.activations??[]).length===1&&id&&id in(this.item.system.activations??{})?this.item.update({"system.-=activations":null}):this.item.update({[`system.activations.-=${id}`]:null})}),$html.find("[data-action=activation-frequency-add]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");if(id&&id in(this.item.system.activations??{})){const per=CONFIG.PF2E.frequencies.day;this.item.update({[`system.activations.${id}.frequency`]:{value:1,max:1,per}})}}),$html.find("[data-action=activation-frequency-delete]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");id&&id in(this.item.system.activations??{})&&this.item.update({[`system.activations.${id}.-=frequency`]:null})})}async _updateObject(event2,formData){formData["system.quantity"]===null&&(formData["system.quantity"]=0);const[materialType,materialGrade]=[formData["system.material.type"],formData["system.material.grade"]],typeIsValid=materialType===void 0||typeof materialType=="string"&&materialType in CONFIG.PF2E.preciousMaterials,gradeIsValid=materialGrade===void 0||typeof materialGrade=="string"&&materialGrade in CONFIG.PF2E.preciousMaterialGrades;(!typeIsValid||!gradeIsValid)&&(formData["system.material.type"]=null,formData["system.material.grade"]=null),formData["system.baseItem"]===""&&(formData["system.baseItem"]=null),"system.price.value"in formData&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"])));const expanded=foundry.utils.expandObject(formData);for(const action2 of Object.values(expanded.system?.activations??[])){const actionCost=action2.actionCost;if(actionCost){const isAction=actionCost.type==="action";actionCost.value||(actionCost.value=isAction?actionCost.value||1:null)}}return super._updateObject(event2,foundry.utils.flattenObject(expanded))}}class ArmorPF2e extends PhysicalItemPF2e{static{__name(this,"ArmorPF2e")}static{__name2(this,"ArmorPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get isBarding(){return["light-barding","heavy-barding"].includes(this.category)}get baseType(){return this.system.baseItem??null}get group(){return this.system.group||null}get category(){return this.system.category}get dexCap(){return this.system.dexCap}get strength(){return this.system.strength}get checkPenalty(){return this.system.checkPenalty||0}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}getRollOptions(prefix="armor"){const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,[`base:${this.baseType}`]:!!this.baseType,"rune:potency":this.system.runes.potency>0,"rune:resilient":this.system.runes.resilient>0}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`),...this.system.runes.property.map(r=>`${prefix}:rune:property:${sluggify(r)}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"wornarmor"},super.prepareBaseData(),AutomaticBonusProgression.cleanupRunes(this);const maxPropertySlots=getPropertyRuneSlots(this);this.system.runes.property.length=Math.min(this.system.runes.property.length,maxPropertySlots);const abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),baseTraits=this.system.traits.value,investedTrait=this.system.runes.potency||this.system.runes.resilient||abpEnabled&&this.system.runes.property.length>0?"invested":null,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=investedTrait&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,investedTrait,magicTrait]).sort())}prepareDerivedData(){super.prepareDerivedData();const potencyRune=this.isInvested&&!AutomaticBonusProgression.isEnabled(this.actor)?this.system.runes.potency:0,baseArmor=Number(this.system.acBonus)||0;this.system.acBonus=baseArmor+potencyRune}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");if(this.isEquipped)for(const rollOption of this.getRollOptions("armor"))actor.rollOptions.all[rollOption]=!0}async getChatData(htmlOptions={}){const properties=[CONFIG.PF2E.armorCategories[this.category],`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,`${this.system.dexCap||0} ${game.i18n.localize("PF2E.ArmorDexLabel")}`,`${this.system.checkPenalty||0} ${game.i18n.localize("PF2E.ArmorCheckLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.armorTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseArmorTypes[this.baseType]:null,group=this.group?CONFIG.PF2E.armorGroups[this.group]:null,fallback="TYPES.Item.armor",itemType=game.i18n.localize(base??group??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.group!==void 0&&(changed.system.group||=null),changed.system.dexCap!==void 0){const integerValue=Math.floor(Number(changed.system.dexCap))||0;changed.system.dexCap=Math.max(0,integerValue)}if(changed.system.checkPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.checkPenalty))||0;changed.system.checkPenalty=Math.min(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return super._preUpdate(changed,options,user)}}class BookPF2e extends PhysicalItemPF2e{static{__name(this,"BookPF2e")}static{__name2(this,"BookPF2e")}}class InventoryBulk{static{__name(this,"InventoryBulk")}static{__name2(this,"InventoryBulk")}actor;#value=null;encumberedAfterAddend=0;maxAddend=0;constructor(actor){this.actor=actor}get#actorStrength(){return this.actor.isOfType("character","npc")?this.actor.abilities.str.mod:1/0}get encumberedAfter(){return Math.floor(this.#actorStrength+5+this.encumberedAfterAddend)}get encumberedAfterBreakdown(){const addend=this.encumberedAfterAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`5 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get max(){return Math.floor(this.#actorStrength+10+this.maxAddend)}get maxBreakdown(){const addend=this.maxAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`10 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get value(){return this.#value?this.#value:(this.#value=InventoryBulk.computeTotalBulk(this.actor.inventory.filter(i=>!i.isInContainer),this.actor.size),this.#value)}get encumberedPercentage(){const totalTimes10=this.value.toLightUnits(),encumberedAtTimes10=this.encumberedAfter*10+10;return Math.floor(totalTimes10/encumberedAtTimes10*100)}get maxPercentage(){const totalTimes10=this.value.toLightUnits(),limitTimes10=this.max*10+10;return Math.floor(totalTimes10/limitTimes10*100)}get maxPercentageInteger(){return this.maxPercentage>100?100:this.maxPercentage}get isEncumbered(){return this.value.normal>this.encumberedAfter}get isOverMax(){return this.value.normal>this.max}get bulk(){return this.value.normal}static computeTotalBulk(items,actorSize){items=this.#flattenNonStowing(items);const nonStackingItems=items.filter(i=>i.isOfType("backpack")||i.system.bulk.per===1&&i.system.baseItem),nonStackingIds=new Set(nonStackingItems.map(i=>i.id)),stackingItems=items.filter(i=>!nonStackingIds.has(i.id)),baseBulk=nonStackingItems.map(i=>i.bulk).reduce((first,second)=>first.plus(second),new Bulk),stackingBehaviors=stackingItems.map(item=>({per:item.system.bulk.per,item,group:item.system.baseItem,bulk:new Bulk(item.system.bulk.value).convertToSize(item.size,actorSize)})),bulks=[...groupBy(stackingBehaviors,d=>`${d.group}-${d.per}-${d.bulk.toLightUnits()}`).values()].map(dataEntries=>{const{bulk,per}=dataEntries[0],quantity=dataEntries.map(entry=>entry.item.quantity).reduce((sum,value)=>sum+value,0),bulkRelevantQuantity=Math.floor(quantity/per);return bulk.times(bulkRelevantQuantity)});return baseBulk.plus(bulks.reduce((first,second)=>first.plus(second),new Bulk))}static#flattenNonStowing(items){return items.map(item=>item.isOfType("backpack")&&!item.stowsItems?this.#flattenNonStowing(item.contents.contents):item).flat()}}class ActorInventory extends DelegatedCollection{static{__name(this,"ActorInventory")}static{__name2(this,"ActorInventory")}actor;bulk;constructor(actor,entries){super(entries?.map(entry=>[entry.id,entry])),this.actor=actor,this.bulk=new InventoryBulk(this.actor)}get coins(){return this.filter(i=>i.isOfType("treasure")&&i.isCoinage).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get totalWealth(){return this.filter(item=>game.user.isGM||item.isIdentified).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get invested(){return this.actor.isOfType("character")?{value:this.filter(item=>!!item.isInvested).length,max:this.actor.system.resources.investiture.max}:null}findStackableItem(item){const testItem=item instanceof PhysicalItemPF2e?item.clone():new ItemProxyPF2e(foundry.utils.deepClone(item));if(!testItem.isOfType("physical"))return null;const stackCandidates=this.filter(i=>!i.isInContainer&&i.isStackableWith(testItem));if(stackCandidates.length===0)return null;if(stackCandidates.length>1){const notEquipped=stackCandidates.filter(item2=>!item2.isEquipped);return notEquipped.length>0?notEquipped[0]:stackCandidates[0]}else return stackCandidates[0]}async addCoins(coins,{combineStacks=!0}={}){const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>combineStacks&&item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){const quantity=coins[denomination]??0;if(quantity>0){const item=coinsByDenomination.get(denomination)?.at(0);if(item)await item.update({"system.quantity":item.quantity+quantity});else{const compendiumId=coinCompendiumIds[denomination],pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd");if(!pack)throw ErrorPF2e("Unexpected error retrieving equipment compendium");const item2=(await pack.getDocument(compendiumId))?.clone();item2?.isOfType("treasure")&&(item2.updateSource({"system.quantity":quantity}),await this.actor.createEmbeddedDocuments("Item",[item2.toObject()]))}}}}async removeCoins(coins,{byValue=!0}={}){const coinsToRemove=new CoinsPF2e(coins),actorCoins=this.coins,coinsToAdd=new CoinsPF2e;if(byValue){let valueToRemoveInCopper=coinsToRemove.copperValue;if(valueToRemoveInCopper>actorCoins.copperValue)return!1;if(valueToRemoveInCopper%10>actorCoins.cp)coinsToAdd.cp=10,coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper+=10-coinsToRemove.cp;else{coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper-=coinsToRemove.cp;const newCopper=actorCoins.cp-coinsToRemove.cp,extraCopper=Math.min(valueToRemoveInCopper/10,Math.trunc(newCopper/10))*10;coinsToRemove.cp+=extraCopper,valueToRemoveInCopper-=extraCopper}if(valueToRemoveInCopper/10%10>actorCoins.sp)coinsToAdd.sp=10,coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper+=100-coinsToRemove.sp*10;else{coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper-=coinsToRemove.sp*10;const newSilver=actorCoins.sp-coinsToRemove.sp,extraSilver=Math.min(valueToRemoveInCopper/100,Math.trunc(newSilver/10))*10;coinsToRemove.sp+=extraSilver,valueToRemoveInCopper-=extraSilver*10}if(valueToRemoveInCopper/100%10>actorCoins.gp)coinsToAdd.gp=10,coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper+=1e3-coinsToRemove.gp*100;else{coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper-=coinsToRemove.gp*100;const newGold=actorCoins.gp-coinsToRemove.gp,extraGold=Math.min(valueToRemoveInCopper/1e3,Math.trunc(newGold/10))*10;coinsToRemove.gp+=extraGold,valueToRemoveInCopper-=extraGold*100}coinsToRemove.pp=valueToRemoveInCopper/1e3}const coinsToPull=actorCoins.add(coinsToAdd);if(!(coinsToRemove.pp<=coinsToPull.pp&&coinsToRemove.gp<=coinsToPull.gp&&coinsToRemove.sp<=coinsToPull.sp&&coinsToRemove.cp<=coinsToPull.cp))return!1;Object.values(coinsToAdd).some(value=>value!==0)&&await this.addCoins(coinsToAdd);const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){let quantityToRemove=coinsToRemove[denomination];const coinItems=coinsByDenomination.get(denomination);if(quantityToRemove&&coinItems){const itemsToUpdate=[],itemsToDelete=[];for(const item of coinItems){if(quantityToRemove===0)break;if(item.quantity>quantityToRemove){itemsToUpdate.push({_id:item.id,"system.quantity":item.quantity-quantityToRemove}),quantityToRemove=0;break}else quantityToRemove-=item.quantity,itemsToDelete.push(item.id)}itemsToUpdate.length>0&&await this.actor.updateEmbeddedDocuments("Item",itemsToUpdate),itemsToDelete.length>0&&await this.actor.deleteEmbeddedDocuments("Item",itemsToDelete),quantityToRemove>0&&console.warn("Attempted to remove more coinage than exists")}}return!0}async sellAllTreasure(){const treasures=this.actor.itemTypes.treasure.filter(item=>!item.isCoinage),treasureIds=treasures.map(item=>item.id),coins=treasures.map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e);await this.actor.deleteEmbeddedDocuments("Item",treasureIds),await this.actor.inventory.addCoins(coins)}async add(item,options={}){if(options.stack&&item.isOfType("physical")){const stackableItem=this.findStackableItem(item._source);if(stackableItem){await stackableItem.update({"system.quantity":stackableItem.quantity+item.quantity});return}}await this.actor.createEmbeddedDocuments("Item",[item.toObject()])}}class ContainerPF2e extends PhysicalItemPF2e{static{__name(this,"ContainerPF2e")}static{__name2(this,"ContainerPF2e")}contents=new Collection;get stowsItems(){return this.system.stowing}get isCollapsed(){return this.system.collapsed}get capacity(){return{value:InventoryBulk.computeTotalBulk(this.contents.contents,this.actor?.size??"med"),max:new Bulk(this.system.bulk.capacity)}}get percentFull(){const{value,max}=this.capacity,realPercent=Math.floor(value.toLightUnits()/max.toLightUnits()*100);return realPercent>100?Math.floor(value.normal/max.normal*100):realPercent}get bulkIgnored(){const isOverfilled=this.percentFull>100,extradimensionalParadox=this.traits.has("extradimensional")&&hasExtraDimensionalParent(this);return!isOverfilled&&!extradimensionalParadox?new Bulk(this.system.bulk.ignored):new Bulk}get bulk(){return super.bulk.plus(this.capacity.value.minus(this.bulkIgnored))}prepareSiblingData(){super.prepareSiblingData(),this.contents=new Collection(this.actor.inventory.filter(i=>i.container?.id===this.id).map(item=>[item.id,item]))}async ejectContents(){if(!this.actor)return;const updates=this.contents.map(i=>({_id:i.id,"system.containerId":this.container?.id??null}));await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}_preUpdate(changed,options,user){if(!changed.system?.bulk)return super._preUpdate(changed,options,user);changed.system.bulk.heldOrStowed!==void 0&&(changed.system.bulk.heldOrStowed=Math.clamped(Number(changed.system.bulk.heldOrStowed),0,999)||0,Number.isInteger(changed.system.bulk.heldOrStowed)||(changed.system.bulk.heldOrStowed=.1));for(const property of["capacity","ignored"])changed.system.bulk[property]!==void 0&&(changed.system.bulk[property]=Math.clamped(Math.trunc(Number(changed.system.bulk[property])),0,999)||0);return super._preUpdate(changed,options,user)}}class EquipmentPF2e extends PhysicalItemPF2e{static{__name(this,"EquipmentPF2e")}static{__name2(this,"EquipmentPF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}prepareBaseData(){super.prepareBaseData(),this.system.apex&&(this.traits.has("apex")?this.isInvested||(this.system.apex.selected=!1):delete this.system.apex)}prepareSiblingData(){if(super.prepareSiblingData(),!this.system.apex)return;const otherApexData=this.actor.itemTypes.equipment.flatMap(e=>e===this?[]:e.system.apex??[]);if(this.system.apex.selected||this.isInvested&&otherApexData.every(d=>!d.selected)){this.system.apex.selected=!0;for(const data of otherApexData)data.selected=!1}}prepareActorData(){const{actor}=this;actor?.isOfType("character")&&this.system.apex?.selected&&(actor.system.build.attributes.apex?this.system.apex.selected=!1:actor.system.build.attributes.apex=this.system.apex.attribute)}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const identificationConfig=CONFIG.PF2E.identification,slotType=/book\b/.test(this.slug??"")?"Book":/\bring\b/.test(this.slug??"")?"Ring":this.system.usage.value?.replace(/^worn/,"").capitalize()??"",itemType=objectHasKey(identificationConfig.UnidentifiedType,slotType)?game.i18n.localize(identificationConfig.UnidentifiedType[slotType]):game.i18n.localize(identificationConfig.UnidentifiedType.Object);return typeOnly?itemType:game.i18n.format(identificationConfig.UnidentifiedItem,{item:itemType})}async _preCreate(data,options,user){return delete this._source.system.apex?.selected,super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const changedTraits=changed.system?.traits?.value;return!(this._source.system.traits.value.includes("apex")&&(!Array.isArray(changedTraits)||changedTraits.includes("apex")))&&this._source.system.apex&&(delete changed.system?.apex,changed.system??={},changed.system=foundry.utils.mergeObject(changed.system,{"-=apex":null})),super._preUpdate(changed,options,user)}}class TreasurePF2e extends PhysicalItemPF2e{static{__name(this,"TreasurePF2e")}static{__name2(this,"TreasurePF2e")}get isCoinage(){return this.system.stackGroup==="coins"}get denomination(){if(!this.isCoinage)return null;const options=DENOMINATIONS.filter(denomination=>!!this.price.value[denomination]);return options.length===1?options[0]:null}prepareBaseData(){super.prepareBaseData(),this.isCoinage&&(this.system.size="med")}async getChatData(htmlOptions={}){const systemData=this.system,traits=this.traitChatData({});return this.processChatData(htmlOptions,{...systemData,traits})}}class WeaponPF2e extends PhysicalItemPF2e{static{__name(this,"WeaponPF2e")}static{__name2(this,"WeaponPF2e")}constructor(data,context={}){super(data,context),context.shield&&(this.shield=context.shield)}altUsageType=null;get isEquipped(){const{category,slug,traits}=this.system;return category==="unarmed"&&slug!=="handwraps-of-mighty-blows"?!0:super.isEquipped||this.handsHeld===1&&traits.value.some(t=>/^jousting-d\d{1,2}$/.test(t))}isStackableWith(item){if(this.category==="unarmed"||!item.isOfType("weapon")||item.category==="unarmed")return!1;const equippedButStackable=["bomb","dart"].includes(this.group??"");return(this.isEquipped||item.isEquipped)&&!equippedButStackable?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem}get group(){return this.system.group}get category(){return this.system.category}get defaultAttribute(){return this.system.attribute??(this.isRanged?"dex":"str")}get hands(){return{worngloves:"0","held-in-one-hand":"1","held-in-one-plus-hands":"1+","held-in-two-hands":"2"}[this.system.usage.value]??"1"}get maxRange(){return this.system.maxRange??(this.system.range?this.system.range*6:null)}get range(){const rangeIncrement=this.system.range,maxRange=this.system.maxRange;return maxRange?{increment:null,max:maxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get reload(){return this.system.reload.value||null}get isSpecific(){return!!this.system.specific}get isMelee(){return!this.isRanged}get isRanged(){return!!this.system.range}get isThrown(){return this.isRanged&&(this.baseType==="alchemical-bomb"||this.system.traits.value.includes("thrown"))}get isThrowable(){return this.isThrown||this.system.traits.value.some(t=>t.startsWith("thrown"))||!!this.system.meleeUsage?.traits.some(t=>t.startsWith("thrown"))}get isOversized(){return this.category!=="unarmed"&&!!this.parent?.system.traits?.size.isSmallerThan(this.size,{smallIsMedium:!0})}get baseDamage(){return{...foundry.utils.deepClone(this.system.damage),damageType:this.system.traits.toggles.versatile.selection??this.system.traits.toggles.modular.selection??this.system.damage.damageType}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||this.system.splashDamage.value>0||!!baseDamage.persistent?.number}get requiresAmmo(){return this.isRanged&&!this.isThrown&&![null,"-"].includes(this.reload)}get ammo(){const ammo=this.actor?.items.get(this.system.selectedAmmoId??"");return ammo?.isOfType("consumable","weapon")?ammo:null}get otherTags(){return new Set(this.system.traits.otherTags)}isAmmoFor(weapon){return this.system.usage.canBeAmmo&&!weapon.system.traits.value.includes("repeating")}getRollOptions(prefix=this.type){const{baseDamage}=this,damage={category:DamageCategorization.fromDamageType(baseDamage.damageType),type:baseDamage.damageType,dice:{number:baseDamage.die?baseDamage.dice:0,faces:Number(baseDamage.die?.replace(/^d/,""))}},{actor}=this,isDeityFavored=!!(this.baseType&&actor?.isOfType("character")&&actor.deity?.favoredWeapons.includes(this.baseType)),thrownMelee=this.isThrown&&this.altUsageType==="thrown",baseTypeRollOptions=(()=>{const equivalentBases=CONFIG.PF2E.equivalentWeapons;return[this.baseType??[],equivalentBases[this.baseType??""]??[]].flat().reduce((types,t)=>({...types,[`base:${t}`]:!0}),{})})(),{persistent}=this.system.damage,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),ammunitionRollOptions=(ammunition=>{const rollOptions2={};if(ammunition){rollOptions2[`ammo:id:${ammunition.id}`]=!0,rollOptions2[`ammo:slug:${ammunition.slug}`]=!0,rollOptions2[`ammo:level:${ammunition.level}`]=!0,rollOptions2[`ammo:material:type:${ammunition.material.type}`]=!!ammunition.material.type,rollOptions2[`ammo:material:grade:${ammunition.material.grade}`]=!!ammunition.material.grade;for(const trait of ammunition.traits)rollOptions2[`ammo:trait:${trait}`]=!0}return rollOptions2})(this.ammo),bulk=(()=>{const unitBulk=this.bulk.times(1/this.quantity);return unitBulk.isNegligible?"negligible":unitBulk.isLight?"light":unitBulk.toString()})(),rangeIncrement=this.range?.increment,rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,...baseTypeRollOptions,[`base:${this.baseType}`]:!!this.baseType,[`bulk:${bulk}`]:!0,[`usage:hands:${this.hands}`]:this.hands!=="0",[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`reload:${this.reload}`]:!!this.reload,[`damage:type:${damage.type}`]:!0,[`damage:category:${damage.category}`]:!!damage.category,[`damage:die:number:${damage.dice.number}`]:!!damage.dice.faces,[`damage:die:faces:${damage.dice.faces}`]:!!damage.dice.faces,[`damage-dice:${damage.dice.number}`]:!!damage.dice.faces,[`damage:persistent:${persistent?.type}`]:!!persistent,"deity-favored":isDeityFavored,oversized:this.isOversized,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,"thrown-melee":thrownMelee,...propertyRunes,...ammunitionRollOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){super.prepareBaseData(),this.system.category||="simple",this.system.group||=null,this.system.baseItem||=null,this.system.bonusDamage.value||=0,this.system.splashDamage.value||=0,this.system.graspingAppendage=["fist","claw"].includes(this.baseType??"")?!0:this.category==="unarmed"?!!this.system.graspingAppendage:!1,setHasElement(ATTRIBUTE_ABBREVIATIONS,this.system.attribute)||(this.system.attribute=null);const reloadValue=this.system.reload.value||=null;this.system.reload.label=reloadValue?game.i18n.format("PF2E.Item.Weapon.Reload.LabelN",{value:CONFIG.PF2E.weaponReload[reloadValue]}):null,this.system.selectedAmmoId||=null,this.system.damage.die||=null,this.system.damage.modifier??=0,!this.system.damage.die&&this.system.damage.dice>0&&(this.system.damage.modifier||=this.system.damage.dice),this.isThrown&&!tupleHasValue(["-","0"],this.system.reload.value)&&(this.system.reload.value="-"),this.system.category==="unarmed"&&!this.system.traits.value.includes("unarmed")&&this.system.traits.value.push("unarmed"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits);const traitSet=this.traits,mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,this.system.group)||traitSet.has("thrown");mandatoryRanged&&(this.system.range??=10),this.system.meleeUsage&&(this.system.meleeUsage.traits??=[],this.system.meleeUsage.traitToggles??={modular:null,versatile:null}),this.system.traits.toggles=new WeaponTraitToggles(this);const traitsArray=this.system.traits.value;this.system.category==="unarmed"&&!traitsArray.includes("unarmed")&&this.system.traits.value.push("unarmed"),!mandatoryRanged&&traitsArray.some(t=>/^thrown-\d+$/.test(t))&&(this.system.range=null),this.system.reload.consume=this.isMelee?null:this.reload!==null,this.system.usage.canBeAmmo=this._source.system.usage.canBeAmmo??!1,this.flags.pf2e.comboMeleeUsage??=!1,AutomaticBonusProgression.cleanupRunes(this);const{runes}=this.system;runes.effects=[],runes.property.length=Math.min(runes.property.length,getPropertyRuneSlots(this));const{actor}=this,inherentDiceNumber=this.system.damage.die?this._source.system.damage.dice:0,strikingDice=AutomaticBonusProgression.isEnabled(actor)?AutomaticBonusProgression.getStrikingDice(actor?.level??0):this.system.runes.striking;this.system.damage.dice=inherentDiceNumber===1&&!this.flags.pf2e.battleForm?inherentDiceNumber+strikingDice:this.system.damage.dice;const baseTraits=this.system.traits.value,magicTrait=(runes.potency>0||runes.striking>0||runes.property.length>0)&&!baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t))?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()),this.flags.pf2e.attackItemBonus=this.system.runes.potency||this.system.bonus.value||0}prepareDerivedData(){super.prepareDerivedData(),this.system.usage.canBeAmmo&&!this.isThrowable&&(this.system.usage.canBeAmmo=!1)}prepareSiblingData(){super.prepareSiblingData();const ammoRules=this.ammo?.system.rules.map(r=>({label:this.ammo?.name,...foundry.utils.deepClone(r)}))??[];this.system.rules.push(...ammoRules)}async getChatData(htmlOptions={}){const traits=this.traitChatData(CONFIG.PF2E.weaponTraits),chatData=await super.getChatData(),rangeLabel=createActionRangeLabel(this.range),properties=compact([CONFIG.PF2E.weaponCategories[this.category],this.system.reload.label,rangeLabel]);return this.processChatData(htmlOptions,{...chatData,traits,properties})}getMystifiedData(status,{source=!1}={}){const mystifiedData=super.getMystifiedData(status);return source&&(mystifiedData.name=this._source.name),mystifiedData}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes,base=this.baseType?baseWeaponTypes2[this.baseType]??baseShieldTypes2[this.baseType]??null:null,group=this.group?CONFIG.PF2E.weaponGroups[this.group]:null,itemType=game.i18n.localize(base??group??"TYPES.Item.weapon");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getAltUsages({recurse=!0}={}){const meleeUsage=this.toMeleeUsage();return[this.toThrownUsage()??[],meleeUsage??[],recurse?meleeUsage?.toThrownUsage()??[]:[]].flat()}clone(data,context){const clone=super.clone(data,context);return context?.altUsage&&clone instanceof WeaponPF2e&&(clone.altUsageType=context.altUsage),clone}toThrownUsage(){const traits=this._source.system.traits.value,thrownTrait=traits.find(t=>/^thrown-\d{1,3}$/.test(t));if(this.isRanged||!thrownTrait)return null;const range2=Number(/(\d{1,3})$/.exec(thrownTrait)?.at(1)),newTraits=foundry.utils.deepClone(traits);newTraits.splice(newTraits.indexOf(thrownTrait),1,"thrown");const overlay={system:{range:range2,traits:{value:newTraits}}};return this.clone(overlay,{keepId:!0,altUsage:"thrown"})}toMeleeUsage(){const{meleeUsage}=this.system;if(!meleeUsage||this.flags.pf2e.comboMeleeUsage)return null;const traitToggles={module:{selection:meleeUsage.traitToggles.modular},versatile:{selection:meleeUsage.traitToggles.versatile}},overlay={system:{damage:{damageType:meleeUsage.damage.type,dice:1,die:meleeUsage.damage.die},group:meleeUsage.group,range:null,reload:{value:null},traits:{value:meleeUsage.traits.concat("combination"),toggles:traitToggles},selectedAmmoId:null},flags:{pf2e:{comboMeleeUsage:!0}}};return this.clone(overlay,{keepId:!0,altUsage:"melee"})}toNPCAttacks({keepId=!1}={}){const{actor}=this;if(!actor.isOfType("npc"))throw ErrorPF2e("Melee items can only be generated for NPCs");const baseDamage=(()=>{const weaponDamage=this.baseDamage,ability=this.range?.increment&&!this.isThrown?"dex":"str",actorLevel=actor.system.details.level.base,dice=this.flags.pf2e.fixedAttack?weaponDamage.dice:[1,2,3,4].reduce((closest,dice2)=>Math.abs(dice2-Math.round((actorLevel+2)/4))<Math.abs(closest-Math.round((actorLevel+2)/4))?dice2:closest),constant=(()=>{const fromAbility=actor.abilities[ability].mod,totalModifier=this.flags.pf2e.fixedAttack?weaponDamage.modifier:fromAbility+(actor.level>1?dice:0),sign=totalModifier<0?"-":"+";return totalModifier===0?"":[sign,Math.abs(totalModifier)].join("")})();return{damage:weaponDamage.die?`${dice}${weaponDamage.die}${constant}`:dice.toString(),damageType:weaponDamage.damageType,category:null}})(),fromPropertyRunes=this.system.runes.property.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.dice??[]).map(d=>({damage:`${d.diceNumber}${d.dieSize}`,damageType:d.damageType??baseDamage.damageType,category:d.category??null})),reachTraitToNPCReach={tiny:null,sm:"reach-10",med:"reach-10",lg:"reach-15",huge:"reach-20",grg:"reach-25"},toAttackTraits=__name2(traits=>{const{increment:rangeIncrement,max:maxRange}=this.range??{},newTraits=traits.flatMap(t=>t==="reach"?reachTraitToNPCReach[this.size]??[]:t==="thrown"&&setHasElement(THROWN_RANGES,rangeIncrement)?`thrown-${rangeIncrement}`:t).filter(t=>(["holy","unholy"].includes(t)||!(t in CONFIG.PF2E.creatureTraits))&&!(t.startsWith("thrown")&&!this.isThrown)&&!(["grapple","finesse","shove","trip"].includes(t)&&this.isRanged)&&!(t==="brutal"&&this.isMelee)&&!(t==="combination"&&(this.isMelee||this.isThrown))&&!(t==="critical-fusion"&&this.isThrown)&&!["artifact","cursed"].includes(t));if(traits.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&newTraits.push("magical"),rangeIncrement&&!this.isThrown){const prefix=maxRange===rangeIncrement*6?"range-increment":"range";newTraits.push(`${prefix}-${rangeIncrement}`)}const sizeToReach=SIZE_TO_REACH[actor.size];this.isMelee&&sizeToReach!==5&&!newTraits.some(t=>t.startsWith("reach"))&&newTraits.push(`reach-${sizeToReach}`);const reloadTrait=`reload-${this.reload}`;return objectHasKey(CONFIG.PF2E.npcAttackTraits,reloadTrait)&&newTraits.push(reloadTrait),uniq(newTraits).sort()},"toAttackTraits"),persistentDamage=(()=>{const{persistent}=this.system.damage;return persistent?{damage:persistent.faces?`${persistent.number}d${persistent.faces}`:persistent.number.toString(),damageType:persistent.type,category:"persistent"}:[]})(),splashDamage=this.system.splashDamage.value?{damage:this.system.splashDamage.value.toString(),damageType:this.system.damage.damageType,category:"splash"}:[],source={_id:keepId?this.id:null,name:this._source.name,type:"melee",system:{slug:this.slug??sluggify(this._source.name),weaponType:{value:this.isMelee?"melee":"ranged"},bonus:{value:this.flags.pf2e.fixedAttack||Math.round(1.5*this.actor.level+7)},damageRolls:[baseDamage,splashDamage,fromPropertyRunes,persistentDamage].flat().reduce((rolls,roll)=>foundry.utils.mergeObject(rolls,{[foundry.utils.randomID()]:roll}),{}),traits:{value:toAttackTraits(this.system.traits.value)},rules:foundry.utils.deepClone(this._source.system.rules)},flags:{pf2e:{linkedWeapon:this.id}}},attack=new MeleePF2e(source,{parent:this.actor});return attack.category=this.category,attack.group=this.group,attack.baseType=this.baseType,[attack,...this.getAltUsages({recurse:!1}).flatMap(u=>u.toNPCAttacks())]}async consumeAmmo(){const{ammo}=this;if(ammo?.isOfType("consumable"))return ammo.consume();if(ammo?.isOfType("weapon")){if(!ammo.system.usage.canBeAmmo)throw ErrorPF2e("attempted to consume weapon not usable as ammunition");await ammo.update({"system.quantity":Math.max(ammo.quantity-1,0)})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const traits=changed.system.traits??{};return"value"in traits&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>t in CONFIG.PF2E.weaponTraits)),changed.system.group!==void 0&&(changed.system.group||=null),super._preUpdate(changed,options,user)}_onDelete(options,userId){if(super._onDelete(options,userId),game.user.id===userId){const updates=this.actor?.itemTypes.melee.filter(a=>a.flags.pf2e.linkedWeapon===this.id).map(a=>({_id:a.id,"flags.pf2e.-=linkedWeapon":null}))??[];this.actor?.updateEmbeddedDocuments("Item",updates)}}}class ABCItemPF2e extends ItemPF2e{static{__name(this,"ABCItemPF2e")}static{__name2(this,"ABCItemPF2e")}get rarity(){return this.system.traits.rarity}getLinkedItems(){if(!this.actor||!objectHasKey(this.actor.itemTypes,this.type))return[];const existingABCIds=this.actor.itemTypes[this.type].map(i=>i.id);return this.actor.itemTypes.feat.filter(f=>existingABCIds.includes(f.system.location??""))}async createGrantedItems(options={}){const entries=Object.values(this.system.items);if(!entries.filter(entry=>!!entry.uuid).length)return[];const items=(await UUIDUtils.fromUUIDs(entries.map(e=>e.uuid))).map(i=>i.clone()),level=options.level??this.parent?.level;return items.flatMap(item=>{if(item instanceof FeatPF2e){if(item.category==="classfeature"){const level2=entries.find(e=>item.sourceId===e.uuid)?.level??item.level;item.updateSource({"system.level.value":level2})}return level!==void 0&&level<item.level?[]:(item.updateSource({system:{location:this.id}}),item)}else return console.error("PF2e System | Missing or invalid ABC item"),[]})}logAutoChange(path,value){value===0||!this.actor||(this.actor.system.autoChanges[path]=[{mode:"upgrade",level:1,value,source:this.name}])}}class AncestryPF2e extends ABCItemPF2e{static{__name(this,"AncestryPF2e")}static{__name2(this,"AncestryPF2e")}get traits(){return new Set(this.system.traits.value)}get hitPoints(){return this.system.hp}get speed(){return this.system.speed}get size(){return this.system.size}get lockedBoosts(){return Object.values(this.system.boosts).filter(boost=>boost.value.length===1).map(boost=>boost.selected).filter(boost=>!!boost)}get lockedFlaws(){return Object.values(this.system.flaws).map(flaw=>flaw.selected).filter(flaw=>!!flaw)}getLinkedItems(){return this.actor?Array.from(new Set([...super.getLinkedItems(),...this.actor.itemTypes.feat.filter(f=>f.category==="ancestryfeature")])):[]}prepareBaseData(){super.prepareBaseData();for(const boost of Object.values(this.system.boosts))boost.value.length===1&&(boost.selected=boost.value[0]);for(const flaw of Object.values(this.system.flaws))flaw.value.length===1&&(flaw.selected=flaw.value[0])}prepareActorData(){const{actor}=this;if(!actor.isOfType("character")){console.error("PF2e System | Only a character can have an ancestry");return}actor.ancestry=this,actor.system.attributes.ancestryhp=this.hitPoints,this.logAutoChange("system.attributes.ancestryhp",this.hitPoints),actor.system.traits.size.value=this.size,this.logAutoChange("system.traits.size.value",this.size);const reach=SIZE_TO_REACH[this.size];actor.system.attributes.reach={base:reach,manipulate:reach},actor.system.attributes.speed.value=this.speed;const{build}=actor.system;if(this.system.alternateAncestryBoosts)build.attributes.boosts.ancestry.push(...this.system.alternateAncestryBoosts);else for(const target of["boosts","flaws"])for(const ability of Object.values(this.system[target]))ability.selected&&build.attributes[target].ancestry.push(ability.selected);if(this.system.voluntary){const{boost,flaws}=this.system.voluntary;boost&&build.attributes.boosts.ancestry.push(boost),build.attributes.flaws.ancestry.push(...flaws)}const innateLanguages=this.system.languages.value;for(const language of innateLanguages)language in CONFIG.PF2E.languages&&!actor.system.traits.languages.value.includes(language)&&actor.system.traits.languages.value.push(language);const{senses:senses2}=actor.system.traits,{vision}=this.system;if(!(vision==="normal"||senses2.some(sense=>sense.type===vision))){senses2.push(new CreatureSensePF2e({type:vision,value:"",source:this.name}));const senseRollOptions=actor.rollOptions.sense??={};senseRollOptions[`self:${sluggify(vision)}:from-ancestry`]=!0}actor.system.traits.value.push(...this.traits);const slug=this.slug??sluggify(this.name);actor.system.details.ancestry={name:this.name,trait:slug,adopted:null,versatile:null,countsAs:[slug]},actor.rollOptions.all[`self:ancestry:${slug}`]=!0;for(const trait of this.traits)actor.rollOptions.all[`self:trait:${trait}`]=!0}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),`${prefix}:rarity:${this.rarity}`]}}class BackgroundPF2e extends ABCItemPF2e{static{__name(this,"BackgroundPF2e")}static{__name2(this,"BackgroundPF2e")}get traits(){return new Set(this.system.traits.value)}prepareSiblingData(){if(Object.keys(this.system.items).length>0)return;const grantedSkillFeat=Object.values(this.flags.pf2e.itemGrants).flatMap(g=>this.actor.items.get(g.id)??[]).find(i=>i.isOfType("feat")&&i.category==="skill");grantedSkillFeat&&(this.system.items.GRANT={uuid:grantedSkillFeat.sourceId??grantedSkillFeat.uuid,img:grantedSkillFeat.img,name:grantedSkillFeat.name,level:1},grantedSkillFeat.system.level.taken=1,grantedSkillFeat.system.location=this.id)}prepareActorData(){if(!this.actor.isOfType("character")){console.error("Only a character can have a background");return}this.actor.background=this;const{build}=this.actor.system,boosts=Object.values(this.system.boosts);for(const boost of boosts)boost.selected&&build.attributes.boosts.background.push(boost.selected);const{trainedSkills}=this.system;if(trainedSkills.value.length===1){const key=trainedSkills.value[0],skill=this.actor.system.skills[key];skill.rank=Math.max(skill.rank,1)}}}class ClassPF2e extends ABCItemPF2e{static{__name(this,"ClassPF2e")}static{__name2(this,"ClassPF2e")}get attacks(){return this.system.attacks}get defenses(){return this.system.defenses}get hpPerLevel(){return this.system.hp}get perception(){return this.system.perception}get savingThrows(){return this.system.savingThrows}get grantedFeatSlots(){const system=this.system;return{ancestry:foundry.utils.deepClone(system.ancestryFeatLevels.value),class:[...system.classFeatLevels.value],skill:[...system.skillFeatLevels.value],general:[...system.generalFeatLevels.value]}}getLinkedItems(){const{actor}=this;return actor?Array.from(new Set([...super.getLinkedItems(),...actor.itemTypes.feat.filter(f=>f.category==="classfeature"&&!(f.flags.pf2e.grantedBy&&actor.items.has(f.flags.pf2e.grantedBy.id)))])):[]}async createGrantedItems(options={}){return(await super.createGrantedItems(options)).sort((a,b)=>a.system.level.value-b.system.level.value)}prepareBaseData(){super.prepareBaseData();const{keyAbility}=this.system;keyAbility.selected??=keyAbility.value.length===1?keyAbility.value[0]:null}prepareActorData(){if(!this.actor?.isOfType("character")){console.error("Only a character can have a class");return}this.actor.class=this;const{attributes,build,details,proficiencies,saves,skills}=this.actor.system,slug=this.slug??sluggify(this.name);build.attributes.keyOptions=[...this.system.keyAbility.value],build.attributes.boosts.class=this.system.keyAbility.selected,attributes.classhp=this.hpPerLevel,attributes.perception.rank=Math.max(attributes.perception.rank,this.perception),this.logAutoChange("system.attributes.perception.rank",this.perception),details.keyability.value=(build.attributes.manual?details.keyability.value:build.attributes.boosts.class)??"str";const classDCs=proficiencies.classDCs;classDCs[slug]={label:this.name,rank:1,ability:details.keyability.value,primary:!0},this.logAutoChange(`system.proficiencies.classDCs.${slug}.rank`,1);const{attacks,defenses}=proficiencies;for(const category of WEAPON_CATEGORIES)attacks[category].rank=Math.max(attacks[category].rank,this.attacks[category]),this.logAutoChange(`system.proficiencies.attacks.${category}.rank`,this.attacks[category]);const nonBarding=Array.from(ARMOR_CATEGORIES).filter(c=>!["light-barding","heavy-barding"].includes(c));for(const category of nonBarding)defenses[category].rank=Math.max(defenses[category].rank,this.defenses[category]),this.logAutoChange(`system.proficiencies.defenses.${category}.rank`,this.defenses[category]);for(const saveType of SAVE_TYPES)saves[saveType].rank=Math.max(saves[saveType].rank,this.savingThrows[saveType]),this.logAutoChange(`system.saves.${saveType}.rank`,this.savingThrows[saveType]);for(const trainedSkill of this.system.trainedSkills.value)setHasElement(SKILL_ABBREVIATIONS,trainedSkill)&&(skills[trainedSkill].rank=Math.max(skills[trainedSkill].rank,1));proficiencies.spellcasting.rank=Math.max(proficiencies.spellcasting.rank,this.system.spellcasting),this.logAutoChange("system.proficiencies.spellcasting.rank",this.system.spellcasting),details.class={name:this.name,trait:slug},this.actor.rollOptions.all[`class:${slug}`]=!0}}class AbilityItemPF2e extends ItemPF2e{static{__name(this,"AbilityItemPF2e")}static{__name2(this,"AbilityItemPF2e")}range=null;get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}prepareBaseData(){super.prepareBaseData(),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.actionTraits)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);return(this.frequency||this.system.deathNote)&&options.push(`${prefix}:frequency:limited`),options}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...this.system,traits:this.traitChatData(CONFIG.PF2E.featTraits)})}async _preCreate(data,options,user){return this.parent||this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null}),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){return typeof changed.system?.category=="string"&&(changed.system.category||=null),normalizeActionChangeData(this,changed),super._preUpdate(changed,options,user)}}const KINGDOM_CATEGORY_DATA={"army-tactic":{behavior:"feat",levelLabel:"PF2E.Kingmaker.Feature.Tactic"},"army-war-action":{behavior:"activity"},"kingdom-feat":{behavior:"feat"},"kingdom-feature":{behavior:"feature"},"kingdom-activity":{behavior:"activity"}},KINGMAKER_CATEGORY_TYPES=Object.keys(KINGDOM_CATEGORY_DATA),KINGMAKER_CATEGORIES=mapToObj(KINGMAKER_CATEGORY_TYPES,type=>[type,`PF2E.Kingmaker.Feature.Categories.${type}`]);class CampaignFeaturePF2e extends ItemPF2e{static{__name(this,"CampaignFeaturePF2e")}static{__name2(this,"CampaignFeaturePF2e")}granter=null;get category(){return this.system.category}get level(){return this.behavior!=="activity"?this.system.level?.value??0:null}get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isAction(){return this.behavior==="activity"}get isFeature(){return this.behavior==="feature"}get isFeat(){return this.behavior==="feat"}prepareBaseData(){super.prepareBaseData();const categoryData=KINGDOM_CATEGORY_DATA[this.category]??Object.values(KINGDOM_CATEGORY_DATA)[0];this.behavior=categoryData.behavior,this.group=null,this.levelLabel=categoryData.levelLabel??(this.isFeat?"PF2E.Item.Feat.LevelLabel":"PF2E.LevelLabel"),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max)}prepareActorData(){const prefix=this.isFeature?"feature":this.isFeat?"feat":null;if(prefix){const slug=this.slug??sluggify(this.name);this.actor.rollOptions.all[`${prefix}:${slug}`]=!0}}prepareSiblingData(){const itemGrants=this.flags.pf2e.itemGrants;this.grants=Object.values(itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("campaignFeature")?(item.granter=this,[item]):[]})}getRollOptions(prefix=null){return prefix??=this.isFeature?"feature":this.isFeat?"feat":"action",compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isAction?`action:${this.slug}`:null])}async _preCreate(data,options,user){return this.parent||(this.updateSource({"system.location":null}),this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null})),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(typeof changed.system?.location=="string"&&(changed.system.location||=null),normalizeActionChangeData(this,changed),changed.system&&changed.system.category){const system=changed.system,category=tupleHasValue(KINGMAKER_CATEGORY_TYPES,changed.system.category)?changed.system.category:KINGMAKER_CATEGORY_TYPES[0];if(KINGDOM_CATEGORY_DATA[category].behavior==="activity")"level"in this.system&&(system["-=level"]=null);else{const level=system.level?.value??this.system.level?.value??0;system.level={value:level}}}await super._preUpdate(changed,options,user)}}class TrickMagicItemPopup{static{__name(this,"TrickMagicItemPopup")}static{__name2(this,"TrickMagicItemPopup")}item;checkDC;#localize=localizer("PF2E.TrickMagicItemPopup");constructor(item){if(!item.isOfType("consumable"))throw ErrorPF2e("Unexpected item used for Trick Magic Item");if(!item.actor?.isOfType("character"))throw ErrorPF2e(this.#localize("InvalidActor"));this.item=item,this.actor=item.actor,this.checkDC=calculateTrickMagicItemCheckDC(item),this.#initialize()}async#initialize(){const buttons=TRICK_MAGIC_SKILLS.filter(skill=>skill in this.checkDC).map(value=>({value,label:game.i18n.localize(`PF2E.Skill${value.capitalize()}`),modifier:this.actor.skills[value].check.mod})).reduce((accumulated,skill)=>{const button={icon:fontAwesomeIcon("dice-d20").outerHTML,label:`${skill.label} (${skill.modifier<0?"":"+"}${skill.modifier})`,callback:()=>this.#handleTrickItem(skill.value)};return{...accumulated,[skill.value]:button}},{});new Dialog({title:this.#localize("Title"),content:`<p>${this.#localize("Label")}</p>`,buttons},{classes:["dialog","trick-magic-item"],width:"auto"}).render(!0)}#handleTrickItem(skill){this.actor.skills[skill].check.roll({extraRollOptions:["action:trick-magic-item"],dc:{value:this.checkDC[skill]??0},item:this.item});const trick=new TrickMagicItemEntry(this.actor,skill);this.item.castEmbeddedSpell(trick)}}class ConsumablePF2e extends PhysicalItemPF2e{static{__name(this,"ConsumablePF2e")}static{__name2(this,"ConsumablePF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}get category(){return this.system.category}get isAmmo(){return this.category==="ammo"}get uses(){return pick(this.system.uses,["value","max"])}get embeddedSpell(){if(!this.actor)throw ErrorPF2e(`No owning actor found for "${this.name}" (${this.id})`);return this.system.spell?new SpellPF2e(foundry.utils.deepClone(this.system.spell),{parent:this.actor,fromConsumable:!0}):null}prepareBaseData(){if(super.prepareBaseData(),this.system.uses.max||=1,!!this.isAmmo){for(const rule of this.system.rules)if(rule.key==="RollOption"&&"toggleable"in rule&&rule.toggleable){console.warn("Toggleable RollOption rule elements may not be added to ammunition"),this.system.rules=[];break}else if(["GrantItem","ChoiceSet"].includes(String(rule.key))){console.warn(`${rule.key} rule elements may not be added to ammunition`),this.system.rules=[];break}}}prepareRuleElements(){const rules=super.prepareRuleElements();for(const rule of rules)rule.ignored=!0;return rules}async getChatData(htmlOptions={},rollOptions={}){const traits=this.traitChatData(CONFIG.PF2E.consumableTraits),[category,isUsable]=this.isIdentified?[game.i18n.localize(CONFIG.PF2E.consumableCategories[this.category]),!0]:[this.generateUnidentifiedName({typeOnly:!0}),!["other","scroll","talisman","toolkit","wand"].includes(this.category)],usesLabel=game.i18n.localize("PF2E.Item.Consumable.Uses.Label"),fromFormula=!!rollOptions.fromFormula;return this.processChatData(htmlOptions,{...await super.getChatData(),traits,properties:this.isIdentified&&this.uses.max>1?[`${this.uses.value}/${this.uses.max} ${usesLabel}`]:[],category,isUsable:fromFormula?!1:isUsable})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const liquidOrSubstance=__name2(()=>this.traits.has("inhaled")||this.traits.has("contact")?"PF2E.identification.UnidentifiedType.Substance":"PF2E.identification.UnidentifiedType.Liquid","liquidOrSubstance"),itemType=game.i18n.localize(["drug","elixir","mutagen","oil","poison","potion"].includes(this.category)?liquidOrSubstance():["scroll","snare","ammo"].includes(this.category)?CONFIG.PF2E.consumableCategories[this.category]:"PF2E.identification.UnidentifiedType.Object");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),...Object.entries({[`category:${this.category}`]:!0}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`)]}isAmmoFor(weapon){if(!this.isAmmo)return!1;if(!weapon.isOfType("weapon"))return console.warn("Cannot load a consumable into a non-weapon"),!1;const{max}=this.uses;return weapon.system.traits.value.includes("repeating")?max>1:max<=1}async consume(){const{actor}=this;if(!actor)return;const{value,max}=this.uses;if(["scroll","wand"].includes(this.category)&&this.system.spell)if(actor.spellcasting.canCastConsumable(this))this.castEmbeddedSpell();else if(actor.itemTypes.feat.some(feat=>feat.slug==="trick-magic-item"))new TrickMagicItemPopup(this);else{const formatParams={actor:actor.name,spell:this.name},message=game.i18n.format("PF2E.LackCastConsumableCapability",formatParams);ui.notifications.warn(message);return}else if(this.category!=="ammo"){const key=max>1&&value===1?"UseExhausted":max>1?"UseMulti":"UseSingle",content=game.i18n.format(`PF2E.ConsumableMessage.${key}`,{name:this.name,current:value-1}),flags={pf2e:{origin:{sourceId:this.flags.core?.sourceId,uuid:this.uuid,type:this.type}}},speaker=ChatMessage.getSpeaker({actor});if(this.system.damage){const{formula,type,kind}=this.system.damage;new DamageRoll(`(${formula})[${type},${kind}]`).toMessage({speaker,flavor:content,flags})}else ChatMessage.create({speaker,content,flags})}if(this.system.uses.autoDestroy&&value<=1){const{quantity}=this,isPreservedAmmo=this.category==="ammo"&&this.system.rules.length>0;quantity<=1&&!isPreservedAmmo?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.uses.value":max})}else await this.update({"system.uses.value":Math.max(value-1,0)})}async castEmbeddedSpell(trickMagicItemData){const{actor}=this,spell=this.embeddedSpell;if(!actor||!spell)return;const entry=(()=>trickMagicItemData||actor.spellcasting.filter(e=>e instanceof SpellcastingEntryPF2e&&e.canCast(spell,{origin:this})).reduce((previous,current)=>{const previousDC=previous.statistic.dc.value;return current.statistic.dc.value>previousDC?current:previous}))();if(entry){const systemData=spell.system;entry instanceof SpellcastingEntryPF2e&&(systemData.location.value=entry.id),entry.cast(spell,{consume:!1})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(typeof changed.system.damage?.type=="string"){const category=changed.system.category??this.system.category;setHasElement(DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES,category)?(setHasElement(DAMAGE_ONLY_CONSUMABLE_CATEGORIES,category)||!["vitality","void","untyped"].includes(changed.system.damage.type))&&(changed.system.damage.kind="damage"):changed.system.damage=null}if(changed.system.uses){if("value"in changed.system.uses){const minimum=this.system.uses.autoDestroy?1:0;changed.system.uses.value=Math.clamped(Math.floor(Number(changed.system.uses.value))||minimum,minimum,9999)}"max"in changed.system.uses&&(changed.system.uses.max=Math.clamped(Math.floor(Number(changed.system.uses.max))||1,1,9999)),typeof changed.system.uses.value=="number"&&typeof changed.system.uses.max=="number"&&(changed.system.uses.value=Math.min(changed.system.uses.value,changed.system.uses.max))}return changed.system.price?.per!==void 0&&(changed.system.price.per=Math.clamped(Math.floor(Number(changed.system.price.per))||1,1,999)),super._preUpdate(changed,options,user)}}class DeityPF2e extends ItemPF2e{static{__name(this,"DeityPF2e")}static{__name2(this,"DeityPF2e")}get category(){return this.system.category}get favoredWeapons(){return[...this.system.weapons]}prepareBaseData(){super.prepareBaseData(),this.system.sanctification?.modal||(this.system.sanctification=null),this.category==="philosophy"&&(this.system.attribute=[],this.system.domains={primary:[],alternate:[]},this.system.font=[],this.system.sanctification=null,this.system.skill=null,this.system.spells={},this.system.weapons=[])}prepareActorData(){if(!this.actor.isOfType("character")){this.delete({render:!1});return}this.actor.deity=this;const{deities}=this.actor.system.details,systemData=this.system;deities.primary={skill:foundry.utils.deepClone(systemData.skill),weapons:foundry.utils.deepClone(systemData.weapons)};for(const domain of this.system.domains.primary){const label=CONFIG.PF2E.deityDomains[domain]?.label;deities.domains[domain]=label??domain;const apocryphaKey=`${domain}-apocryphal`;if(objectHasKey(CONFIG.PF2E.deityDomains,apocryphaKey)){const apocrypha=CONFIG.PF2E.deityDomains[apocryphaKey];deities.domains[apocryphaKey]=apocrypha.label}}const slug=this.slug??sluggify(this.name),prefix="deity:primary",actorRollOptions=this.actor.rollOptions;actorRollOptions.all.deity=!0,actorRollOptions.all[`${prefix}:${slug}`]=!0;const sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);for(const option of sanctifications)actorRollOptions.all[option]=!0;for(const baseType of this.favoredWeapons)actorRollOptions.all[`${prefix}:favored-weapon:${baseType}`]=!0;actorRollOptions.all[`self:deity:slug:${slug}`]=!0}setFavoredWeaponRank(){if(!this.actor.isOfType("character"))return;const favoredWeaponRank=this.actor.flags.pf2e.favoredWeaponRank;if(favoredWeaponRank>0){const attacks=this.actor.system.proficiencies.attacks,baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes;for(const baseType of this.favoredWeapons)attacks[`weapon-base-${baseType}`]={label:baseWeaponTypes2[baseType]??baseShieldTypes2[baseType]??baseType,rank:Math.max(Number(attacks[`weapon-base-${baseType}`]?.rank)||0,favoredWeaponRank)}}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);return[...baseOptions,`${prefix}:category:${this.category}`,...sanctifications].sort()}getSanctificationRollOptions(){const{sanctification}=this.system,modal=sanctification?.modal;return sanctification?.modal&&sanctification.what.length>0?sanctification.what.map(s=>`sanctification:${modal}:${s}`):["sanctification:none"]}}function featCanHaveKeyOptions(feat){if(feat.category!=="classfeature"||feat.level!==1||feat.traits.size>1)return!1;const{grantedBy}=feat;return!grantedBy||grantedBy.isOfType("feat")&&grantedBy.category==="classfeature"}__name(featCanHaveKeyOptions,"featCanHaveKeyOptions"),__name2(featCanHaveKeyOptions,"featCanHaveKeyOptions");class FeatPF2e extends ItemPF2e{static{__name(this,"FeatPF2e")}static{__name2(this,"FeatPF2e")}get category(){return this.system.category}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isFeature(){return setHasElement(FEATURE_CATEGORIES,this.category)}get isFeat(){return setHasElement(FEAT_CATEGORIES,this.category)}get onlyLevel1(){return this.system.onlyLevel1}get maxTakable(){return this.system.maxTakable}prepareBaseData(){super.prepareBaseData(),this.group=null,this.system.level.taken??=null,this.system.location||=null;const traits=this.system.traits.value;this.category==="general"&&!traits.includes("general")&&traits.push("general"),this.category==="skill"&&(traits.includes("skill")||traits.push("skill"),!traits.includes("general")&&!traits.includes("archetype")&&traits.push("general")),traits.includes("dedication")&&(this.system.category="class",traits.includes("archetype")||traits.push("archetype")),this.system.traits.value.includes("lineage")&&(this.system.onlyLevel1=!0),this.system.maxTakable??=1/0,this.system.onlyLevel1&&(this.system.maxTakable=1),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.subfeatures=foundry.utils.mergeObject({keyOptions:[]},this.system.subfeatures??{}),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null)}prepareActorData(){const{actor}=this,prefix=this.isFeature?"feature":"feat",slug=this.slug??sluggify(this.name);actor.rollOptions.all[`${prefix}:${slug}`]=!0;const{subfeatures}=this.system;featCanHaveKeyOptions(this)||(subfeatures.keyOptions=[]),actor.isOfType("character")&&subfeatures.keyOptions.length>0&&(actor.system.build.attributes.keyOptions=uniq([...actor.system.build.attributes.keyOptions,...subfeatures.keyOptions]))}prepareSiblingData(){this.grants=Object.values(this.flags.pf2e.itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("feat")&&!item.system.location||item?.isOfType("heritage")?[item]:[]});for(const grant of this.grants.filter(g=>g.isOfType("feat")))grant.system.level.taken=this.system.level.taken}onPrepareSynthetics(){processSanctification(this)}async getChatData(htmlOptions={}){const levelLabel=game.i18n.format("PF2E.LevelN",{level:this.level}),actionTypeLabel=getActionTypeLabel(this.actionCost?.type,this.actionCost?.value),properties=actionTypeLabel?[levelLabel,actionTypeLabel]:[levelLabel],traits=this.traitChatData(CONFIG.PF2E.featTraits);return this.processChatData(htmlOptions,{...this.system,properties,traits})}getRollOptions(prefix="feat"){return prefix=prefix==="feat"&&this.isFeature?"feature":prefix,compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isFeat?`${prefix}:rarity:${this.rarity}`:null,this.frequency?`${prefix}:frequency:limited`:null])}async _preCreate(data,options,user){return this.parent||(this._source.system.location=null,delete this._source.system.level.taken,this._source.system.frequency&&delete this._source.system.frequency.value),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);"location"in changed.system&&(changed.system.location||=null),typeof changed.system.level?.value=="number"&&changed.system.level.value!==1&&(changed.system.onlyLevel1=!1),normalizeActionChangeData(this,changed);const traits=changed.system.traits?.value;return setHasElement(FEATURE_CATEGORIES,changed.system.category??this.category)?(changed.system.onlyLevel1=!1,changed.system.maxTakable=1,this.category!=="ancestry"&&Array.isArray(traits)&&traits.findSplice(t=>t==="lineage")):(Array.isArray(traits)&&traits.includes("lineage")||changed.system?.onlyLevel1)&&foundry.utils.mergeObject(changed,{system:{maxTakable:1}}),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.isOwner&&this.actor?.isOfType("character")&&this.isFeat))return;const actorItemNames={actor:this.actor.name,item:this.name};if(this.onlyLevel1&&this.actor.level>1){const formatParams={...actorItemNames,actorLevel:this.actor.level},warning=game.i18n.format("PF2E.Item.Feat.Warning.TakenAfterLevel1",formatParams);ui.notifications.warn(warning)}if(this.flags.pf2e.grantedBy)return;const slug=this.slug??sluggify(this.name),timesTaken=this.actor.itemTypes.feat.filter(f=>f.slug===slug).length,{maxTakable}=this;if(maxTakable===1&×Taken>1)ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanOnce",actorItemNames));else if(timesTaken>maxTakable){const formatParams={...actorItemNames,maxTakable,timesTaken};ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanMax",formatParams))}}}class HeritagePF2e extends ItemPF2e{static{__name(this,"HeritagePF2e")}static{__name2(this,"HeritagePF2e")}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get isVersatile(){return!this.system.ancestry}prepareActorData(){if(!this.actor.isOfType("character"))throw ErrorPF2e("heritage embedded on non-character");const slug=this.slug??sluggify(this.name);(this.actor.itemTypes.heritage.length===1||!this.grantedBy)&&(this.actor.heritage=this,this.actor.system.details.heritage={name:this.name,trait:slug in CONFIG.PF2E.ancestryTraits?slug:null}),this.actor.system.traits.value.push(...this.traits),this.isVersatile&&this.actor.system.details.ancestry?.countsAs.push(slug),this.actor.rollOptions.all[`heritage:${slug}`]=!0,this.actor.rollOptions.all[`self:heritage:${slug}`]=!0}getRollOptions(prefix=this.type){const ancestryOrVersatile=this.system.ancestry?`ancestry:${this.system.ancestry.slug}`:"versatile";return[...super.getRollOptions(prefix),`${prefix}:${ancestryOrVersatile}`]}}class KitPF2e extends ItemPF2e{static{__name(this,"KitPF2e")}static{__name2(this,"KitPF2e")}get entries(){return Object.values(this.system.items)}get price(){return{value:new CoinsPF2e(this.system.price.value),per:this.system.price.per??1}}async createGrantedItems(options={}){const size=new ActorSizePF2e({value:options.size??"med",smallIsMedium:!0}).value,entries=options.entries??this.entries,itemUUIDs=entries.map(e=>e.uuid),items=await UUIDUtils.fromUUIDs(itemUUIDs);if(entries.length!==items.length)throw ErrorPF2e(`Some items from ${this.name} were not found`);return items.every(i=>i instanceof ItemPF2e&&!i.parent)?items.reduce(async(promise,item,index)=>{const prepared=await promise,clone=item.clone({_id:foundry.utils.randomID(),system:{size}},{keepId:!0}),entry=entries[index];if(clone.isOfType("physical")&&clone.updateSource({"system.quantity":entry.quantity,"system.containerId":options.containerId}),clone.isOfType("backpack")&&entry.items){const contents=await this.createGrantedItems({entries:Object.values(entry.items),containerId:clone.id,size});prepared.push(clone,...contents)}else if(clone instanceof KitPF2e){const inflatedKit=await clone.createGrantedItems({containerId:options.containerId,size});prepared.push(...inflatedKit)}else clone instanceof PhysicalItemPF2e&&prepared.push(clone);return prepared},[]):[]}async _preUpdate(changed,options,user){if(!changed.system)return await super._preUpdate(changed,options,user);if(isObject(changed.system.price)){const price=changed.system.price;for(const denomination of DENOMINATIONS)price[denomination]===0&&(price["-=denomination"]=null)}return super._preUpdate(changed,options,user)}}class LorePF2e extends ItemPF2e{static{__name(this,"LorePF2e")}static{__name2(this,"LorePF2e")}}class LoreSheetPF2e extends ItemSheetPF2e{static{__name(this,"LoreSheetPF2e")}static{__name2(this,"LoreSheetPF2e")}}class DicePF2e{static{__name(this,"DicePF2e")}static{__name2(this,"DicePF2e")}_rolled;terms;static async d20Roll({event:event2,item=null,parts,data,template,title,speaker,flavor,onClose,dialogOptions,rollMode=game.settings.get("core","rollMode"),rollType=""}){const userSettingQuickD20Roll=!game.user.settings.showCheckDialogs,_roll=__name2(async(rollParts,adv,$form)=>{let flav=flavor instanceof Function?flavor(rollParts,data):title;adv===1?(rollParts[0]=["2d20kh"],flav=game.i18n.format("PF2E.Roll.FortuneTitle",{title})):adv===-1&&(rollParts[0]=["2d20kl"],flav=game.i18n.format("PF2E.Roll.MisfortuneTitle",{title})),$form&&(data.itemBonus=$form.find("[name=itemBonus]").val()),(!data.itemBonus||data.itemBonus===0)&&rollParts.indexOf("@itemBonus")!==-1&&rollParts.splice(rollParts.indexOf("@itemBonus"),1),$form&&(data.statusBonus=$form.find("[name=statusBonus]").val()),(!data.statusBonus||data.statusBonus===0)&&rollParts.indexOf("@statusBonus")!==-1&&rollParts.splice(rollParts.indexOf("@statusBonus"),1),$form&&(data.circumstanceBonus=$form.find("[name=circumstanceBonus]").val()),(!data.circumstanceBonus||data.circumstanceBonus===0)&&rollParts.indexOf("@circumstanceBonus")!==-1&&rollParts.splice(rollParts.indexOf("@circumstanceBonus"),1);const roll=await new Roll(rollParts.join("+"),data).roll({async:!0}),origin=item?{uuid:item.uuid,type:item.type}:null;return roll.toMessage({speaker,flavor:flav,flags:{pf2e:{context:{type:rollType},origin}}},{rollMode:$form?$form.find("[name=rollMode]").val():rollMode}),roll},"_roll");if(parts.unshift("1d20"),userSettingQuickD20Roll&&!event2.altKey&&!(event2.ctrlKey||event2.metaKey)&&!event2.shiftKey||!userSettingQuickD20Roll&&event2.shiftKey)return _roll(parts,0);if(event2.ctrlKey||event2.metaKey)return rollMode="blindroll",_roll(parts,0);if(event2.shiftKey||!userSettingQuickD20Roll){parts.indexOf("@circumstanceBonus")===-1&&(parts=parts.concat(["@circumstanceBonus"])),parts.indexOf("@itemBonus")===-1&&(parts=parts.concat(["@itemBonus"])),parts.indexOf("@statusBonus")===-1&&(parts=parts.concat(["@statusBonus"])),template=template||"systems/pf2e/templates/chat/roll-dialog.hbs";const dialogData={data,rollMode,formula:parts.join(" + "),rollModes:CONFIG.Dice.rollModes},content=await renderTemplate(template,dialogData);let roll;return new Promise(resolve=>{new Dialog({title,content,buttons:{advantage:{label:game.i18n.localize("PF2E.Roll.Fortune"),callback:async html=>{roll=await _roll(parts,1,html)}},normal:{label:game.i18n.localize("PF2E.Roll.Normal"),callback:async html=>{roll=await _roll(parts,0,html)}},disadvantage:{label:game.i18n.localize("PF2E.Roll.Misfortune"),callback:async html=>{roll=await _roll(parts,-1,html)}}},default:game.i18n.localize("PF2E.Roll.Normal"),close:html=>{onClose&&onClose(html,parts,data),resolve(roll)}},dialogOptions).render(!0)})}else return _roll(parts,0)}alter(add2,multiply){const rgx=new RegExp(DiceTerm.REGEXP,"g");if(this._rolled)throw ErrorPF2e("You may not alter a Roll which has already been rolled");return this.terms=this.terms?.map(t=>t.replace(rgx,(_match,nd,d,mods)=>(nd=nd*(multiply||1)+(add2||0),mods=mods||"",`${nd}d${d}${mods}`))),this}}function simplifyFormula(formula){if(formula==="0")return formula;const fixedFormula=formula.replace(/^\s*-\s+/,"-").replace(/\s*\+\s*-\s*/g," - "),roll=new Roll(fixedFormula);if(!roll.terms.every(t=>[" - "," + "].includes(t.expression)||t instanceof Die||t instanceof NumericTerm))return fixedFormula;const terms=parseTermsFromSimpleFormula(roll);return createSimpleFormula(terms)}__name(simplifyFormula,"simplifyFormula"),__name2(simplifyFormula,"simplifyFormula");class MeleePF2e extends ItemPF2e{static{__name(this,"MeleePF2e")}static{__name2(this,"MeleePF2e")}get traits(){return new Set(this.system.traits.value)}get isMelee(){return this.system.weaponType.value==="melee"}get isRanged(){return this.system.weaponType.value==="ranged"}get isThrown(){return this.isRanged&&this.system.traits.value.some(t=>t.startsWith("thrown"))}get defaultAttribute(){const{traits}=this;return this.isMelee?traits.has("finesse")?"dex":"str":traits.has("brutal")?"str":"dex"}get attackModifier(){return Number(this.system.bonus.value)||0}get reach(){if(this.isRanged)return null;const reachTrait=this.system.traits.value.find(t=>/^reach-\d+$/.test(t));return reachTrait?Number(reachTrait.replace("reach-","")):SIZE_TO_REACH[this.actor?.size??"med"]}get range(){if(this.isMelee)return null;const specifiedMaxRange=(()=>{const rangeTrait=this.system.traits.value.find(t=>/^range-\d+$/.test(t)),range2=Number(rangeTrait?.replace(/\D/g,"")||"NaN");return Number.isInteger(range2)?range2:null})(),rangeIncrement=(()=>{if(specifiedMaxRange)return null;const incrementTrait=this.system.traits.value.find(t=>/^(?:range-increment|thrown)-\d+$/.test(t));return Number(incrementTrait?.replace(/\D/g,""))||10})();return specifiedMaxRange?{increment:null,max:specifiedMaxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get baseDamage(){const partials=Object.values(this.system.damageRolls),instance=partials.find(p=>!p.category)??partials.at(0);return instance?WeaponDamagePF2e.npcDamageToWeaponDamage(instance):{dice:0,die:null,modifier:0,damageType:"untyped",persistent:null,category:null}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||!!baseDamage.persistent?.number||Object.values(this.system.damageRolls).some(d=>d.category==="splash")}get attackEffects(){return this.system.attackEffects.value}get isMagical(){const{traits}=this;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get linkedWeapon(){const item=this.actor?.items.get(this.flags.pf2e.linkedWeapon??"");return item?.isOfType("weapon")?item:null}_initialize(options){this.category=this.group=this.baseType=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits),this.system.material={type:null,grade:null,effects:[]},this.system.runes={property:[]};for(const attackDamage of Object.values(this.system.damageRolls))attackDamage.category||=null,attackDamage.damageType==="bleed"&&(attackDamage.category="persistent")}prepareSiblingData(){const{linkedWeapon}=this,isUnarmed=this.traits.has("unarmed");this.category=isUnarmed?"unarmed":linkedWeapon?.category??null,this.group=isUnarmed?"brawling":this.linkedWeapon?.group??null,this.baseType=tupleHasValue(["claw","fist","jaws"],this.slug)?this.slug:this.linkedWeapon?.baseType??null}prepareActorData(){if(!this.actor?.isOfType("npc"))return;const damageInstances=Object.values(this.system.damageRolls);for(const instance of Object.values(this.system.damageRolls)){try{instance.damage=new Roll(instance.damage)._formula}catch{const message=`Unable to parse damage formula on NPC attack ${this.name}`;console.warn(`PF2e System | ${message}`),instance.damage="1d4"}const{isElite,isWeak}=this.actor;if((isElite||isWeak)&&damageInstances.indexOf(instance)===0){const adjustment=isElite?2:-2;instance.damage=simplifyFormula(`${instance.damage} + ${adjustment}`)}else instance.damage=new Roll(instance.damage)._formula}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),{damageType}=this.baseDamage,damageCategory=DamageCategorization.fromDamageType(damageType),rangeIncrement=this.range?.increment,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),otherOptions=Object.entries({equipped:!0,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,[`category:${this.category}`]:!!this.category,[`group:${this.group}`]:!!this.group,[`base:${this.baseType}`]:!!this.baseType,[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`damage:type:${damageType}`]:!0,[`damage:category:${damageCategory}`]:!!damageCategory,...propertyRunes}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`);return[baseOptions,otherOptions].flat().sort()}async toMessage(_event,{create=!0}={}){if(!create)return;const strike=this.actor?.system.actions?.find(s=>s.item===this);return strike?game.pf2e.rollActionMacro({itemId:this.id,slug:strike.slug}):void 0}}function setActorShieldData(shield){const{actor}=shield;if(!(shield.isEquipped&&actor.heldShield===shield)||!actor.isOfType("character","npc"))return;const{attributes}=actor.system;if(![shield.id,null].includes(attributes.shield.itemId))return;const{hitPoints}=shield;attributes.shield={itemId:shield.id,name:shield.name,ac:shield.acBonus,hp:hitPoints,hardness:shield.hardness,brokenThreshold:hitPoints.brokenThreshold,raised:shield.isRaised,broken:shield.isBroken,destroyed:shield.isDestroyed,icon:shield.img},actor.rollOptions.all["self:shield:equipped"]=!0,shield.isDestroyed?actor.rollOptions.all["self:shield:destroyed"]=!0:shield.isBroken&&(actor.rollOptions.all["self:shield:broken"]=!0)}__name(setActorShieldData,"setActorShieldData"),__name2(setActorShieldData,"setActorShieldData");class ShieldPF2e extends PhysicalItemPF2e{static{__name(this,"ShieldPF2e")}static{__name2(this,"ShieldPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem??null}get isBuckler(){return["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"].includes(this.system.baseItem??"")}get isTowerShield(){return["fortress-shield","tower-shield"].includes(this.system.baseItem??"")}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}get isRaised(){return!!this.actor?.isOfType("character","npc")&&this.id===this.actor.attributes.shield.itemId&&this.actor.attributes.shield.raised}getRollOptions(prefix="armor"){const reinforcingRune=this.system.runes.reinforcing,reinforcingSlug=[null,"minor","lesser","moderate","greater","major","supreme"][reinforcingRune],reinforcingOptions={[`rune:reinforcing:${reinforcingRune}`]:!!reinforcingRune,[`rune:reinforcing:${reinforcingSlug}`]:!!reinforcingRune},rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`base:${this.baseType}`]:!!this.baseType,...reinforcingOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"held-in-one-hand"},super.prepareBaseData(),"category"in this.system&&(this.type="shield",this.system.runes={reinforcing:0}),this.system.traits.integrated&&(this.system.traits.integrated.runes=foundry.utils.mergeObject({potency:0,striking:0,property:[]},this.system.traits.integrated.runes));const materialData=getMaterialValuationData(this),reinforcingRune=this.system.runes.reinforcing,adjustFromMaterialAndRune=__name2((property,base)=>{const fromMaterial=this.isSpecific?Math.max(base,materialData?.[property]??base):materialData?.[property]??base,additionalFromRune=reinforcingRune?RUNE_DATA.shield.reinforcing[reinforcingRune]?.[property]:null,sumFromRune=fromMaterial+(additionalFromRune?.increase??0);return additionalFromRune&&sumFromRune>additionalFromRune.max?Math.max(fromMaterial,additionalFromRune.max):sumFromRune},"adjustFromMaterialAndRune");this.system.hardness=adjustFromMaterialAndRune("hardness",this.system.hardness),this.system.hp.max=adjustFromMaterialAndRune("maxHP",this.system.hp.max),this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2);const baseTraits=this.system.traits.value,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=this.system.runes.reinforcing>0&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()).filter(t=>t in CONFIG.PF2E.shieldTraits);const integratedTrait=this.system.traits.value.find(t=>t.startsWith("integrated"));if(integratedTrait){const isVersatileWeapon=integratedTrait.includes("versatile"),traitParts=integratedTrait.split("-"),damageTypeMap={b:"bludgeoning",p:"piercing",s:"slashing"},mainDamageType=damageTypeMap[traitParts.at(2)??""]??"slashing",versatileDamageType=isVersatileWeapon?damageTypeMap[traitParts.at(-1)??""]:null;this.system.traits.integrated&&versatileDamageType?(this.system.traits.integrated.versatile=foundry.utils.mergeObject({options:[mainDamageType,versatileDamageType],selection:mainDamageType},this.system.traits.integrated.versatile??{}),this.system.traits.integrated.versatile.options):this.system.traits.integrated&&(this.system.traits.integrated.versatile=null),this.system.traits.integrated=foundry.utils.mergeObject({damageType:mainDamageType,runes:{potency:0,striking:0,property:[]},versatile:null},this.system.traits.integrated??{})}else this.system.traits.integrated=null}prepareDerivedData(){super.prepareDerivedData(),this.system.acBonus=this.isBroken||this.isDestroyed?0:this.acBonus}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");setActorShieldData(this)}onPrepareSynthetics(){super.onPrepareSynthetics(),setActorShieldData(this)}async getChatData(htmlOptions={}){const properties=[`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.shieldTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseShieldTypes[this.baseType]:null,fallback="TYPES.Item.shield",itemType=game.i18n.localize(base??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}generateWeapon(){if(this.isStowed)return null;const shieldThrowTrait=this.system.traits.value.find(t=>t.startsWith("shield-throw-")),baseData=foundry.utils.deepClone({...pick(this,["_id","name","img"]),type:"weapon",system:{category:"martial",group:"shield",baseItem:this.baseType,equipped:{...this._source.system.equipped,invested:null},hp:pick(this.system.hp,["value","max"]),material:omit(this.material,["effects"]),traits:{rarity:this.rarity,value:shieldThrowTrait?[`thrown-${shieldThrowTrait.slice(-2)}`]:[],otherTags:[]},damage:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0,persistent:null}}});if(this.system.traits.integrated){const damageType=this.system.traits.integrated.damageType,versatileTrait=this.system.traits.value.find(t=>t.includes("versatile")),versatileWeaponTrait=versatileTrait?.slice(versatileTrait.indexOf("versatile"))??null;objectHasKey(CONFIG.PF2E.weaponTraits,versatileWeaponTrait)&&(baseData.system.traits.value.push(versatileWeaponTrait),baseData.system.traits.toggles={versatile:{selection:this.system.traits.integrated.versatile?.selection??damageType}});const integratedWeaponRunes=this.system.traits.integrated?.runes,additionalData={system:{damage:{dice:1,die:"d6",damageType,modifier:0,persistent:null},runes:integratedWeaponRunes}};(integratedWeaponRunes?.potency||integratedWeaponRunes?.striking)&&(additionalData.name=this._source.name);const combinedData=foundry.utils.mergeObject(baseData,additionalData);return new ItemProxyPF2e(combinedData,{parent:this.parent,shield:this})}return new ItemProxyPF2e(baseData,{parent:this.parent,shield:this})}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return this._source.system.traits.value.some(t=>t.startsWith("integrated-"))&&!!changed.system.traits?.value&&Array.isArray(changed.system.traits.value)&&!changed.system.traits.value.some(t=>t.startsWith("integrated-"))&&changed.system?.traits&&(changed.system.traits.integrated=null),super._preUpdate(changed,options,user)}}function createSpellRankLabel(spell,castRank){const typeLabel=spell.isCantrip?game.i18n.localize("PF2E.TraitCantrip"):spell.isFocusSpell?game.i18n.localize("PF2E.TraitFocus"):spell.isRitual?game.i18n.localize("PF2E.Item.Spell.Ritual.Label"):game.i18n.localize("TYPES.Item.spell");return castRank?game.i18n.format("PF2E.ItemLevel",{type:typeLabel,level:castRank}):typeLabel}__name(createSpellRankLabel,"createSpellRankLabel"),__name2(createSpellRankLabel,"createSpellRankLabel");async function createDescriptionPrepend(spell,{includeTraditions}){const traditions=includeTraditions?spell.system.traits.traditions.map(t=>game.i18n.localize(CONFIG.PF2E.magicTraditions[t]).toLocaleLowerCase(game.i18n.lang)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", "):null,templatePath="systems/pf2e/templates/items/partials/spell-description-prepend.hbs",rendered=(await renderTemplate(templatePath,{spell,traditions})).trim();return rendered?`${rendered}
|
|
<hr />`:""}__name(createDescriptionPrepend,"createDescriptionPrepend"),__name2(createDescriptionPrepend,"createDescriptionPrepend");class SpellOverlayCollection extends Collection{static{__name(this,"SpellOverlayCollection")}static{__name2(this,"SpellOverlayCollection")}constructor(spell,entries){super(Object.entries(entries??{})),this.spell=spell}get overrideVariants(){return[...this.entries()].reduce((result,[overlayId,data])=>{if(data.overlayType==="override"){const spell=this.spell.loadVariant({overlayIds:[overlayId]});if(spell)return[...result,spell]}return result},[])}getType(overlayId){return this.get(overlayId,{strict:!0}).overlayType}async create(overlayType,options={renderSheet:!1}){const id=foundry.utils.randomID();switch(overlayType){case"override":if(await this.spell.update({[`system.overlays.${id}`]:{_id:id,sort:this.overrideVariants.length+1,overlayType:"override",system:{}}}),options.renderSheet){const variantSpell=this.spell.loadVariant({overlayIds:[id]});variantSpell&&variantSpell.sheet.render(!0)}break}}async updateOverride(variantSpell,data,options){const variantId=variantSpell.variantId;if(!variantId)return null;variantSpell.updateSource(data,options);const variantSource=variantSpell.toObject(),originSource=this.spell.toObject(),difference2=foundry.utils.diffObject(originSource,variantSource);return Object.keys(difference2).length===0||(delete difference2.system?.description,difference2.overlayType="override",await this.spell.update({[`system.overlays.-=${variantId}`]:null},{render:!1}),await this.spell.update({[`system.overlays.${variantId}`]:difference2}),variantSpell.sheet.rendered&&variantSpell.sheet.render(!0)),variantSpell}async deleteOverlay(overlayId){this.verifyOverlayId(overlayId),await this.spell.update({[`system.overlays.-=${overlayId}`]:null}),this.delete(overlayId)}verifyOverlayId(overlayId){if(!this.has(overlayId))throw ErrorPF2e(`Spell ${this.spell.name} (${this.spell.uuid}) does not have an overlay with id: ${overlayId}`)}}class SpellPF2e extends ItemPF2e{static{__name(this,"SpellPF2e")}static{__name2(this,"SpellPF2e")}isFromConsumable;trickMagicEntry=null;constructor(data,context={}){super(data,context),this.isFromConsumable=!!context.fromConsumable}get variantId(){return this.original?this.appliedOverlays?.get("override")??null:null}get baseRank(){return this.system.level.value}get baseLevel(){return this.baseRank}get rank(){if(!this.actor)return this.baseRank;const isAutoHeightened=this.isCantrip||this.isFocusSpell,fixedHeightenedRank=this.system.location.autoHeightenLevel||this.spellcasting?.system?.autoHeightenLevel.value||null;return(isAutoHeightened?fixedHeightenedRank||Math.ceil(this.actor.level/2)||null:this.system.location.heightenedLevel||null)||this.baseRank}get level(){return this.rank}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get traditions(){return new Set(this.system.traits.traditions)}get actionGlyph(){return this.isRitual?null:getActionGlyph(this.system.time.value)||null}get spellcasting(){const spellcastingId=this.system.location.value;return this.trickMagicEntry?this.trickMagicEntry:this.actor?.spellcasting.get(spellcastingId??"")??null}get isAttack(){return this.traits.has("attack")}get isCantrip(){return this.traits.has("cantrip")&&!this.isRitual}get isFocusSpell(){return this.traits.has("focus")}get isRitual(){return!!this.system.ritual}get attribute(){return this.spellcasting?.attribute??"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellPF2e#ability` is deprecated. Use `SpellPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get unlimited(){return this.isCantrip}get isVariant(){return!!this.original}get hasVariants(){return this.overlays.size>0}get area(){if(!this.system.area)return null;const size=Number(this.system.area.value),unit=game.i18n.localize("PF2E.Foot"),shape=game.i18n.localize(CONFIG.PF2E.areaTypes[this.system.area.type]),label=game.i18n.format("PF2E.Item.Spell.Area",{size,unit,shape});return{...this.system.area,label}}get range(){return null}get damageKinds(){return new Set(Object.values(this.system.damage).flatMap(d=>Array.from(d.kinds)))}get uuid(){return this.isVariant?this.original?.uuid??super.uuid:super.uuid}computeCastRank(slotRank){return(this.isCantrip||this.isFocusSpell)&&this.actor?this.rank:Math.max(this.baseRank,slotRank??this.rank)}getRollData(rollOptions={}){const spellLevel=Number(rollOptions?.castLevel)||null,castLevel=Math.max(this.baseRank,spellLevel||this.rank);if(spellLevel&&castLevel!==this.rank)return this.clone({"system.location.heightenedLevel":castLevel}).getRollData();const rollData=super.getRollData();return this.actor?.isOfType("character","npc")&&(rollData.mod=this.actor.abilities[this.attribute].mod),rollData.castLevel=castLevel,rollData.heighten=Math.max(0,castLevel-this.baseRank),rollData}async getDamage(params={skipDialog:!0}){const{spellcasting}=this;if(!Object.keys(this.system.damage).length||!this.actor||!spellcasting?.statistic)return null;const castLevel=this.rank,rollData=this.getRollData({castLevel}),base=[];for(const[id,damage]of Object.entries(this.system.damage??{})){if(!DamageRoll.validate(damage.formula))return console.error(`Failed to parse damage formula "${damage.formula}"`),null;const terms=parseTermsFromSimpleFormula(damage.formula,{rollData}),heightening=this.system.heightening;if(heightening?.type==="interval"&&heightening.interval){const scalingFormula=heightening.damage[id],partCount=Math.floor((castLevel-this.baseRank)/heightening.interval);if(scalingFormula&&partCount>0){const scalingTerms=parseTermsFromSimpleFormula(scalingFormula,{rollData});for(let i=0;i<partCount;i++)terms.push(...foundry.utils.deepClone(scalingTerms))}}if(terms.length>0&&!base.length&&this.actor.isOfType("npc")&&this.actor.attributes.adjustment){const value=this.unlimited?2:4;terms.push({dice:null,modifier:this.actor.isElite?value:-value})}const damageType=damage.type,category=damage.category||null,materials=damage.materials;base.push({terms:combinePartialTerms(terms),damageType,category,materials})}if(!base.length)return null;const{attribute,isAttack}=this,checkStatistic=spellcasting.statistic,spellTraits2=uniq(compact([...this.traits,spellcasting.tradition])),damageKinds=Array.from(this.damageKinds),domains=compact([damageKinds,damageKinds.map(k=>`spell-${k}`),damageKinds.map(k=>`${this.id}-${k}`),isAttack?["attack-damage","attack-spell-damage"]:null,checkStatistic.base?damageKinds.map(k=>`${checkStatistic.base?.slug}-${k}`):null].flat()),contextData=await this.actor.getDamageRollContext({target:isAttack?params.target:null,item:this,statistic:checkStatistic.check,domains,options:new Set(["action:cast-a-spell","self:action:slug:cast-a-spell",...spellTraits2]),checkContext:null,outcome:null,traits:spellTraits2,viewOnly:!isAttack||!params.target}),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options:contextData.options,self:contextData.self,target:contextData.target??null,rollMode:params.rollMode,traits:contextData.traits},modifiers=[],damageDice=[],{actor}=contextData.self;if(actor.system.abilities){const attributes=actor.system.abilities,attributeModifiers=Object.entries(this.system.damage).filter(([,d])=>d.applyMod).map(([k,d])=>new ModifierPF2e({label:CONFIG.PF2E.abilities[attribute],slug:`ability-${k}`,type:"untyped",modifier:attributes[attribute].mod,damageType:d.type,damageCategory:d.category||null,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,`ability-${k}`)})),extractOptions={resolvables:{spell:this,target:contextData.target?.actor??null},test:contextData.options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:contextData.options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[],kinds:this.damageKinds};if(!params.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials:Array.from(roll.materials),modifiers},context}}loadVariant(options={}){if(this.original)return this.original.loadVariant(options);const{castLevel,overlayIds}=options,appliedOverlays=new Map,heightenEntries=this.getHeightenLayers(castLevel),overlays=overlayIds?.map(id=>({id,data:this.overlays.get(id,{strict:!0})}))??[],overrides=(()=>{if(!heightenEntries.length&&!overlays.length)return castLevel!==this.rank?foundry.utils.mergeObject(this.toObject(),{system:{location:{heightenedLevel:castLevel}}}):null;let source=this.toObject();if(overlays.map(overlay=>overlay.data.overlayType).filter(type=>type==="override").length>1)throw ErrorPF2e(`Error loading variant of Spell ${this.name} (${this.uuid}). Cannot apply multiple override overlays.`);for(const{id,data}of overlays){switch(data.overlayType){case"override":{delete source.system.overlays,source.system.rules=[],source=foundry.utils.mergeObject(source,data,{overwrite:!0});break}}appliedOverlays.set(data.overlayType,id)}for(const overlay of heightenEntries)foundry.utils.mergeObject(source.system,overlay.system);const currentRank=source.system.location.heightenedLevel??source.system.level.value;return castLevel&&castLevel!==currentRank&&(source.system.location.heightenedLevel=castLevel),source._id=this.id,source})();if(!overrides)return null;const variant=new SpellPF2e(overrides,{parent:this.actor,fromConsumable:this.isFromConsumable});return variant.original=this,variant.appliedOverlays=appliedOverlays,variant.trickMagicEntry=this.trickMagicEntry,variant.system.traits.value=Array.from(variant.traits),processSanctification(variant),variant}getHeightenLayers(rank){const heightening=this.system.heightening;return heightening?.type!=="fixed"?[]:Object.entries(heightening.levels).map(([rank2,system])=>({level:Number(rank2),system})).filter(system=>!rank||rank>=system.level).sort((first,second)=>first.level-second.level)}placeTemplate(message){const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"},{area}=this.system;if(!area)throw ErrorPF2e("Attempted to create template with non-area spell");const templateType=templateConversion[area.type],templateData={t:templateType,distance:Number(area.value)/5*(canvas.dimensions?.distance??0),fillColor:game.user.color,flags:{pf2e:{messageId:message?.id,origin:{name:this.name,slug:this.slug,traits:foundry.utils.deepClone(this.system.traits.value),...this.getOriginData()},areaType:this.system.area?.type??null}}};switch(templateType){case"ray":templateData.width=CONFIG.MeasuredTemplate.defaults.width*(canvas.dimensions?.distance??1);break;case"cone":templateData.angle=CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":{const distance=templateData.distance??0;templateData.distance=Math.hypot(distance,distance),templateData.width=distance,templateData.direction=45;break}}return canvas.templates.createPreview(templateData)}prepareBaseData(){super.prepareBaseData(),this.system.location.value||=null,this.system.level.value=Math.clamped(this.system.level.value,1,10)||1,this.system.area?.value?(this.system.area.value=Number(this.system.area.value)||5,this.system.area.type||="burst"):this.system.area=null,this.isRitual&&(this.system.damage={},this.system.defense=null,this.system.traits.value=this.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this.system.traits.traditions=[],this.system.location.value="rituals"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.spellTraits),this.system.traits.value.includes("attack")&&(this.system.defense=foundry.utils.mergeObject(this.system.defense??{},{passive:{statistic:"ac"},save:this.system.defense?.save??null}));const castTime=this.system.time.value=this.system.time.value.trim();!["","2 to 2 rounds"].includes(castTime)&&!this.isRitual&&!getActionGlyph(castTime)&&(this.system.traits.value.push("exploration"),this.system.traits.value.sort());for(const damage of Object.values(this.system.damage)){if(!isObject$1(damage)||typeof damage.formula!="string"){this.system.damage={},delete this.system.heightening,delete this.system.overlays;break}damage.formula=damage.formula?.trim()||"0",damage.kinds=new Set(damage.kinds??["damage"]),(damage.kinds.size===0||this.system.defense?.save?.statistic)&&damage.kinds.add("damage")}if(this.system.heightening?.type==="fixed")for(const heighten of Object.values(this.system.heightening.levels))for(const partial of compact(Object.values(heighten.damage??{})))partial.formula=partial.formula?.trim()||"0";else if(this.system.heightening?.type==="interval")for(const key of Object.keys(this.system.heightening.damage??{}))this.system.heightening.damage[key]=this.system.heightening.damage[key]?.trim()||"0";this.overlays=new SpellOverlayCollection(this,this.system.overlays)}prepareSiblingData(){this.spellcasting?.isInnate&&foundry.utils.mergeObject(this.system.location,{uses:{value:1,max:1}},{overwrite:!1})}prepareActorData(){if(!this.actor?.isOfType("character"))return;const{traits}=this;traits.has("focus")&&!traits.has("cantrip")&&(this.actor.system.resources.focus.max+=1)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const{spellcasting}=this,spellOptions=new Set(["magical",`${prefix}:rank:${this.rank}`,...this.traits]);spellcasting?.tradition&&spellOptions.add(`${prefix}:trait:${spellcasting.tradition}`),!!(spellcasting?.isPrepared||spellcasting?.isSpontaneous)&&!this.isCantrip&&!this.isFromConsumable&&spellOptions.add(`${prefix}:spell-slot`),this.system.duration.value||spellOptions.add(`${prefix}:duration:0`),this.unlimited||spellOptions.add(`${prefix}:frequency:limited`);for(const damage of Object.values(this.system.damage)){damage.type&&(spellOptions.add(`${prefix}:damage:${damage.type}`),spellOptions.add(`${prefix}:damage:type:${damage.type}`));const category=DamageCategorization.fromDamageType(damage.type);category&&spellOptions.add(`${prefix}:damage:category:${category}`),damage.category==="persistent"&&spellOptions.add(`${prefix}:damage:persistent:${damage.type}`)}const isAreaEffect=!!this.system.area?.value;isAreaEffect&&spellOptions.add("area-effect"),this.damageKinds.has("damage")&&(spellOptions.add("damaging-effect"),isAreaEffect&&spellOptions.add("area-damage"));for(const option of spellcasting?.getRollOptions?.("spellcasting")??[])spellOptions.add(option);const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...spellOptions),rollOptions}async toMessage(event2,{create=!0,data,rollMode}={}){const domData=htmlClosest(event2?.currentTarget,".item")?.dataset,castData=foundry.utils.mergeObject(data??{},domData??{}),castLevel=Number(castData.castLevel??"");if(castLevel&&castLevel!==this.rank)return this.loadVariant({castLevel})?.toMessage(event2,{create,data,rollMode});const message=await super.toMessage(event2,{create:!1,data:castData,rollMode});if(!message)return;const messageSource=message.toObject(),flags=messageSource.flags.pf2e,spellcasting=this.spellcasting;if(spellcasting?.statistic){const tradition=spellcasting.tradition??this.traditions.first()??"arcane";if(flags.casting={id:spellcasting.id,tradition},this.isFromConsumable&&(flags.casting.embeddedSpell=this.toObject()),this.system.defense){const dc=spellcasting.statistic.withRollOptions({item:this}).dc;flags.context={type:"spell-cast",domains:dc.domains,options:[...dc.options],rollMode}}}return create?ChatMessagePF2e.create(messageSource,{renderSheet:!1}):(message.updateSource(messageSource),message)}async getChatData(htmlOptions={},rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned spell ${this.name}`);const slotRank=Number(rollOptions.slotLevel)||this.rank,castLevel=Number(rollOptions.castLevel)||this.computeCastRank(slotRank);if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.getChatData(htmlOptions,rollOptions)}const variants=this.overlays.overrideVariants.map(variant=>({...pick(variant,["name","actionGlyph","sort"]),overlayIds:[...variant.appliedOverlays.values()]})).sort((a,b)=>a.sort-b.sort),rollData=htmlOptions.rollData??this.getRollData({castLevel});rollData.item??=this;const systemData=this.system,description=await(async()=>{const options={...htmlOptions,rollData},prepend=await createDescriptionPrepend(this,{includeTraditions:!1}),description2=await TextEditor.enrichHTML(this.description,{...options,async:!0});return`${prepend}
|
|
${description2}`})(),spellcasting=this.spellcasting;if(!spellcasting)return console.warn(`PF2e System | Orphaned spell ${this.name} (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statistic=spellcasting?.statistic;if(!statistic&&!this.isRitual)return console.warn(`PF2e System | Spell ${this.name} is missing a statistic to cast with (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statisticChatData=statistic?.getChatData({item:this}),spellDC=statisticChatData?.dc.value,damage=await this.getDamage(),hasDamage=!!damage,saveType=systemData.defense?.save&&tupleHasValue(SAVE_TYPES,systemData.defense.save.statistic)?systemData.defense.save.statistic:null,isSave=!!saveType,saveKey=systemData.defense?.save?.basic?"PF2E.SaveDCLabelBasic":"PF2E.SaveDCLabel",saveLabel=(()=>{if(!(spellDC&&saveType))return null;const localized=game.i18n.format(saveKey,{dc:spellDC,type:game.i18n.localize(CONFIG.PF2E.saves[saveType])}),tempElement=createHTMLElement("div",{innerHTML:localized}),visibility=game.settings.get("pf2e","metagame_showDC")?"all":"owner";return TextEditorPF2e.convertXMLNode(tempElement,"dc",{visibility,whose:null}),tempElement.innerHTML})(),{damageKinds}=this,damageLabel=damageKinds.has("damage")?damageKinds.has("healing")?"PF2E.Damage.Kind.Both.Roll.Verb":"PF2E.Damage.Kind.Damage.Roll.Verb":"PF2E.Damage.Kind.Healing.Roll.Verb",{baseRank}=this,heightened=castLevel-baseRank,rankLabel=createSpellRankLabel(this,castLevel),area=this.area,properties=compact([heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinalString(baseRank)}):null,heightened?game.i18n.format("PF2E.SpellLevelHeightened",{heightened}):null]),spellTraits2=this.traitChatData(CONFIG.PF2E.spellTraits,uniq(compact([...this.traits,spellcasting.tradition])));return{...systemData,description:{value:description},isAttack:this.isAttack,isSave,check:this.isAttack&&statisticChatData?statisticChatData.check:void 0,save:{...statisticChatData?.dc??{},type:saveType,label:saveLabel},hasDamage,castLevel,rankLabel,damageLabel,formula:damage?.template.damage.roll.formula,properties,traits:spellTraits2,area,variants,isAura:this.traits.has("aura")}}async rollAttack(event2,attackNumber=1,context={}){const{spellcasting}=this,statistic=spellcasting?.statistic;if(statistic)context.extraRollOptions=uniq(compact(["action:cast-a-spell","self:action:slug:cast-a-spell",context.extraRollOptions].flat())),await statistic.check.roll({...eventToRollParams(event2,{type:"check"}),...context,action:"cast-a-spell",item:this,traits:uniq(compact([...this.traits,spellcasting.tradition])),attackNumber});else throw ErrorPF2e("Spell points to location that is not a spellcasting type")}async rollDamage(event2,mapIncreases){const element=htmlClosest(event2.currentTarget,"*[data-cast-level]"),castLevel=Number(element?.dataset.castLevel)||this.rank;if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.rollDamage(event2)}const targetToken=Array.from(game.user.targets).find(t=>t.actor?.isOfType("creature","hazard","vehicle"))?.document??null,spellDamage=await this.getDamage({target:targetToken,...eventToRollParams(event2,{type:"damage"})});if(!spellDamage)return null;const{template,context}=spellDamage;return typeof mapIncreases=="number"&&(context.mapIncreases=mapIncreases,context.options.add(`map:increases:${mapIncreases}`)),DamagePF2e.roll(template,context)}async rollCounteract(event2){if(event2=event2 instanceof Event?event2:event2?.originalEvent,!this.actor?.isOfType("character","npc"))return null;if(!this.spellcasting?.statistic?.attribute)return console.warn(ErrorPF2e(`Spell ${this.name} (${this.uuid}) is missing a statistic with which to counteract.`).message),null;const localize=localizer("PF2E.Item.Spell.Counteract"),statistic=new Statistic(this.actor,{slug:"counteract",label:localize("Label"),attribute:this.spellcasting.attribute,rank:this.spellcasting.statistic.rank??0}),domain="counteract-check",notes=[new RollNotePF2e({selector:domain,text:localize("Hint")}),...DEGREE_OF_SUCCESS_STRINGS.map(degreeString=>{const counteractRank={criticalFailure:0,failure:this.rank,success:this.rank+1,criticalSuccess:this.rank+3}[degreeString];return new RollNotePF2e({selector:domain,title:`PF2E.Check.Result.Degree.Check.${degreeString}`,text:localize(degreeString,{rank:counteractRank}),outcome:[degreeString]})})],traits=uniq(compact([...this.traits,this.spellcasting.tradition])),{check}=statistic.extend({domains:[domain],rollOptions:traits});return check.roll({...eventToRollParams(event2,{type:"check"}),label:game.i18n.localize("PF2E.Check.Specific.Counteract"),extraRollNotes:notes,traits})}getOriginData(){const flag=super.getOriginData();return flag.castLevel=this.rank,this.isVariant&&this.appliedOverlays&&(flag.variant={overlays:[...this.appliedOverlays.values()]}),flag}async update(data,options={}){return this.original&&this.appliedOverlays.has("override")&&this.sheet.rendered?this.original.overlays.updateOverride(this,data,options):super.update(data,options)}async _preCreate(data,options,user){return this._source.system.location.value||=null,this._source.system.ritual&&(this._source.system.damage={},this._source.system.defense=null,this._source.system.location.value=null,this._source.system.traits.value=this._source.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this._source.system.traits.traditions=[]),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const diff=options.diff??=!0,newLocation=changed.system.location?.value,locationChanged=typeof newLocation=="string"&&newLocation!==this._source.system.location.value;if(diff&&(!this.actor||locationChanged)){const system=changed.system,locationUpdates=system.location=this.actor?system.location??{}:{value:""},keys2=Object.keys(this._source.system.location).filter(k=>k!=="value"&&!(k in locationUpdates));for(const key of keys2)locationUpdates[`-=${key}`]=null}if(changed.system.level){const{level}=changed.system;level.value=Math.clamped(Math.trunc(Number(level.value)||1),1,10)}const systemChanges=compact([changed.system,...Object.values(changed.system.overlays??{}).map(o=>o?.system)]);for(const system of systemChanges){(system.defense?.save??{}).statistic===""&&(system.defense=null);for(const partial of compact(Object.values(system.damage??{})))typeof partial.category=="string"&&(partial.category||=null),(partial.category||partial?.type&&!["vitality","void","untyped"].includes(partial.type))&&(partial.kinds=["damage"]);if(system.heightening&&"levels"in system.heightening)for(const rank of compact(Object.values(system.heightening.levels??{})))for(const partial of Object.values(rank.damage??{}))typeof partial?.category=="string"&&(partial.category||=null);const uses=system?.location?.uses;if(uses){const currentUses=uses.value??this.system.location.uses?.value??1,currentMax=uses.max??this.system.location.uses?.max??1;uses.value=Math.clamped(Number(currentUses),0,Number(currentMax))}}return super._preUpdate(changed,options,user)}}class RitualSpellcasting{static{__name(this,"RitualSpellcasting")}static{__name2(this,"RitualSpellcasting")}actor;spells;constructor(actor,rituals){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,usesSpellProficiency:!1,...await this.spells.getSpellData()}}}class SpellCollection extends Collection{static{__name(this,"SpellCollection")}static{__name2(this,"SpellCollection")}entry;actor;constructor(entry){if(!entry.actor)throw ErrorPF2e("a spell collection must have an associated actor");super(),this.entry=entry,this.actor=entry.actor}get id(){return this.entry.id}get highestRank(){const highestSpell=Math.max(...this.map(s=>s.rank)),actorSpellRank=Math.ceil((this.actor?.level??0)/2);return Math.min(10,Math.max(highestSpell,actorSpellRank))}#assertEntryIsDocument(entry){if(!(entry instanceof ItemPF2e))throw ErrorPF2e("`this#entry` is not a `SpellcastingEntryPF2e`")}async addSpell(spell,options={}){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),heightenedRank=canHeighten?options.slotLevel??spell.rank:spell.baseRank;if(spell.system.location.value===this.id&&spell.rank===heightenedRank)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.baseRank>heightenedRank&&this.id===spell.system.location?.value){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(heightenedRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel}))}const heightenedUpdate=canHeighten&&heightenedRank>=spell.baseRank?{"system.location.heightenedLevel":heightenedRank}:{};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,slotRank,spellSlot){if(this.#assertEntryIsDocument(this.entry),spell.baseRank>slotRank&&!(slotRank===0&&spell.isCantrip)){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(slotRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,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${slotRank}.prepared.${spellSlot}`,updates={[key]:{id:spell.id}},slot=this.entry.system.slots[`slot${slotRank}`].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(slotRank,spellSlot){this.#assertEntryIsDocument(this.entry),CONFIG.debug.hooks===!0&&console.debug(`PF2e System | Updating spellcasting entry ${this.id} to remove spellslot ${spellSlot} for spell rank ${slotRank}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`;return this.entry.update({[key]:{name:game.i18n.localize("PF2E.SpellSlotEmpty"),id:null,prepared:!1,expended:!1}})}setSlotExpendedState(slotRank,spellSlot,isExpended){this.#assertEntryIsDocument(this.entry);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}.expended`;return this.entry.update({[key]:isExpended})}async getSpellData(){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 this.#getRitualData();this.#assertEntryIsDocument(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 rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],active=[];if((this.entry.system.showSlotlessLevels.value||data.max>0)&&(rank===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.computeCastRank(rank),spell,expended:!!value.expended})}}results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,uses:{value:rank>0&&isFlexible?data.value||0:void 0,max:data.max},isCantrip:rank===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=cantrips.map(spell=>({spell}));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=leveled.map(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.rank);for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],spells2=spellsByLevel.get(rank)??[];if(alwaysShowHeader||spells2.length){const uses=this.entry.isSpontaneous&&rank!==0?{value:data.value,max:data.max}:void 0,active=spells2.map(spell=>({spell,expended:this.entry.isInnate&&!spell.system.location.uses?.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:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:rank===0,uses,active})}}}if(this.entry.isSpontaneous||isFlexible){for(const spell of signatureSpells)for(const result of results){if(spell.baseRank>result.level||!this.entry.system.showSlotlessLevels.value&&result.uses?.max===0)continue;const existing=result.active.find(a=>a?.spell.id===spell.id);if(existing)existing.signature=!0;else if(result.uses?.max){const castLevel=result.level;result.active.push({spell,castLevel,signature:!0,virtual:!0})}}for(const result of results)if(result.level>0&&result.uses?.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(rank=>rank.uses?.max||0).reduce((first,second)=>first+second,0);return{value:signatureSpells.length,max:totalSlots}})();return{levels:results,flexibleAvailable,spellPrepList:this.getSpellPrepList(spells)}}async#getRitualData(){const groupedByRank=groupBy(Array.from(this.values()),s=>s.rank);return{levels:Array.from(groupedByRank.entries()).sort(([a],[b])=>a-b).map(([rank,spells])=>({label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:!1,active:spells.map(spell=>({spell}))})),spellPrepList:null}}getSpellPrepList(spells){if(!this.entry.isPrepared)return{};const spellPrepList={},spellsByRank=groupBy(spells,spell=>spell.isCantrip?0:spell.baseRank);for(let rank=0;rank<=this.highestRank;rank++)spellPrepList[rank]=spellsByRank.get(rank)?.map(spell=>({spell,signature:this.entry.isFlexible&&spell.system.location.signature}))??[];return Object.values(spellPrepList).some(s=>!!s.length)?spellPrepList:null}}class SpellcastingEntryPF2e extends ItemPF2e{static{__name(this,"SpellcastingEntryPF2e")}static{__name2(this,"SpellcastingEntryPF2e")}get attribute(){return this.system.ability.value||"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellcastingEntryPF2e#ability` is deprecated. Use `SpellcastingEntryPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get tradition(){const defaultTradition=this.system.prepared.value==="items"?null:"arcane",tradition=this.system.tradition.value;return setHasElement(MAGIC_TRADITIONS,tradition)?tradition:defaultTradition}get category(){return this.system.prepared.value}get rank(){return this.system.proficiency.value??0}get isPrepared(){return this.system.prepared.value==="prepared"}get isFlexible(){return this.isPrepared&&!!this.system.prepared.flexible}get isSpontaneous(){return this.system.prepared.value==="spontaneous"}get isInnate(){return this.system.prepared.value==="innate"}get isFocusPool(){return this.system.prepared.value==="focus"}get isRitual(){return!1}get highestLevel(){return this.spells?.highestRank??0}get showSlotlessLevels(){return this.system.showSlotlessLevels.value}prepareBaseData(){super.prepareBaseData(),this.system.proficiency.value=Math.max(1,this.system.proficiency.value),this.system.prepared.flexible??=!1,this.system.prepared.validItems||=null,this.actor&&(this.statistic=new Statistic(this.actor,{slug:this.slug??sluggify(this.name),label:"PF2E.Actor.Creature.Spellcasting.InvalidProficiency",check:{type:"check"}}))}prepareSiblingData(){if(!this.actor||this.system.prepared.value==="items")this.spells=null;else{this.spells=new SpellCollection(this);const spells=this.actor.itemTypes.spell.filter(i=>i.system.location.value===this.id);for(const spell of spells)this.spells.set(spell.id,spell);this.actor.spellcasting.collections.set(this.spells.id,this.spells)}}prepareActorData(){const actor=this.parent;if(!this.system.proficiency.slug&&!this.isInnate&&actor.isOfType("character")){const spellProficiency=actor.system.proficiencies.spellcasting;spellProficiency.rank=Math.clamped(Math.max(spellProficiency.rank,this.system.proficiency.value),1,4)}}prepareStatistic(){const actor=this.actor;if(!actor)return;const{attribute,tradition}=this,slug=this.slug??sluggify(`${this.name}-spellcasting`),baseDomains=["all",`${attribute}-based`,"spell-attack-dc"],checkDomains=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],dcDomains=[`${tradition}-spell-dc`,"spell-dc"];if(actor.isOfType("character")){const baseStat=actor.getStatistic(this.system.proficiency.slug||"base-spellcasting");if(!baseStat)return;this.system.ability.value=baseStat.attribute??this.system.ability.value,this.system.proficiency.value=Math.max(this.rank,baseStat.rank??0),this.statistic=baseStat.extend({slug,label:baseStat.slug==="base-spellcasting"&&tradition?CONFIG.PF2E.magicTraditions[tradition]:baseStat.label,attribute:this.attribute,rank:this.rank,rollOptions:this.getRollOptions("spellcasting"),domains:baseDomains,check:{type:"attack-roll",domains:checkDomains},dc:{domains:dcDomains}})}else if(actor.isOfType("npc")){const adjustment=actor.isElite?2:actor.isWeak?-2:0,baseMod=Number(this.system?.spelldc?.value??0)+adjustment,baseDC=Number(this.system?.spelldc?.dc??0)+adjustment;this.statistic=new Statistic(actor,{slug,attribute:this.attribute,label:CONFIG.PF2E.magicTraditions[tradition??"arcane"],domains:baseDomains,rollOptions:this.getRollOptions("spellcasting"),check:{type:"attack-roll",domains:checkDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseMod,"untyped")]},dc:{domains:dcDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseDC-10,"untyped")]}})}else throw ErrorPF2e(`Actor type ${actor.type} does not support spellcasting entries`);const stat=actor.isOfType("npc")?{value:this.statistic.dc.value}:{value:this.statistic.dc.value,rank:this.statistic.rank??0},attributes=actor.system.attributes;stat.value>attributes.classOrSpellDC.value&&(attributes.classOrSpellDC=stat),(!attributes.spellDC||stat.value>attributes.spellDC.value)&&(attributes.spellDC=stat)}getLinkedItems(){return this.actor?.itemTypes.spell.filter(i=>i.system.location.value===this.id)??[]}canCast(spell,{origin}={}){if(this.system.prepared.value==="items")return origin?this.system.prepared.validItems==="scroll"?origin.traits.has("scroll"):!0:!1;const isSpellcastingFeature=this.isPrepared||this.isSpontaneous;if(origin&&!isSpellcastingFeature||!this.spells)return!1;const matchesTradition=this.tradition&&spell.traditions.has(this.tradition),isInSpellList=this.spells.some(s=>s.slug===spell.slug);return matchesTradition||isInSpellList}async cast(spell,options={}){const consume=options.consume??!0,message=options.message??!0,slotRank=options.level??spell.rank,valid=!consume||spell.isCantrip||await this.consume(spell,slotRank,options.slot);if(message&&valid){const castRank=spell.computeCastRank(slotRank);await spell.toMessage(void 0,{rollMode:options.rollMode,data:{castLevel:castRank}})}}async consume(spell,rank,slot){const actor=this.actor;if(!actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries require an actor");if(this.isRitual)return!0;if(spell.isVariant&&(spell=spell.original),this.isFocusPool&&actor.isOfType("character","npc")){const currentPoints=actor.system.resources.focus?.value??0;return currentPoints>0?(await actor.update({"system.resources.focus.value":currentPoints-1}),!0):(ui.notifications.warn(game.i18n.localize("PF2E.Focus.NotEnoughFocusPointsError")),!1)}const rankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),slotKey=goesToEleven(rank)?`slot${rank}`:"slot0";if(this.system.slots===null||!this.spells)return!1;if(this.isPrepared&&!this.isFlexible){const preparedData=this.system.slots[slotKey].prepared;if(slot??=Number(Object.entries(preparedData).filter(([_,slot2])=>slot2.id===spell.id&&!slot2.expended).at(0)?.[0]),!Number.isInteger(slot))throw ErrorPF2e("Slot not given for prepared spell, and no alternative slot was found");return preparedData[slot].expended??!1?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await this.spells.setSlotExpendedState(rank,slot,!0),!0)}if(this.isInnate){const remainingUses=spell.system.location.uses?.value||0;return remainingUses<=0?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await spell.update({"system.location.uses.value":remainingUses-1}),!0)}const slots=this.system.slots[slotKey];return slots.value>0?(await this.update({[`system.slots.${slotKey}.value`]:slots.value-1}),!0):(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotNotEnoughError",{name:spell.name,level:rankLabel})),!1)}async addSpell(spell,options){return this.spells?.addSpell(spell,options)??null}async prepareSpell(spell,slotRank,spellSlot){return this.spells?.prepareSpell(spell,slotRank,spellSlot)??null}async unprepareSpell(spellLevel,slotRank){return this.spells?.unprepareSpell(spellLevel,slotRank)??null}async setSlotExpendedState(slotRank,spellSlot,isExpended){return this.spells?.setSlotExpendedState(slotRank,spellSlot,isExpended)??null}async getSheetData(){if(!this.actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");const spellCollectionData=await this.spells?.getSpellData()??{levels:[],spellPrepList:null};return{id:this.id,name:this.name,sort:this.sort,attribute:this.attribute,statistic:this.statistic.getChatData(),tradition:this.tradition,category:this.system.prepared.value,isPrepared:this.isPrepared,isSpontaneous:this.isSpontaneous,isFlexible:this.isFlexible,isInnate:this.isInnate,isFocusPool:this.isFocusPool,isRitual:this.isRitual,hasCollection:!!this.spells,usesSpellProficiency:!this.system.proficiency.slug,showSlotlessLevels:this.showSlotlessLevels,...spellCollectionData}}getRollOptions(prefix="spellcasting"){return[`${prefix}:${this.attribute}`,`${prefix}:${this.tradition}`,`${prefix}:${this.system.prepared.value}`]}async _preUpdate(changed,options,user){if(changed.system?.slots)for(const key of[0,1,2,3,4,5,6,7,8,9,10]){const slotKey=`slot${key}`,slotData=changed.system.slots[slotKey];if(slotData&&("max"in slotData&&(slotData.max=Math.max(Number(slotData.max)||0,0)),"value"in slotData)){const max="max"in slotData?Number(slotData?.max)||0:this.system.slots[slotKey].max;slotData.value=Math.clamped(Number(slotData.value),0,max)}}return super._preUpdate(changed,options,user)}getSpellData(){return this.getSheetData()}}const createDisintegrateEffect=__name2(()=>({_id:null,type:"effect",name:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Name"),img:"systems/pf2e/icons/effects/fine-powder.svg",system:{slug:"effect-fine-powder",description:{value:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Description")},rules:[{key:"TokenImage",value:"systems/pf2e/icons/effects/fine-powder.svg"}],tokenIcon:{show:!1}}}),"createDisintegrateEffect");function applyIWR(actor,roll,rollOptions){if(actor.isDead)return{finalDamage:0,applications:[],persistent:[]};if(!game.pf2e.settings.iwr)return{finalDamage:roll.total,applications:[],persistent:roll.instances.filter(i=>i.persistent&&!i.options.evaluatePersistent)};const{immunities,weaknesses,resistances}=actor.attributes,instances=roll.instances,persistent=[],ignoredResistances=(roll.options.ignoredResistances??[]).map(ir=>new Resistance({type:ir.type,value:ir.max??1/0})),nonDamageWeaknesses=weaknesses.filter(w=>NON_DAMAGE_WEAKNESSES.has(w.type)&&instances.some(i=>w.test([...i.formalDescription,...rollOptions]))),damageWeaknesses=weaknesses.filter(w=>!nonDamageWeaknesses.includes(w)),applications=instances.flatMap(instance=>{const formalDescription=new Set([...instance.formalDescription,...rollOptions]),wasIncreased=instance.total<=0&&typeof roll.options.increasedFrom=="number",isFirst=instances.indexOf(instance)===0,instanceTotal=wasIncreased&&isFirst?1:Math.max(instance.total,0);if(!actor.isAffectedBy(instance.type))return[{category:"unaffected",type:instance.type,adjustment:-1*instanceTotal}];const immunity=immunities.find(i=>i.test(formalDescription));if(immunity)return[{category:"immunity",type:immunity.label,adjustment:-1*instanceTotal}];const critImmunity=immunities.find(i=>i.type==="critical-hits"),critImmuneTotal=roll.options.degreeOfSuccess===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?instance.critImmuneTotal:instanceTotal,instanceApplications=[],critImmunityApplies=critImmunity&&critImmuneTotal<instanceTotal;critImmunityApplies&&instanceApplications.push({category:"immunity",type:critImmunity.label,adjustment:-1*(instanceTotal-critImmuneTotal)});const precisionImmunity=immunities.find(i=>i.type==="precision"),precisionDamage=Math.min(instance.componentTotal("precision"),critImmuneTotal);if(precisionDamage>0&&precisionImmunity?.test([...formalDescription,"damage:component:precision"])){const adjustedPrecisionDamage=critImmunityApplies?Math.floor(precisionDamage/2):precisionDamage,adjustment2=-1*Math.min(critImmuneTotal,adjustedPrecisionDamage);instanceApplications.push({category:"immunity",type:precisionImmunity.applicationLabel,adjustment:adjustment2})}const afterImmunities=Math.max(instanceTotal+instanceApplications.reduce((sum,a)=>sum+a.adjustment,0),0);if(instance.persistent&&!instance.options.evaluatePersistent&&persistent.push(instance),afterImmunities===0)return instanceApplications;const mainWeaknesses=damageWeaknesses.filter(w=>w.test(formalDescription)),splashWeakness=instance.componentTotal("splash")?weaknesses.find(w=>w.type==="splash-damage")??null:null,precisionWeakness=precisionDamage>0?weaknesses.find(r=>r.type==="precision"):null,highestWeakness=compact([...mainWeaknesses,precisionWeakness,splashWeakness]).reduce((highest,w)=>w&&!highest||w&&highest&&w.value>highest.value?w:highest,null);highestWeakness&&instanceApplications.push({category:"weakness",type:highestWeakness.applicationLabel,adjustment:highestWeakness.value});const afterWeaknesses=afterImmunities+(highestWeakness?.value??0),applicableResistances=resistances.filter(r=>r.test(formalDescription)).map(r=>({label:r.applicationLabel,value:r.getDoubledValue(formalDescription),ignored:ignoredResistances.some(ir=>ir.test(formalDescription))})),criticalResistance=resistances.find(r=>r.type==="critical-hits");criticalResistance&&critImmuneTotal<instanceTotal&&applicableResistances.push({label:criticalResistance.applicationLabel,value:Math.min(criticalResistance.getDoubledValue(formalDescription),instanceTotal-critImmuneTotal),ignored:ignoredResistances.some(ir=>ir.test(formalDescription))});const precisionResistance=(()=>{const resistance=precisionDamage>0?resistances.find(r=>r.type==="precision"):null;return resistance?{label:resistance.applicationLabel,value:Math.min(resistance.value,precisionDamage),ignored:!1}:null})();precisionResistance&&applicableResistances.push(precisionResistance);const highestResistance=applicableResistances.filter(r=>!r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null),highestIgnored=applicableResistances.filter(r=>r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null);return highestResistance?.value?instanceApplications.push({category:"resistance",type:highestResistance.label,adjustment:-1*Math.min(afterWeaknesses,highestResistance.value),ignored:!1}):highestIgnored&&instanceApplications.push({category:"resistance",type:ignoredResistances.find(ir=>ir.test(formalDescription))?.typeLabel??"???",adjustment:0,ignored:!0}),instanceApplications}).concat(...nonDamageWeaknesses.map(w=>({category:"weakness",type:w.typeLabel,adjustment:w.value}))).sort((a,b)=>{if(a.category===b.category)return 0;switch(a.category){case"unaffected":return-1;case"immunity":return b.type==="unaffected"?1:-1;case"weakness":return["unaffected","immunity"].includes(b.category)?1:-1;default:return 1}}),adjustment=applications.reduce((sum,a)=>sum+a.adjustment,0);return{finalDamage:Math.max(roll.total+adjustment,0),applications,persistent}}__name(applyIWR,"applyIWR"),__name2(applyIWR,"applyIWR");class ActorConditions extends DelegatedCollection{static{__name(this,"ActorConditions")}static{__name2(this,"ActorConditions")}#slugMap=new Collection;get active(){return this.filter(c=>c.active)}get stored(){return this.filter(c=>!c.inMemoryOnly)}get clumsy(){return this.bySlug("clumsy",{active:!0}).shift()??null}get doomed(){return this.bySlug("doomed",{active:!0}).shift()??null}get drained(){return this.bySlug("drained",{active:!0}).shift()??null}get dying(){return this.bySlug("dying",{active:!0}).shift()??null}get enfeebled(){return this.bySlug("enfeebled",{active:!0}).shift()??null}get frightened(){return this.bySlug("frightened",{active:!0}).shift()??null}get sickened(){return this.bySlug("sickened",{active:!0}).shift()??null}get slowed(){return this.bySlug("slowed",{active:!0}).shift()??null}get stunned(){return this.bySlug("stunned",{active:!0}).shift()??null}get stupefied(){return this.bySlug("stupefied",{active:!0}).shift()??null}get wounded(){return this.bySlug("wounded",{active:!0}).shift()??null}get(key,{strict=!1,active=null,temporary=null}={}){const condition=super.get(key,{strict});if(!(active===!0&&!condition?.active)&&!(active===!1&&condition?.active)&&!(temporary===!0&&condition?.actor.items.has(key))&&!(temporary===!1&&!condition?.actor.items.has(key)))return condition}set(id,condition){super.set(id,condition);const listBySlug=this.#slugMap.get(condition.slug)??[];return listBySlug.push(condition),this.#slugMap.set(condition.slug,listBySlug),this}every(condition){return this.contents.every(condition)}flatMap(transformer){return this.contents.flatMap(transformer)}delete(){return!1}bySlug(slug,{active=null,temporary=null}={}){return(this.#slugMap.get(slug)??[]).filter(condition=>{const activeFilterSatisfied=active===!0?condition.active:active===!1?!condition.active:!0,temporaryFilterSatisfied=temporary===!0?!condition.actor.items.has(condition.id):temporary===!1?condition.actor.items.has(condition.id):!0;return activeFilterSatisfied&&temporaryFilterSatisfied})}}var VisionLevels=(VisionLevels2=>(VisionLevels2[VisionLevels2.BLINDED=0]="BLINDED",VisionLevels2[VisionLevels2.NORMAL=1]="NORMAL",VisionLevels2[VisionLevels2.LOWLIGHT=2]="LOWLIGHT",VisionLevels2[VisionLevels2.DARKVISION=3]="DARKVISION",VisionLevels2))(VisionLevels||{});class ItemTransfer{static{__name(this,"ItemTransfer")}static{__name2(this,"ItemTransfer")}constructor(source,target,quantity,containerId){this.source=source,this.target=target,this.quantity=quantity,this.containerId=containerId}#templatePaths={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"};async request(){const gamemaster=game.users.find(u=>u.isGM&&u.active);if(!gamemaster){const source=this.#getSource(),target=this.#getTarget(),loot=[source,target].find(a=>a?.isLootableBy(game.user)&&!a.isOwner);if(!loot)throw ErrorPF2e("Unexpected missing actor");ui.notifications.error(game.i18n.format("PF2E.loot.GMSupervisionError",{loot:ItemTransfer.#tokenName(loot)}));return}console.debug(`PF2e System | Requesting item transfer from GM ${gamemaster.name}`),game.socket.emit("system.pf2e",{request:"itemTransfer",data:this})}async enact(requester){if(!game.user.isGM)throw ErrorPF2e("Unauthorized item transfer");console.debug("PF2e System | Enacting item transfer");const sourceActor=this.#getSource(),sourceItem=sourceActor?.inventory.find(i=>i.id===this.source.itemId),targetActor=this.#getTarget();if(!(sourceActor?.isLootableBy(game.user)&&sourceItem&&targetActor?.isLootableBy(game.user)))throw ErrorPF2e("Failed sanity check during item transfer");const targetItem=await sourceActor.transferItemToActor(targetActor,sourceItem,this.quantity,this.containerId),sourceIsLoot=sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Loot";!sourceItem&&sourceIsLoot||this.#sendMessage(requester,sourceActor,targetActor,targetItem)}#getActor(tokenId,actorId){return typeof tokenId=="string"?canvas.tokens.placeables.find(t=>t.id===tokenId)?.actor??null:game.actors.get(actorId)??null}#getSource(){return this.#getActor(this.source.tokenId,this.source.actorId)}#getTarget(){return this.#getActor(this.target.tokenId,this.target.actorId)}static#tokenName(document2){return"items"in document2?document2.isOfType("party")?game.i18n.localize("PF2E.loot.PartyStash"):document2.token?document2.token.name:document2.prototypeToken?.name??document2.name:document2.character?canvas.tokens.placeables.find(t=>t.actor?.id===document2.id)?.name??document2.character?.name:document2.name}async#sendMessage(requester,sourceActor,targetActor,item){const localize=localizer("PF2E.loot");if(!item)if(sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Merchant"){const message=localize("InsufficientFundsMessage"),content2=await renderTemplate(this.#templatePaths.content,{imgPath:targetActor.img,message:game.i18n.format(message,{buyer:targetActor.name})}),flavor2=await this.#messageFlavor(sourceActor,targetActor,localize("BuySubtitle"));await ChatMessage.create({user:requester.id,speaker:{alias:ItemTransfer.#tokenName(targetActor)},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor:flavor2,content:content2});return}else throw ErrorPF2e("Unexpected item-transfer failure");const[speaker,subtitle,formatArgs]=(()=>{const isMerchant=__name2(actor=>actor.isOfType("loot")&&actor.isMerchant,"isMerchant"),isWhat=__name2(actor=>({isCharacter:actor.testUserPermission(requester,"OWNER")&&actor.isOfType("character"),isMerchant:isMerchant(actor),isNPC:actor.isOfType("npc")&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER"),isLoot:(actor.isOfType("party")||actor.isOfType("loot"))&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER")&&!isMerchant(actor)}),"isWhat"),source=isWhat(sourceActor),target=isWhat(targetActor);if(source.isCharacter&&target.isLoot)return[ItemTransfer.#tokenName(sourceActor),localize("DepositSubtitle"),[localize("DepositMessage"),{depositor:ItemTransfer.#tokenName(sourceActor),container:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isMerchant)return[ItemTransfer.#tokenName(sourceActor),localize("GiveSubtitle"),[localize("GiveMessage"),{giver:ItemTransfer.#tokenName(sourceActor),recipient:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isNPC)return[ItemTransfer.#tokenName(sourceActor),localize("PlantSubtitle"),[localize("PlantMessage"),{planter:ItemTransfer.#tokenName(sourceActor),corpse:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("TakeSubtitle"),[localize("TakeMessage"),{taker:ItemTransfer.#tokenName(targetActor),container:ItemTransfer.#tokenName(sourceActor)}]];if(source.isNPC&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("LootSubtitle"),[localize("LootMessage"),{looter:ItemTransfer.#tokenName(targetActor),corpse:ItemTransfer.#tokenName(sourceActor)}]];if([source,target].every(actor=>actor.isLoot||actor.isNPC))return[requester.character?.name??requester.name,localize("TransferSubtitle"),[localize("TransferMessage"),{transferrer:requester.character?.name??requester.name,fromContainer:ItemTransfer.#tokenName(sourceActor),toContainer:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isMerchant)return[requester.character?.name??requester.name,localize("GiveSubtitle"),[localize("GiveMessage"),{seller:requester.character?.name??requester.name,buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isCharacter)return[ItemTransfer.#tokenName(sourceActor),localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isLoot)return[requester.character?.name??requester.name,localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:requester.character?.name??requester.name}]];throw ErrorPF2e("Unexpected item-transfer failure")})(),formatProperties=formatArgs[1];if(!formatProperties)throw ErrorPF2e("Unexpected item-transfer failure");formatProperties.quantity=this.quantity,formatProperties.item=item.name;const content=await renderTemplate(this.#templatePaths.content,{imgPath:item.img,message:game.i18n.format(...formatArgs).replace(/\b1 × /,"")}),flavor=await this.#messageFlavor(sourceActor,targetActor,subtitle);await ChatMessage.create({user:requester.id,speaker:{alias:speaker},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor,content})}async#messageFlavor(sourceActor,targetActor,subtitle){const glyph=getActionGlyph(sourceActor.isOfType("loot")&&targetActor.isOfType("loot")?2:1),action2={title:"PF2E.Actions.Interact.Title",subtitle,glyph},traits=[{name:"manipulate",label:CONFIG.PF2E.featTraits.manipulate,description:CONFIG.PF2E.traitsDescriptions.manipulate}];return await renderTemplate(this.#templatePaths.flavor,{action:action2,traits})}}class ActorSpellcasting extends DelegatedCollection{static{__name(this,"ActorSpellcasting")}static{__name2(this,"ActorSpellcasting")}constructor(actor,entries){super(entries.map(entry=>[entry.id,entry])),this.actor=actor;for(const entry of entries)entry.spells&&this.collections.set(entry.spells.id,entry.spells)}collections=new Collection;get regular(){return this.filter(e=>e instanceof SpellcastingEntryPF2e)}get ritual(){const ritualCasting=this.collections.get("rituals")?.entry;return ritualCasting instanceof RitualSpellcasting?ritualCasting:null}get spellcastingFeatures(){return this.regular.filter(e=>e.isPrepared||e.isSpontaneous)}canCastConsumable(item){const spell=item.embeddedSpell;return!!spell&&this.some(e=>e.canCast(spell,{origin:item}))}refocus(options={}){if(!options.all)throw ErrorPF2e("Actors do not currently support regular refocusing");if(this.actor.isOfType("character","npc")){const focus=this.actor.system.resources.focus,rechargeFocus=focus?.max&&focus.value<focus.max;if(focus&&rechargeFocus)return focus.value=focus.max,{"system.resources.focus.value":focus.value}}return null}recharge(){const itemUpdates=this.contents.flatMap(entry=>{if(!(entry instanceof SpellcastingEntryPF2e))return[];if(entry.isFocusPool||!entry.spells)return[];if(entry.isInnate)return entry.spells.map(spell=>{const value=spell.system.location.uses?.max??1;return{_id:spell.id,"system.location.uses.value":value}});const slots=entry.system.slots;let updated=!1;for(const slot of Object.values(slots))if(entry.isPrepared&&!entry.isFlexible)for(const preparedSpell of Object.values(slot.prepared))preparedSpell.expended&&(preparedSpell.expended=!1,updated=!0);else slot.value<slot.max&&(slot.value=slot.max,updated=!0);return updated?{_id:entry.id,"system.slots":slots}:[]}),actorUpdates=this.refocus({all:!0});return{itemUpdates,actorUpdates}}}class ActorPF2e extends Actor{static{__name(this,"ActorPF2e")}static{__name2(this,"ActorPF2e")}constructed=!0;constructor(data,context={}){super(data,context),Object.defineProperties(this,{_itemTypes:{configurable:!1,enumerable:!1},checkAreaEffects:{value:foundry.utils.debounce(checkAreaEffects,50)}})}static getDefaultArtwork(actorData){const img=`systems/pf2e/icons/default-icons/${actorData.type}.svg`;return{img,texture:{src:img}}}get itemTypes(){return this._itemTypes??=super.itemTypes}get allowedItemTypes(){return["condition","effect"]}get sourceId(){return this.flags.core?.sourceId??null}get schemaVersion(){return Number(this.system._migration?.version??this.system.schema?.version)||null}get primaryUpdater(){const{activeGM}=game.users;if(activeGM)return activeGM;const activeUsers=game.users.filter(u=>u.active),primaryPlayer=this.isToken?null:activeUsers.find(u=>u.character?.id===this.id);return primaryPlayer||(game.users.filter(u=>this.canUserModify(u,"update")).sort((a,b)=>a.id>b.id?1:-1).shift()??null)}get abilities(){return null}get attributes(){return this.system.attributes}get hitPoints(){const{hp}=this.system.attributes;return hp?{value:hp.value,max:hp.max,temp:hp.temp,unrecoverable:hp.unrecoverable,negativeHealing:hp.negativeHealing}:null}get traits(){return new Set(this.system.traits?.value??[])}get level(){return this.system.details.level.value}get size(){return this.system.traits?.size.value??"med"}get dimensions(){const size=this.system.traits?.size??new ActorSizePF2e({value:"med"});return{length:size.length,width:size.width,height:Math.min(size.length,size.width)}}get canSee(){return!0}get canAct(){return!0}get canAttack(){return!1}get isDead(){const deathIcon=game.settings.get("pf2e","deathIcon");if(this.token)return this.token.overlayEffect===deathIcon;const tokens=this.getActiveTokens(!0,!0);return tokens.length>0&&tokens.every(t=>t.overlayEffect===deathIcon)}get modeOfBeing(){const{traits}=this,isPC=isReallyPC(this);return traits.has("undead")&&!traits.has("eidolon")?"undead":traits.has("construct")&&!isPC&&!traits.has("eidolon")?"construct":"living"}get visionLevel(){return VisionLevels.NORMAL}get emitsSound(){return!1}get rollOptions(){return this.flags.pf2e.rollOptions}get heldShield(){return null}get hardness(){return 0}get canHostRuleElements(){return!0}get alliance(){return this.system.details.alliance}get combatant(){return game.combat?.combatants.find(c=>c.actor?.uuid===this.uuid)??null}get temporaryEffects(){const fromConditions=this.conditions.active.map(c=>new TokenEffect(c)),fromEffects=this.itemTypes.effect.filter(e=>e.system.tokenIcon?.show&&(e.isIdentified||game.user.isGM)).map(e=>new TokenEffect(e));return[super.temporaryEffects,fromConditions,fromEffects,this.synthetics.tokenEffectIcons].flat()}isOfType(...types){return types.some(t=>t==="creature"?tupleHasValue(CREATURE_ACTOR_TYPES,this.type):this.type===t)}isAllyOf(actor){return this.alliance!==null&&this!==actor&&this.alliance===actor.alliance}isEnemyOf(actor){return this.alliance!==null&&actor.alliance!==null&&this.alliance!==actor.alliance}isImmuneTo(effect){if(!game.pf2e.settings.iwr)return!1;const item=typeof effect=="string"?null:"parent"in effect?effect:new ItemProxyPF2e(effect),statements=new Set(item?item.getRollOptions("item"):["item:type:condition",`item:slug:${effect}`]);return this.attributes.immunities.some(i=>i.test(statements))}isAffectedBy(damage){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,damage)?damage:damage.isOfType("condition")?damage.system.persistent?.damageType??null:null;if(!setHasElement(UNAFFECTED_TYPES,damageType))return!0;const{traits}=this;return{good:traits.has("evil"),evil:traits.has("good"),lawful:traits.has("chaotic"),chaotic:traits.has("lawful"),vitality:!!this.attributes.hp?.negativeHealing,void:!(this.modeOfBeing==="construct"||this.attributes.hp?.negativeHealing),bleed:this.modeOfBeing==="living",spirit:!this.itemTypes.effect.some(e=>e.traits.has("possession"))}[damageType]}checkItemValidity(source){return itemIsOfType(source,...this.allowedItemTypes)?!0:(ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type:game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase())})),!1)}getStatistic(slug){return["armor","ac"].includes(slug)?this.armorClass?.parent??null:tupleHasValue(SAVE_TYPES,slug)?this.saves?.[slug]??null:this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:this.synthetics.statistics.get(slug)??null}getSelfRollOptions(prefix="self"){const{rollOptions}=this;return Object.keys(rollOptions.all).flatMap(o=>o.startsWith("self:")&&rollOptions.all[o]?o.replace(/^self/,prefix):[])}getReach(_options){return 0}getContextualClone(rollOptions,ephemeralEffects=[]){const rollOptionsAll=rollOptions.reduce((options,option)=>({...options,[option]:!0}),{}),applicableEffects=ephemeralEffects.filter(e=>!this.isImmuneTo(e));return this.clone({items:[foundry.utils.deepClone(this._source.items),applicableEffects].flat(),flags:{pf2e:{rollOptions:{all:rollOptionsAll}}}},{keepId:!0})}async applyAreaEffects(aura,origin){if(game.user!==this.primaryUpdater||this.isOfType("party")||!this.allowedItemTypes.includes("effect")||origin.token.hidden)return;const toCreate=[],rollOptions=aura.effects.some(e=>e.predicate.length>0)?new Set([...origin.actor.getRollOptions(),...this.getSelfRollOptions("target")]):new Set([]);for(const data of aura.effects.filter(e=>e.predicate.test(rollOptions)))if(!this.itemTypes.effect.some(e=>e.sourceId===data.uuid)&&auraAffectsActor(data,origin.actor,this)){const effect=await fromUuid(data.uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("affliction","effect"))){console.warn(`Effect from ${data.uuid} not found`);continue}const flags={core:{sourceId:effect.uuid},pf2e:{aura:{slug:aura.slug,origin:origin.actor.uuid,removeOnExit:data.removeOnExit}}},source=foundry.utils.mergeObject(effect.toObject(),{flags});source.system.level.value=aura.level??source.system.level.value,source.system.duration.unit="unlimited",source.system.duration.expiry=null,source.system.traits.value.length===0&&source.system.traits.value.push(...aura.traits),source.system.context={target:null,origin:{actor:origin.actor.uuid,token:origin.token.uuid,item:null,spellcasting:null},roll:null};for(const alteration of data.alterations)alteration.applyTo(source);toCreate.push(source)}toCreate.length>0&&await this.createEmbeddedDocuments("Item",toCreate)}static async createDialog(data={},context={}){const omittedTypes=[];game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("army");const original=game.system.documentTypes.Actor;try{if(game.system.documentTypes.Actor=difference(original,omittedTypes),context.types){const validTypes=context.types??[];validTypes.includes("creature")&&validTypes.push(...CREATURE_ACTOR_TYPES),game.system.documentTypes.Actor=game.system.documentTypes.Actor.filter(type=>tupleHasValue(validTypes,type))}return super.createDialog(data,context)}finally{game.system.documentTypes.Actor=original}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ActorPF2e?d.toObject():d);for(const source of[...sources]){const linkable=SIZE_LINKABLE_ACTOR_TYPES.has(source.type),linkToActorSize=linkable&&(source.prototypeToken?.flags?.pf2e?.linkToActorSize??!0),autoscale=linkable&&(source.prototypeToken?.flags?.pf2e?.autoscale??(linkToActorSize&&game.settings.get("pf2e","tokens.autoscale"))),merged=foundry.utils.mergeObject(source,{ownership:source.ownership??{default:CONST.DOCUMENT_OWNERSHIP_LEVELS.NONE},prototypeToken:{flags:{pf2e:{linkToActorSize,autoscale}}}}),dimensionMap={familiar:.5,vehicle:2};switch(merged.prototypeToken.height??=dimensionMap[source.type]??1,merged.prototypeToken.width??=merged.prototypeToken.height,merged.type){case"character":case"familiar":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0};break;case"loot":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!1};break;case"party":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0,range:1};break}const migrated=await migrateActorSource(source);sources.splice(sources.indexOf(source),1,migrated)}return super.createDocuments(sources,context)}static async updateDocuments(updates=[],context={}){for(const changed of updates)await processPreUpdateActorHooks(changed,{pack:context.pack??null});return super.updateDocuments(updates,context)}_initialize(options){this.constructed??=!1,this._itemTypes=null,this.rules=[],this.initiative=null,this.armorClass=null,this.conditions=new ActorConditions,this.auras=new Map;const preparationWarnings=new Set;this.synthetics={criticalSpecalizations:{standard:[],alternate:[]},damageDice:{damage:[]},degreeOfSuccessAdjustments:{},dexterityModifierCaps:[],modifierAdjustments:{all:[],damage:[]},modifiers:{all:[],damage:[]},movementTypes:{},multipleAttackPenalties:{},ephemeralEffects:{},rollNotes:{},rollSubstitutions:{},rollTwice:{},senses:[],statistics:new Map,strikeAdjustments:[],strikes:new Map,striking:{},tokenMarks:new Map,toggles:[],tokenEffectIcons:[],tokenOverrides:{},weaponPotency:{},preparationWarnings:{add:warning=>preparationWarnings.add(warning),flush:foundry.utils.debounce(()=>{for(const warning of preparationWarnings)console.warn(warning);preparationWarnings.clear()},10)}},super._initialize(options),game._documentsReady&&this.synthetics.preparationWarnings.flush()}_initializeSource(source,options){const initialized=super._initializeSource(source,options);if(options?.pack&&initialized._id){const uuid=`Compendium.${options.pack}.${initialized._id}`,art=game.pf2e.system.moduleArt.map.get(uuid)??{};return foundry.utils.mergeObject(initialized,art)}return initialized}prepareData(){this.signature??=UUIDv5(this.uuid,"e9fa1461-0edc-4791-826e-08633f1c6ef7"),super.prepareData();const spellcasting=this.itemTypes.spellcastingEntry,traditionBased=spellcasting.filter(s=>setHasElement(MAGIC_TRADITIONS,s.system.proficiency.slug)),nonTraditionBased=spellcasting.filter(s=>!traditionBased.includes(s));for(const entry of traditionBased)entry.prepareStatistic();for(const rule of this.rules)rule.afterPrepareData?.();for(const entry of nonTraditionBased)entry.prepareStatistic();if(this.attributes.flanking.offGuardable&&this.isImmuneTo("off-guard")&&(this.attributes.flanking.offGuardable=!1),this.preparePrototypeToken(),this.constructed&&canvas.ready){const thisTokenIsControlled=canvas.tokens.controlled.some(t=>t.document===this.parent||t.document.actorLink&&t.actor===this);(game.user.character===this||thisTokenIsControlled)&&game.pf2e.effectPanel.refresh()}}prepareBaseData(){super.prepareBaseData(),this.system.autoChanges={},this.system.attributes.flanking={canFlank:!1,canGangUp:[],flankable:!1,offGuardable:!1};const{attributes,details}=this.system;attributes.hp&&=foundry.utils.mergeObject(attributes.hp,{negativeHealing:!1,unrecoverable:0}),attributes.immunities=attributes.immunities?.map(i=>new Immunity(i))??[],attributes.weaknesses=attributes.weaknesses?.map(w=>new Weakness(w))??[],attributes.resistances=attributes.resistances?.map(r=>new Resistance(r))??[],details.level.value=Math.floor(details.level.value)||0;const traits=this.system.traits;traits?.size&&(traits.size=new ActorSizePF2e(traits.size)),this.flags.pf2e=foundry.utils.mergeObject(this.flags.pf2e??{},{rollOptions:{all:{[`self:type:${this.type}`]:!0,[`self:signature:${this.signature}`]:!0,...createEncounterRollOptions(this)}},trackedItems:{}})}prepareEmbeddedDocuments(){for(const item of this.items)item.reset();const physicalItems=this.items.filter(i=>i.isOfType("physical"));this.inventory=new ActorInventory(this,physicalItems),this.spellcasting=(()=>{const rituals=this.itemTypes.spell.filter(s=>s.isRitual).sort((a,b)=>a.sort-b.sort),spellcastingEntries=[this.itemTypes.spellcastingEntry,rituals.length>0?new RitualSpellcasting(this,rituals):[]].flat();return new ActorSpellcasting(this,spellcastingEntries)})();for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.register(effect);this.prepareDataFromItems()}prepareDataFromItems(){for(const condition of this.itemTypes.condition)this.conditions.set(condition.id,condition);for(const item of this.items)item.prepareSiblingData?.(),item.prepareActorData?.();this.rules=this.prepareRuleElements()}prepareRuleElements(){return sortBy(this.items.contents,i=>i instanceof AbstractEffectPF2e).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}prepareSynthetics(){for(const rule of this.rules.filter(r=>!r.ignored))try{rule.beforePrepareData?.()}catch(error){const ruleName=game.i18n.localize(`PF2E.RuleElement.${rule.key}`);console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${ruleName}.`,error)}for(const item of this.items)item.onPrepareSynthetics?.()}prepareDerivedData(){const{rollOptions}=this;for(const trait of this.traits)rollOptions.all[`self:trait:${trait}`]=!0;this.spellcasting.base=new Statistic(this,{slug:"base-spellcasting",label:"PF2E.Actor.Creature.Spellcasting.Label",rank:this.isOfType("character")?this.system.proficiencies.spellcasting.rank:0,domains:["all","spell-attack-dc"],check:{type:"attack-roll"}})}preparePrototypeToken(){this.prototypeToken.flags=foundry.utils.mergeObject({pf2e:{linkToActorSize:SIZE_LINKABLE_ACTOR_TYPES.has(this.type)}},this.prototypeToken.flags),TokenDocumentPF2e.assignDefaultImage(this.prototypeToken),TokenDocumentPF2e.prepareSize(this.prototypeToken)}async getRollContext(params){const[selfToken,targetToken]=canvas.ready&&!params.viewOnly?[canvas.tokens.controlled.find(t=>t.actor===this)??this.getActiveTokens().shift()??null,params.target?.token??params.target?.actor?.getActiveTokens().shift()??null]:[null,null],isAttackAction=["attack","attack-roll","attack-damage"].some(d=>params.domains.includes(d)),isMelee=!!(params.melee||params.item?.isOfType("weapon","melee")&¶ms.item.isMelee),reach=isMelee&¶ms.item?.isOfType("action","weapon","melee")?this.getReach({action:"attack",weapon:params.item}):this.getReach({action:"attack"}),isFlankingAttack=!!(isAttackAction&&isMelee&&typeof reach=="number"&&targetToken?.actor&&selfToken?.isFlanking(targetToken,{reach})),originEphemeralEffects=await extractEphemeralEffects({affects:"origin",origin:this,target:params.target?.actor??targetToken?.actor??null,item:params.item??null,domains:params.domains,options:[...params.options,...params.item?.getRollOptions("item")??[]]}),targetMarkOption=(()=>{const tokenMark=targetToken?this.synthetics.tokenMarks.get(targetToken.document.uuid):null;return tokenMark?`target:mark:${tokenMark}`:null})(),initialActionOptions=params.traits?.map(t=>`self:action:trait:${t}`)??[],selfActor=params.viewOnly||!targetToken?.actor?this:this.getContextualClone(compact([...Array.from(params.options),...targetToken.actor.getSelfRollOptions("target"),targetMarkOption,...initialActionOptions,isFlankingAttack?"self:flanking":null]),originEphemeralEffects),isStrike=params.statistic instanceof StatisticModifier,strikeActions=isStrike?selfActor.system.actions?.flatMap(a=>[a,a.altUsages??[]].flat())??[]:[],statistic=params.viewOnly?params.statistic:isStrike?strikeActions.find(action2=>params.item?.id!==action2.item.id||params?.item.name!==action2.item.name?!1:params.item.isOfType("melee")&&action2.item.isOfType("melee")?!0:params.item.isOfType("weapon")&&action2.item.isOfType("weapon")&¶ms.item.isMelee===action2.item.isMelee)??params.statistic:params.statistic,selfItem=(()=>{if(selfActor===this)return params.item??null;if(statistic&&"item"in statistic&&statistic.item instanceof ItemPF2e&&statistic.item.isOfType("action","melee","spell","weapon"))return statistic.item;const itemClone=selfActor.items.get(params.item?.id??"");return itemClone?.isOfType("melee","weapon")?itemClone:params.item??null})(),itemOptions=selfItem?.getRollOptions("item")??[],actionTraits2=(()=>{const traits=compact([params.traits].flat());if(selfItem?.isOfType("weapon","melee")){const strikeAdjustments=[selfActor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(selfItem.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(selfItem,traits)}return uniq(traits).sort()})(),distance=selfToken&&targetToken?selfToken.distanceTo(targetToken):null,[originDistance,targetDistance]=typeof distance=="number"?[`origin:distance:${distance}`,`target:distance:${distance}`]:[null,null],originMarkOption=(()=>{const tokenMark=selfToken?targetToken?.actor?.synthetics.tokenMarks.get(selfToken.document.uuid):null;return tokenMark?`origin:mark:${tokenMark}`:null})(),originRollOptions=selfToken&&targetToken?compact(uniq([...selfActor.getSelfRollOptions("origin"),...actionTraits2.map(t=>`origin:action:trait${t}`),...originDistance?[originDistance]:[],originMarkOption])):[],getTargetRollOptions=__name2(actor=>{const targetOptions=actor?.getSelfRollOptions("target")??[];return targetToken&&(targetOptions.push("target"),targetMarkOption&&targetOptions.push(targetMarkOption)),targetOptions.sort()},"getTargetRollOptions"),targetRollOptions=getTargetRollOptions(targetToken?.actor),targetEphemeralEffects=await extractEphemeralEffects({affects:"target",origin:selfActor,target:targetToken?.actor??null,item:selfItem,domains:params.domains,options:[...params.options,...itemOptions,...targetRollOptions]});if(isFlankingAttack&&isOffGuardFromFlanking(targetToken.actor,selfActor,originRollOptions)){const name2=game.i18n.localize("PF2E.Item.Condition.Flanked"),condition=game.pf2e.ConditionManager.getCondition("off-guard",{name:name2});targetEphemeralEffects.push(condition.toObject())}const targetActor=params.viewOnly?null:(params.target?.actor??targetToken?.actor)?.getContextualClone(compact([...params.options,...itemOptions,...originRollOptions]),targetEphemeralEffects)??null,rollOptions=new Set(compact([...params.options,...selfActor.getRollOptions(params.domains),...targetActor?getTargetRollOptions(targetActor):targetRollOptions,...actionTraits2.map(t=>`self:action:trait:${t}`),...itemOptions,isAttackAction?"attack":null]).sort());targetDistance&&rollOptions.add(targetDistance);const rangeIncrement=selfItem?getRangeIncrement(selfItem,distance):null;rangeIncrement&&rollOptions.add(`target:range-increment:${rangeIncrement}`);const self={actor:selfActor,token:selfToken?.document??null,statistic,item:selfItem,modifiers:[]},target=targetActor&&targetToken&&distance!==null?{actor:targetActor,token:targetToken.document,distance,rangeIncrement}:null;return{options:rollOptions,self,target,traits:actionTraits2}}async getCheckContext(params){const context=await this.getRollContext(params),targetActor=context.target?.actor,rangeIncrement=context.target?.rangeIncrement??null,rangePenalty=calculateRangePenalty(this,rangeIncrement,params.domains,context.options);rangePenalty&&context.self.modifiers.push(rangePenalty);const dcData=(()=>{const{domains,defense}=params,scope=domains.includes("attack")?"attack":"check",statistic=targetActor?.getStatistic(defense)?.dc;return statistic?{scope,statistic,slug:defense,value:statistic.value}:null})();return{...context,dc:dcData}}async getDamageRollContext(params){params.checkContext??=findMatchingCheckContext(this,params),params.outcome&¶ms.options.add(`check:outcome:${sluggify(params.outcome)}`);const substitution=params.checkContext?.substitutions.find(s=>s.selected);return substitution&¶ms.options.add(`check:substitution:${substitution.slug}`),this.getRollContext(params)}async toggleRollOption(domain,option,itemId=null,value,suboption=null){return value=typeof itemId=="boolean"?itemId:value??!this.rollOptions[domain]?.[option],typeof itemId=="string"?this.items.get(itemId,{strict:!0}).rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null:this.rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null}async modifyTokenAttribute(attribute,value,isDelta=!1,isBar){const token=this.getActiveTokens(!0,!0).shift(),{hitPoints}=this;if(!!(attribute==="attributes.hp"&&hitPoints&&(isDelta||value===0&&token?.combatant))&&token){const damage=isDelta?-1*value:hitPoints.value-value;return this.applyDamage({damage,token})}return super.modifyTokenAttribute(attribute,value,isDelta,isBar)}async applyDamage({damage,token,item,rollOptions=new Set,skipIWR=!1,shieldBlockRequest=!1,breakdown=[],notes=[]}){const{hitPoints}=this;if(!hitPoints)return this;const result=typeof damage=="number"?{finalDamage:Math.trunc(damage),applications:[],persistent:[]}:skipIWR?{finalDamage:damage.total,applications:[],persistent:[]}:applyIWR(this,damage,rollOptions),{finalDamage}=result,localize=localizer("PF2E.Actor.ApplyDamage"),actorShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldBlock=actorShield&&shieldBlockRequest?(()=>actorShield.broken?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsBroken",{actor:token.name,shield:actorShield.name})),!1):actorShield.destroyed?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsDestroyed",{actor:token.name,shield:actorShield.name})),!1):actorShield.raised?!0:(ui.notifications.warn(localize("ShieldNotRaised",{actor:token.name})),!1))():!1,shieldHardness=shieldBlock?actorShield?.hardness??0:0,damageAbsorbedByShield=finalDamage>0?Math.min(shieldHardness,finalDamage):0,{heldShield}=this,blockingShield=heldShield?.id===actorShield?.itemId?heldShield:null,currentShieldHP=blockingShield?blockingShield._source.system.hp.value:actorShield?.hp.value??0,shieldDamage=shieldBlock?Math.min(currentShieldHP,Math.abs(finalDamage)-damageAbsorbedByShield):0,baseActorHardness=this.hardness,effectiveActorHardness=(()=>{const damageHasAdamantine=typeof damage=="number"?!1:damage.materials.has("adamantine"),materialGrade=item?.isOfType("weapon")&&item.system.material.type==="adamantine"?item.system.material.grade??"standard":"standard",itemHardness={low:0,standard:10,high:13}[materialGrade];return damageHasAdamantine&&itemHardness>=baseActorHardness?Math.floor(baseActorHardness/2):baseActorHardness})(),damageAbsorbedByActor=finalDamage>0?Math.min(finalDamage-damageAbsorbedByShield,effectiveActorHardness):0;if(damageAbsorbedByActor>0){const typeLabel=effectiveActorHardness===baseActorHardness?"PF2E.Damage.Hardness.Full":"PF2E.Damage.Hardness.Half";result.applications.push({category:"reduction",type:game.i18n.localize(typeLabel),adjustment:-1*damageAbsorbedByActor})}const damageResult=this.calculateHealthDelta({hp:hitPoints,sp:this.isOfType("character")?this.attributes.hp.sp:null,delta:finalDamage-damageAbsorbedByShield-damageAbsorbedByActor}),preUpdateSource=this.toObject();blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:damageResult.totalApplied===0});const staminaMax=this.isOfType("character")?this.attributes.hp.sp?.max??0:0,instantDeath=(()=>damageResult.totalApplied<=0||damageResult.updates["system.attributes.hp.value"]!==0?null:rollOptions.has("item:trait:death")&&!this.attributes.immunities.some(i=>i.type==="death-effects")?"death-effect":rollOptions.has("item:type:spell")&&rollOptions.has("item:slug:disintegrate")?"fine-powder":this.isOfType("npc")&&this.modeOfBeing==="undead"?"destroyed":damageResult.totalApplied>=(hitPoints.max+staminaMax)*2?"massive-damage":null)(),finePowder=instantDeath==="fine-powder";if(damageResult.totalApplied!==0){const updated=await this.update(damageResult.updates,{damageTaken:damageResult.totalApplied,finePowder}),setting=game.settings.get("pf2e","automation.actorsDeadAtZero"),deadAtZero=this.isOfType("npc")&&["npcsOnly","both"].includes(setting)||this.isOfType("character")&&setting==="both"&&!!instantDeath;updated?.isDead&&deadAtZero&&(damageResult.totalApplied>=0&&!token.combatant?.isDefeated||damageResult.totalApplied<0&&token.combatant?.isDefeated)&&token.combatant?.toggleDefeated({overlayIcon:!finePowder}).then(()=>{finePowder&&this.createEmbeddedDocuments("Item",[createDisintegrateEffect()])})}const hpStatement=(()=>hitPoints.max===0||finalDamage-damageAbsorbedByActor===0?localize("TakesNoDamage"):finalDamage>0?damageAbsorbedByShield>0?damageResult.totalApplied>0?localize("DamagedForNShield"):localize("ShieldAbsorbsAll"):localize("DamagedForN"):damageResult.totalApplied<0?localize("HealedForN"):localize("AtFullHealth"))(),updatedShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldStatement=updatedShield&&shieldDamage>0?updatedShield.broken?localize("ShieldDamagedForNBroken"):updatedShield.destroyed?localize("ShieldDamagedForNDestroyed"):localize("ShieldDamagedForN"):null,statements=(()=>{const deathMessage=instantDeath&&localize(`InstantDeath.${sluggify(instantDeath,{camel:"bactrian"})}`),concatenated=compact([hpStatement,shieldStatement,deathMessage]).map(s=>game.i18n.format(s,{actor:token.name.replace(/[<>]/g,""),hpDamage:Math.abs(damageResult.totalApplied),absorbedDamage:damageAbsorbedByShield,shieldDamage})).join(" "),tempElem=document.createElement("div");return tempElem.innerHTML=concatenated,TextEditorPF2e.convertXMLNode(tempElem,"actor",{whose:null,classes:["target-name"]}),tempElem.innerHTML})(),deparenthesize=__name2(formula=>formula.replace(/^\(([^)]+)\)$/,"$1"),"deparenthesize"),persistentDamage=result.persistent.map(instance=>{const condition=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject();return condition.system.persistent={formula:deparenthesize(instance.head.expression),damageType:instance.type,dc:15},condition}),persistentCreated=persistentDamage.length>0?await this.createEmbeddedDocuments("Item",persistentDamage):[],canUndoDamage=!!(damageResult.totalApplied||shieldDamage||persistentCreated.length),content=await renderTemplate("systems/pf2e/templates/chat/damage/damage-taken.hbs",{breakdown,notes,statements,persistent:compact(persistentCreated.map(p=>p.system.persistent?.damage.formula)),iwr:{applications:result.applications,visibility:this.hasPlayerOwner?"all":"gm"},canUndoDamage}),flavor=await(async()=>{if(breakdown.length||notes.length)return renderTemplate("systems/pf2e/templates/chat/damage/damage-taken-flavor.hbs",{breakdown,notes})})(),appliedDamage=canUndoDamage?{uuid:this.uuid,isHealing:damageResult.totalApplied<0,shield:shieldDamage!==0?{id:actorShield?.itemId??"",damage:shieldDamage}:null,persistent:persistentCreated.map(c=>c.id),updates:Object.entries(damageResult.updates).map(([path,newValue])=>{const preUpdateValue=foundry.utils.getProperty(preUpdateSource,path);if(typeof preUpdateValue=="number"){const difference2=preUpdateValue-newValue;return difference2===0?[]:{path,value:difference2}}return[]}).flat()}:null;return await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({token}),flags:{pf2e:{appliedDamage}},flavor,content,type:CONST.CHAT_MESSAGE_TYPES.OTHER,whisper:game.settings.get("pf2e","metagame_secretDamage")&&!token.actor?.hasPlayerOwner?ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id):[]}),this}async undoDamage(appliedDamage){const{updates,shield,persistent}=appliedDamage,actorUpdates={};for(const update of updates){const currentValue=foundry.utils.getProperty(this,update.path);typeof currentValue=="number"&&(actorUpdates[update.path]=currentValue+update.value)}if(shield){const item=this.inventory.get(shield.id);item&&(actorUpdates.items=[{_id:shield.id,"system.hp.value":item.hitPoints.value+shield.damage}])}const updateCount=Object.keys(actorUpdates).length;if(persistent.length&&await this.deleteEmbeddedDocuments("Item",persistent,{render:updateCount===0}),updateCount){const{hitPoints}=this,damageTaken=hitPoints&&typeof actorUpdates["system.attributes.hp.value"]=="number"?hitPoints.value-actorUpdates["system.attributes.hp.value"]:0;this.update(actorUpdates,{damageTaken,damageUndo:!0})}}isLootableBy(user){return this.canUserModify(user,"update")}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(item instanceof PhysicalItemPF2e))throw ErrorPF2e("Only physical items (with quantities) can be transfered between actors");const container=targetActor.inventory.get(containerId??"");if(!(!container||container instanceof ContainerPF2e))throw ErrorPF2e("containerId refers to a non-container");if(__name2((source,target)=>{const bothAreOwned=source.isOwner&&target.isOwner,sourceIsOwnedOrLoot=source.isLootableBy(game.user),targetIsOwnedOrLoot=target.isLootableBy(game.user);return!bothAreOwned&&sourceIsOwnedOrLoot&&targetIsOwnedOrLoot},"gmMustTransfer")(this,targetActor)){const source={tokenId:this.token?.id,actorId:this.id,itemId:item.id},target={tokenId:targetActor.token?.id,actorId:targetActor.id};return await new ItemTransfer(source,target,quantity,container?.id).request(),null}if(!this.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemSource")),null;if(!targetActor.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemDestination")),null;quantity=Math.min(quantity,item.quantity);const newQuantity=item.quantity-quantity;newQuantity<1?await item.delete():await item.update({"system.quantity":newQuantity});const newItemData=item.toObject();return newItemData.system.quantity=quantity,newItemData.system.equipped.carryType="worn",hasInvestedProperty(newItemData)&&(newItemData.system.equipped.invested=item.traits.has("invested")?!1:null),targetActor.addToInventory(newItemData,container,newStack)}async addToInventory(itemSource,container,newStack){const stackItem=this.inventory.findStackableItem(itemSource);if(!newStack&&stackItem&&stackItem.type!=="backpack"){const stackQuantity=stackItem.quantity+itemSource.system.quantity;return await stackItem.update({"system.quantity":stackQuantity}),stackItem}const result=await ItemPF2e.create(itemSource,{parent:this});if(!result)return null;const movedItem=this.inventory.get(result.id);return movedItem?(await this.stowOrUnstow(movedItem,container),movedItem):null}async stowOrUnstow(item,container){if(!container)await item.update({"system.containerId":null,"system.equipped.carryType":"worn","system.equipped.handsHeld":0,"system.equipped.inSlot":!1});else if(!isCycle(item,container)){const carryType=container.stowsItems?"stowed":"worn";await item.update({"system.containerId":container.id,"system.equipped.carryType":carryType,"system.equipped.handsHeld":0,"system.equipped.inSlot":!1})}}calculateHealthDelta(args){const updates={},{hp,sp,delta}=args;if(hp.max===0)return{updates,totalApplied:0};const appliedToTemp=(()=>{if(!hp.temp||delta<=0)return 0;const applied=Math.min(hp.temp,delta);return updates["system.attributes.hp.temp"]=Math.max(hp.temp-applied,0),applied})(),appliedToSP=(()=>{if(!(!!sp&&game.pf2e.settings.variants.stamina)||delta<=0)return 0;const remaining=delta-appliedToTemp,applied=Math.min(sp.value,remaining);return updates["system.attributes.hp.sp.value"]=Math.max(sp.value-applied,0),applied})(),appliedToHP=(()=>{const remaining=delta-appliedToTemp-appliedToSP;return updates["system.attributes.hp.value"]=Math.clamped(hp.value-remaining,0,hp.max),remaining})(),totalApplied=appliedToTemp+appliedToSP+appliedToHP;return{updates,totalApplied}}getRollOptions(domains=[]){const withAll=Array.from(new Set(["all",...domains])),{rollOptions}=this,toReturn=new Set;for(const domain of withAll)for(const[option,value]of Object.entries(rollOptions[domain]??{}))value&&toReturn.add(option);return Array.from(toReturn)}getRollData(){const rollData={actor:this};for(const prop of["abilities","attributes","details","skills","saves"])Object.defineProperty(rollData,prop,{get:()=>(foundry.utils.logCompatibilityWarning(`@${prop} is deprecated`,{since:"5.0.1",until:"6"}),objectHasKey(this.system,prop)?foundry.utils.deepClone(this.system[prop]):null)});return rollData}getCondition(slugOrKey,{all=!1}={}){const conditions=this.conditions.filter(c=>c.key===slugOrKey||c.slug===slugOrKey);return all?conditions.sort((conditionA,conditionB)=>{const[valueA,valueB]=[conditionA.value??0,conditionB.value??0];return valueA>valueB?-1:valueA<valueB?1:0}):conditions.find(c=>c.active)??null}hasCondition(...slugs){return slugs.some(s=>this.conditions.bySlug(s,{active:!0}).length>0)}async decreaseCondition(conditionSlug,{forceRemove}={forceRemove:!1}){const condition=typeof conditionSlug=="string"?this.getCondition(conditionSlug):conditionSlug;if(!condition)return;if(condition.slug==="persistent-damage"){const matching=this.conditions.stored.filter(c=>c.key===condition.key).map(c=>c.id);await this.deleteEmbeddedDocuments("Item",matching);return}const currentValue=condition._source.system.value.value,newValue=typeof currentValue=="number"?Math.max(currentValue-1,0):null;newValue!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,newValue):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{max=Number.MAX_SAFE_INTEGER,value}={}){if(conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.itemTypes.condition;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const newValue=(()=>{const currentValue=existing._source.system.value.value;if(currentValue===null)return null;const addend=value??1;return Math.clamped(currentValue+addend,1,max)})();return newValue?(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,newValue),existing):null}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource.system.value.value=="number"&&max?Math.clamped(conditionSource.system.value.value,value??1,max):null;return conditionSource.system.value.value=conditionValue,(await this.createEmbeddedDocuments("Item",[conditionSource])).shift()??null}return null}async toggleCondition(conditionSlug){if(!setHasElement(CONDITION_SLUGS,conditionSlug))throw ErrorPF2e(`Unrecognized condition: ${conditionSlug}`);this.hasCondition(conditionSlug)?await this.decreaseCondition(conditionSlug,{forceRemove:!0}):await this.increaseCondition(conditionSlug)}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}_applyDefaultTokenSettings(data,options){const diff=super._applyDefaultTokenSettings(data,options);return this._source.prototypeToken.texture.src===CONST.DEFAULT_TOKEN&&(this._source.prototypeToken.texture.src=ActorPF2e.getDefaultArtwork(data).texture.src),diff}async _preUpdate(changed,options,user){const changedHP=changed.system?.attributes?.hp,currentHP=this.hitPoints;if(!options.damageTaken&&this.hasPlayerOwner&&typeof changedHP?.value=="number"&¤tHP){const damageTaken=-1*(changedHP.value-currentHP.value),levelChanged=!!changed.system?.details&&"level"in changed.system.details;damageTaken&&!levelChanged&&(options.damageTaken=damageTaken)}return super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const hideFromUser=!this.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_secretDamage");if(options.damageTaken&&!hideFromUser){const tokens=this.getActiveTokens();for(const token of tokens)token.showFloatyText(-1*options.damageTaken)}if(canvas.ready&&changed.system?.details&&"alliance"in changed.system.details)for(const token of this.getActiveTokens(!0,!0))token.reset();const currentHP=this.hitPoints?.value??0,hpChange=Number(changed.system?.attributes?.hp?.value)||0;if(currentHP>0&&hpChange>0&&this.isDead){const{combatant}=this;if(combatant)combatant.toggleDefeated({to:!1});else for(const tokenDoc of this.getActiveTokens(!1,!0))tokenDoc.update({overlayEffect:""})}}_onDelete(options,userId){for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.unregister(effect);super._onDelete(options,userId)}_onEmbeddedDocumentChange(){super._onEmbeddedDocumentChange(),this.synthetics.preparationWarnings.flush()}}const ActorProxyPF2e=new Proxy(ActorPF2e,{construct(_target,args){return new CONFIG.PF2E.Actor.documentClasses[args[0].type](...args)}});class CreaturePF2e extends ActorPF2e{static{__name(this,"CreaturePF2e")}static{__name2(this,"CreaturePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"affliction"]}get creatureTypes(){return this.system.traits.value.filter(t=>t in CONFIG.PF2E.creatureTypes).sort()}get rarity(){return this.system.traits.rarity}get hardness(){return Math.floor(Math.abs(this.system.attributes.hardness.value))||0}getReach({action:action2="interact",weapon=null}={}){const baseReach=this.attributes.reach.base,weaponReach=weapon?.isOfType("melee")?weapon.reach:null;if(action2==="interact"||this.type==="familiar")return baseReach;if(typeof weaponReach=="number")return weaponReach;{const traitsFromItems=(weapon?[{item:weapon,ready:!0}]:this.system.actions??[]).filter(a=>a.ready).map(a=>new Set(a.item.system.traits?.value??[]));if(traitsFromItems.length===0)return baseReach;const reaches=traitsFromItems.map(traits=>{if(setHasElement(traits,"reach"))return baseReach+5;const reachNPattern=/^reach-\d{1,3}$/;return Number([...traits].find(t=>reachNPattern.test(t))?.replace("reach-",""))||baseReach});return Math.max(...reaches)}}get visionLevel(){const{senses:senses2}=this.system.traits;if(!(Array.isArray(senses2)&&senses2.every(s=>isObject(s)&&"type"in s&&typeof s.type=="string")))return VisionLevels.NORMAL;const senseTypes=new Set(senses2.map(sense=>sense.type));return this.getCondition("blinded")?VisionLevels.BLINDED:senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision")?VisionLevels.DARKVISION:senseTypes.has("lowLightVision")?VisionLevels.LOWLIGHT:VisionLevels.NORMAL}get hasDarkvision(){return this.visionLevel===VisionLevels.DARKVISION&&!this.hasCondition("blinded")}get hasLowLightVision(){return this.visionLevel>=VisionLevels.LOWLIGHT&&!this.hasCondition("blinded")}get canSee(){return canvas.scene?this.visionLevel===VisionLevels.BLINDED?!1:canvas.scene.lightLevel>LightLevels.DARKNESS||this.hasDarkvision:!0}get canAct(){const traits=this.system.traits.value;return(!this.isDead||traits.some(t=>t==="eidolon"))&&!this.hasCondition("paralyzed","stunned","unconscious")}get canAttack(){return this.type!=="familiar"&&this.canAct}get isDead(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0&&!this.hasCondition("dying","unconscious")?!0:!!(this.token??this.getActiveTokens(!1,!0).shift())?.hasStatusEffect("dead")}get emitsSound(){return this.system.attributes.emitsSound}get isSpellcaster(){const{itemTypes}=this;return itemTypes.spellcastingEntry.length>0&&itemTypes.spell.length>0}get wornArmor(){return this.itemTypes.armor.find(a=>a.isEquipped)??null}get heldShield(){const heldShields=this.itemTypes.shield.filter(s=>s.isEquipped);return heldShields.length===0?null:heldShields.slice(0,-1).reduce((bestShield,shield)=>{if(bestShield===shield)return bestShield;const withBetterAC=bestShield.acBonus>shield.acBonus?bestShield:shield.acBonus>bestShield.acBonus?shield:null,withMoreHP=bestShield.hitPoints.value>shield.hitPoints.value?bestShield:shield.hitPoints.value>bestShield.hitPoints.value?shield:null,withBetterHardness=bestShield.hardness>shield.hardness?bestShield:shield.hardness>bestShield.hardness?shield:null;return withBetterAC??withMoreHP??withBetterHardness??bestShield},heldShields.slice(-1)[0])}getStatistic(slug){switch(slug){case"perception":return this.perception;case"spell":case"spell-attack":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.mod-a.mod).shift()??null;case"spell-dc":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.dc.value-a.dc.value).shift()??null}return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).find(s=>s.slug===slug)??super.getStatistic(slug)}_initialize(options){this.parties??=new Set,super._initialize(options)}prepareData(){super.prepareData();for(const party of this.parties)party.reset({actor:!0})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.rollOptions.all["self:creature"]=!0;const attributes=this.system.attributes;attributes.hardness??={value:0},attributes.flanking.canFlank=!0,attributes.flanking.flankable=!0,attributes.flanking.offGuardable=!0,attributes.reach={base:0,manipulate:0},attributes.speed=foundry.utils.mergeObject({total:0,value:0},attributes.speed??{}),attributes.initiative&&(attributes.initiative.tiebreakPriority=this.hasPlayerOwner?2:1);const customModifiers=this.system.customModifiers??={};for(const selector of Object.keys(customModifiers))customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));this.isOfType("character","npc")&&(this.system.attributes.shield={itemId:null,name:game.i18n.localize("PF2E.ArmorTypeShield"),ac:0,hp:{value:0,max:0},brokenThreshold:0,hardness:0,raised:!1,broken:!1,destroyed:!1,icon:"systems/pf2e/icons/actions/raise-a-shield.webp"}),attributes.doomed={value:0,max:3},attributes.dying={value:0,max:4,recoveryDC:10},attributes.wounded={value:0,max:3},setImmunitiesFromTraits(this)}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.();for(const changeEntries of Object.values(this.system.autoChanges))changeEntries?.sort((a,b)=>Number(a.level)>Number(b.level)?1:-1);this.rollOptions.all[`self:mode:${this.modeOfBeing}`]=!0}prepareDerivedData(){super.prepareDerivedData();const{attributes}=this,reachFromSize=SIZE_TO_REACH[this.size];attributes.reach.base=Math.max(attributes.reach.base,reachFromSize),attributes.reach.manipulate=Math.max(attributes.reach.manipulate,attributes.reach.base,reachFromSize);const{rollOptions}=this;this.isSpellcaster&&(rollOptions.all["self:caster"]=!0),this.hitPoints.negativeHealing&&(rollOptions.all["self:negative-healing"]=!0),rollOptions.all["self:armored"]=!!this.wornArmor&&this.wornArmor.category!=="unarmored",attributes.shield?.raised&&!attributes.shield.broken&&!attributes.shield.destroyed&&(this.rollOptions.all["self:shield:raised"]=!0),this.system.attributes.emitsSound=!this.isDead,this.prepareSynthetics();const sizeIndex=SIZES.indexOf(this.size),sizeSlug=SIZE_SLUGS[sizeIndex];rollOptions.all[`self:size:${sizeIndex}`]=!0,rollOptions.all[`self:size:${sizeSlug}`]=!0,attributes.wounded.max=Math.max(0,attributes.dying.max-1),attributes.doomed.max=attributes.dying.max;for(const conditionSlug of["doomed","wounded","dying"]){const condition=this.conditions.bySlug(conditionSlug,{active:!0}).at(0),status=attributes[conditionSlug];conditionSlug==="dying"&&(status.max-=attributes.doomed.value),status.value=Math.min(condition?.value??0,status.max)}if(this.system.resources?.focus){const{focus}=this.system.resources;focus.max=Math.clamped(Math.floor(focus.max),0,focus.cap)||0,focus.value=Math.clamped(Math.floor(focus.value),0,focus.max)||0}imposeEncumberedCondition(this)}prepareSynthetics(){super.prepareSynthetics();for(const[selector,modifiers]of Object.entries(this.system.customModifiers))(this.synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}async adjustCarryType(item,{carryType,handsHeld=0,inSlot=!1}){const{usage}=item.system;if(carryType==="stowed"){const container=item.actor.itemTypes.backpack.find(c=>c!==item.container&&!isCycle(item,c));container&&await item.actor.stowOrUnstow(item,container)}else{const equipped={carryType,handsHeld:carryType==="held"?handsHeld:0,inSlot:usage.type==="worn"&&usage.where?inSlot:void 0},updates=[];if(isEquipped(usage,equipped)&&item.isOfType("armor")){const wornArmors=this.itemTypes.armor.filter(a=>a!==item&&a.isEquipped);for(const armor of wornArmors)updates.push({_id:armor.id,system:{equipped:{inSlot:!1}}})}else if(equipped.carryType!=="held"&&item.isOfType("weapon")&&item.shield?.isRaised){const effectIds=item.actor.itemTypes.effect.filter(e=>e.slug==="effect-raise-a-shield"||e.slug==="effect-cover"&&e.system.traits.otherTags.includes("tower-shield")&&item.shield?.isTowerShield).map(e=>e.id);await this.deleteEmbeddedDocuments("Item",effectIds)}updates.push({_id:item.id,system:{containerId:null,equipped}}),await this.updateEmbeddedDocuments("Item",updates)}}async addCustomModifier(stat,label,value,type){if(stat=stat==="armor"?"ac":stat,!this.isOfType("character","npc"))return;if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===label)){const modifierType=setHasElement(MODIFIER_TYPES,type)?type:"untyped",modifier=new ModifierPF2e({label,modifier:value,type:modifierType,custom:!0}).toObject();await this.update({[`system.customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat=stat==="armor"?"ac":stat,stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`system.customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async rollRecovery(event2){const{dying}=this.attributes;if(!dying?.value)return null;const localize=localizer("PF2E.Recovery"),recoveryDC=dying.recoveryDC,dc={label:localize("rollingDescription",{dying:dying.value,dc:"{dc}"}),value:recoveryDC+dying.value,visible:!0},notes=[new RollNotePF2e({selector:"all",text:localize("critSuccess"),outcome:["criticalSuccess"]}),new RollNotePF2e({selector:"all",text:localize("success"),outcome:["success"]}),new RollNotePF2e({selector:"all",text:localize("failure"),outcome:["failure"]}),new RollNotePF2e({selector:"all",text:localize("critFailure"),outcome:["criticalFailure"]})];return new Statistic(this,{slug:"dying-recovery",label:"PF2E.Check.Specific.Recovery",check:{type:"flat-check"}}).roll({...eventToRollParams(event2,{type:"check"}),dc,extraRollNotes:notes})}prepareSenses(data,synthetics){const preparedSenses=data.map(datum=>new CreatureSensePF2e(datum));for(const{sense,predicate,force}of synthetics.senses){if(predicate&&!predicate.test(this.getRollOptions(["all","sense"])))continue;const existing=preparedSenses.find(oldSense=>oldSense.type===sense.type);existing?force?preparedSenses.findSplice(oldSense=>oldSense===existing,sense):(sense.isMoreAcuteThan(existing)&&(existing.acuity=sense.acuity),sense.hasLongerRangeThan(existing)&&(existing.value=sense.value)):preparedSenses.push(sense)}return preparedSenses}prepareSpeed(movementType){const systemData=this.system;if(movementType==="land"){const domains=["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),landSpeed=systemData.attributes.speed;landSpeed.value=Number(landSpeed.value)||0;const fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).flatMap(d=>d()??[]);landSpeed.value=Math.max(landSpeed.value,...fromSynthetics.map(s=>s.value));const modifiers=extractModifiers(this.synthetics,domains),stat=foundry.utils.mergeObject(new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),landSpeed,{overwrite:!1}),typeLabel=game.i18n.localize("PF2E.SpeedTypesLand"),otherData={type:"land",label:game.i18n.format("PF2E.SpeedLabel",{type:typeLabel})};this.rollOptions.all["speed:land"]=!0;const merged=foundry.utils.mergeObject(stat,otherData);return Object.defineProperties(merged,{total:{get(){return stat.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:typeLabel})} ${stat.value}`,...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.signedValue}`)].join(", ")}}}),merged}else{const fastest=(()=>{const{otherSpeeds}=systemData.attributes.speed,existing=otherSpeeds.filter(s=>s.type===movementType),fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).map(d=>d()??[]).flat();return[...existing,...fromSynthetics]})().reduce((best,speed2)=>best?speed2?.value>best.value?speed2:best:speed2,null);if(!fastest)return null;const domains=fastest.derivedFromLand?[`${movementType}-speed`]:["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]),speed={type:movementType,label,value:fastest.value};fastest.source&&(speed.source=fastest.source),this.rollOptions.all[`speed:${movementType}`]=!0;const modifiers=extractModifiers(this.synthetics,domains),stat=new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),merged=foundry.utils.mergeObject(stat,speed,{overwrite:!1});return Object.defineProperties(merged,{total:{get(){return speed.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:speed.label})} ${speed.value}`].concat(stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`)).join(", ")}}}),merged}}deleteEmbeddedDocuments(embeddedName,ids,context){if(embeddedName==="Item"){const linked=ids.map(id=>this.items.get(id)).flatMap(item=>item?.getLinkedItems?.()??[]);ids.push(...linked.map(item=>item.id))}return super.deleteEmbeddedDocuments(embeddedName,[...new Set(ids)],context)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const currentHP=this.hitPoints,changedHP=changed.system.attributes?.hp;typeof changedHP?.value=="number"&&(changedHP.value=options.allowHPOverage?Math.max(0,changedHP.value):Math.clamped(changedHP.value,0,Math.max(currentHP.max-currentHP.unrecoverable,0)));const focusUpdate=changed.system.resources?.focus;if(focusUpdate&&this.system.resources){typeof focusUpdate.max=="number"&&(focusUpdate.max=Math.clamped(focusUpdate.max,0,3));const updatedPoints=Number(focusUpdate.value??this.system.resources.focus?.value)||0,enforcedMax=(Number(focusUpdate.max)||this.system.resources.focus?.max)??0;focusUpdate.value=Math.clamped(updatedPoints,0,enforcedMax)}const traitChanges=changed.system.traits;if(isObject$1(traitChanges)&&Array.isArray(traitChanges.value)){const sourceAlignmentTraits=this._source.system.traits?.value.filter(t=>["good","evil","lawful","chaotic"].includes(t)&&!(t in CONFIG.PF2E.creatureTraits));traitChanges.value=uniq(compact([traitChanges.value,sourceAlignmentTraits].flat()).sort())}return super._preUpdate(changed,options,user)}_onDelete(options,userId){super._onDelete(options,userId);for(const party of this.parties){const updater=party.primaryUpdater;game.user===updater?party.removeMembers(this.uuid):updater||(party.reset(),ui.actors.render())}}}class CharacterFeats extends Collection{static{__name(this,"CharacterFeats")}static{__name2(this,"CharacterFeats")}constructor(actor){super(),this.actor=actor;const classFeatSlots=actor.class?.grantedFeatSlots;this.bonus=new FeatGroup(actor,{id:"bonus",label:"PF2E.FeatBonusHeader"}),this.createGroup({id:"ancestryfeature",label:"PF2E.FeaturesAncestryHeader",supported:["ancestryfeature"]}),this.createGroup({id:"classfeature",label:"PF2E.FeaturesClassHeader",supported:["classfeature"]});const ancestryTraitsFilter=actor.system.details.ancestry?.countsAs.flatMap(t=>t in CONFIG.PF2E.featTraits?`traits-${t}`:[])??[];this.createGroup({id:"ancestry",label:"PF2E.FeatAncestryHeader",featFilter:ancestryTraitsFilter,supported:["ancestry"],slots:classFeatSlots?.ancestry??[]});const classTrait=(()=>{const slug=actor.class?actor.class.slug??sluggify(actor.class.name):null;return slug&&slug in CONFIG.PF2E.featTraits?slug:null})(),classFeatFilter=classTrait?this.actor.level<2?[`traits-${classTrait}`]:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?[`traits-${classTrait}`,"traits-archetype"]:[`traits-${classTrait}`,"traits-dedication"]:[];this.createGroup({id:"class",label:"PF2E.FeatClassHeader",featFilter:classFeatFilter,supported:["class"],slots:classFeatSlots?.class??[]});const evenLevels=new Array(actor.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);game.pf2e.settings.variants.fa&&this.createGroup({id:"archetype",label:"PF2E.FeatArchetypeHeader",supported:["class"],slots:evenLevels,featFilter:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?["traits-archetype"]:["traits-dedication"]});const backgroundSkillFeats=actor.background&&Object.keys(actor.background.system.items??{}).length>0?{id:actor.background.id,level:1,label:game.i18n.localize("PF2E.FeatBackgroundShort")}:null;this.createGroup({id:"skill",label:"PF2E.FeatSkillHeader",supported:["skill"],slots:compact([backgroundSkillFeats,classFeatSlots?.skill].flat())}),this.createGroup({id:"general",label:"PF2E.FeatGeneralHeader",supported:["general","skill"],slots:classFeatSlots?.general??[]}),game.pf2e.settings.campaign.enabled&&this.createGroup({id:"campaign",label:"PF2E.FeatCampaignHeader"})}bonus;createGroup(options){return this.set(options.id,new FeatGroup(this.actor,options))}async insertFeat(feat,slotData){const alreadyHasFeat=this.actor.items.has(feat.id);if(isBoonOrCurse(feat))return alreadyHasFeat?[]:this.actor.createEmbeddedDocuments("Item",[feat.toObject()]);const groupId=slotData?.groupId??"",{group,slotId}=this.get(groupId)?.isFeatValid(feat)?{group:this.get(groupId),slotId:slotData?.slotId??null}:this.#findBestLocation(feat,{requested:groupId}),isFeatValidInSlot=!!group?.isFeatValid(feat);if(groupId!=="bonus"&&!group){const badGroup=this.get(groupId);if(badGroup)return ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.InvalidCategory",{item:feat.name,category:game.i18n.format(badGroup.label)})),[]}return alreadyHasFeat&&feat.system.location&&!isFeatValidInSlot?this.actor.updateEmbeddedDocuments("Item",[{_id:feat.id,"system.location":null}]):group?.insertFeat(feat,slotId)??this.bonus.insertFeat(feat)}#findBestLocation(feat,{requested}){if(feat.isFeature)return{group:this.get(feat.category)??null,slotId:null};if(requested==="bonus")return{group:null,slotId:null};const validGroups=this.filter(c=>c.isFeatValid(feat)&&!c.isFull),group=validGroups.at(0);if(validGroups.length===1&&group){const slotId=group.slotted?Object.values(group.slots).find(slot=>!slot?.feat)?.id??null:null;return{group,slotId}}return{group:null,slotId:null}}assignToSlots(){const groupsBySlot=this.contents.filter(g=>g.slotted).reduce((previous,current)=>{for(const slot of Object.keys(current.slots))previous[slot]=current;return previous},{}),feats=this.actor.itemTypes.feat.sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats.filter(f=>!isBoonOrCurse(f))){if(feat.flags.pf2e.grantedBy&&!feat.system.location){const granter=this.actor.items.get(feat.flags.pf2e.grantedBy.id);if(granter?.isOfType("feat")&&granter.grants.includes(feat))continue}const location=feat.system.location??"";(groupsBySlot[location]??this.get(location)??this.get(feat.category))?.assignFeat(feat)||this.bonus.assignFeat(feat)}this.get("classfeature").feats.sort((a,b)=>(a.feat?.level||0)-(b.feat?.level||0))}}class FeatGroup{static{__name(this,"FeatGroup")}static{__name2(this,"FeatGroup")}actor;id;label;feats=[];slotted=!1;featFilter;supported=[];slots={};constructor(actor,options){this.actor=actor;const maxLevel=options.level??actor.level;if(this.id=options.id,this.label=options.label,this.supported=options.supported??[],this.featFilter=Array.from(new Set([this.supported.map(s=>`category-${s}`),options.featFilter??[]].flat())),options.slots){this.slotted=!0;for(const slotOption of options.slots){const slotData=typeof slotOption=="number"?{id:`${this.id}-${slotOption}`,level:slotOption,label:slotOption.toString()}:typeof slotOption=="string"?{id:`${this.id}-${sluggify(slotOption)}`,level:null,label:slotOption}:slotOption;if(typeof slotData.level=="number"&&slotData.level>maxLevel)continue;const slot={...slotData,level:slotData.level??null,children:[]};this.feats.push(slot),this.slots[slot.id]=slot}}}get isFull(){return this.slotted&&Object.values(this.slots).every(s=>!!s?.feat)}assignFeat(feat){const slotId=feat.isOfType("feat")&&feat.system.location===this.id?feat.system.level.taken?.toString()??"":feat.system.location??"",slot=this.slots[slotId];if(!slot&&this.slotted)return!1;if(slot?.feat)return console.debug(`PF2e System | Multiple feats with same index: ${feat.name}, ${slot.feat.name}`),!1;const childSlots=this.#getChildSlots(feat);if(slot)slot.feat=feat,slot.children=childSlots;else{const label=feat.category==="classfeature"?feat.system.level?.value.toString()??null:null;this.feats.push({feat,label,children:childSlots})}return feat.group=this,!0}#getChildSlots(feat){return feat?.isOfType("feat")?feat.grants.map(grant=>({id:grant.id,label:null,level:grant.system.level?.taken??null,feat:grant,children:this.#getChildSlots(grant)})):[]}isFeatValid(feat){return this.supported.length===0||tupleHasValue(this.supported,feat.category)}async insertFeat(feat,slotId=null){const slot=this.slots[slotId??""],location=this.slotted||this.id==="bonus"?slot?.id??null:this.id,existing=this.actor.items.filter(i=>isFeatLike(i)&&i.system.location===location),isFeatValidInSlot=this.isFeatValid(feat),alreadyHasFeat=this.actor.items.has(feat.id),changed=[];if(!alreadyHasFeat&&(isFeatValidInSlot||!location)){const source=foundry.utils.mergeObject(feat.toObject(),{system:{location}});changed.push(...await this.actor.createEmbeddedDocuments("Item",[source]));const label=game.i18n.localize(this.label);ui.notifications.info(game.i18n.format("PF2E.Item.Feat.Info.Added",{item:feat.name,category:label}))}const locationUpdates=this.slotted?existing.map(f=>({_id:f.id,"system.location":null,..."taken"in(feat._source.system.level??{})?{"system.level.-=taken":null}:{}})):[];return alreadyHasFeat&&isFeatValidInSlot&&locationUpdates.push({_id:feat.id,"system.location":location,...slot?.level&&feat.isOfType("feat")?{"system.level.taken":slot.level}:{}}),locationUpdates.length>0&&changed.push(...await this.actor.updateEmbeddedDocuments("Item",locationUpdates)),changed}}function isBoonOrCurse(feat){return["pfsboon","deityboon","curse"].includes(feat.category)}__name(isBoonOrCurse,"isBoonOrCurse"),__name2(isBoonOrCurse,"isBoonOrCurse");function isFeatLike(item){return"category"in item&&"location"in item.system&&"isFeat"in item&&"isFeature"in item}__name(isFeatLike,"isFeatLike"),__name2(isFeatLike,"isFeatLike");const CHARACTER_SHEET_TABS=["character","actions","inventory","spellcasting","crafting","proficiencies","feats","effects","biography","pfs"];class CharacterPF2e extends CreaturePF2e{static{__name(this,"CharacterPF2e")}static{__name2(this,"CharacterPF2e")}get allowedItemTypes(){const buildItems=["ancestry","heritage","background","class","deity","feat"];return[...super.allowedItemTypes,...buildItems,"physical","spellcastingEntry","spell","action","lore","kit"]}get keyAttribute(){return this.system.details.keyability.value||"str"}get keyAbility(){return foundry.utils.logCompatibilityWarning("`CharacterPF2e#keyAbility` is deprecated. Use `CharacterPF2e#keyAttribute` instead.",{since:"5.2.0",until:"6.0.0"}),this.keyAttribute}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get handsFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.traits.has("free-hand")?0:i.handsHeld),0,2)}get handsReallyFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.handsHeld),0,2)}get hitPoints(){return{...super.hitPoints,recoveryMultiplier:this.system.attributes.hp.recoveryMultiplier,recoveryAddend:this.system.attributes.hp.recoveryAddend}}get heroPoints(){return foundry.utils.deepClone(this.system.resources.heroPoints)}getStatistic(slug){switch(slug){case"class":case"class-dc":case"classDC":return this.classDC;case"class-spell":{const highestClass=Object.values(this.classDCs).sort((a,b)=>b.mod-a.mod).shift(),highestSpell=this.spellcasting.contents.flatMap(s=>s.statistic??[]).sort((a,b)=>b.mod-a.mod).shift();return compact([highestClass,highestSpell]).sort((a,b)=>b.mod-a.mod).shift()??null}case"base-spellcasting":return this.spellcasting.base}return this.classDCs[slug]??super.getStatistic(slug)}async getCraftingFormulas(){const{formulas}=this.system.crafting;formulas.sort((a,b)=>(a.sort??0)-(b.sort??0));const formulaMap=new Map(formulas.map(data=>[data.uuid,data]));return(await UUIDUtils.fromUUIDs(formulas.map(f=>f.uuid))).filter(i=>i instanceof ItemPF2e&&i.isOfType("physical")).map(item=>{const{dc,batchSize,deletable}=formulaMap.get(item.uuid)??{deletable:!1};return new CraftingFormula(item,{dc,batchSize,deletable})})}async getCraftingEntries(formulas){const craftingFormulas=formulas??await this.getCraftingFormulas();return Object.values(this.system.crafting.entries).filter(entry=>CraftingEntry.isValid(entry)).map(entry=>new CraftingEntry(this,craftingFormulas,entry))}async getCraftingEntry(selector){const craftingFormulas=await this.getCraftingFormulas(),craftingEntryData=this.system.crafting.entries[selector];return CraftingEntry.isValid(craftingEntryData)?new CraftingEntry(this,craftingFormulas,craftingEntryData):null}async performDailyCrafting(){const entries=(await this.getCraftingEntries()).filter(e=>e.isDailyPrep),reagentCost=entries.filter(e=>e.isAlchemical).reduce((sum,entry)=>sum+entry.reagentCost,0),reagentValue=(this.system.resources.crafting.infusedReagents.value||0)-reagentCost;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}else await this.update({"system.resources.crafting.infusedReagents.value":reagentValue});for(const item of this.inventory)item.system.temporary&&await item.delete();for(const entry of entries)for(const formula of entry.preparedCraftingFormulas){const itemSource=formula.item.toObject();itemSource.system.quantity=formula.quantity,itemSource.system.temporary=!0,itemSource.system.size=this.ancestry?.size==="tiny"?"tiny":"med",entry.isAlchemical&&(itemSource.type==="consumable"||itemSource.type==="weapon"||itemSource.type==="equipment")&&itemSource.system.traits.value.push("infused"),await this.addToInventory(itemSource)}}_initialize(options){this.familiar??=null,super._initialize(options)}prepareData(){super.prepareData(),game.ready&&this.familiar&&game.actors.has(this.familiar.id)&&this.familiar.reset({fromMaster:!0})}prepareBaseData(){super.prepareBaseData(),this.parties.size||(this.system.exploration=[]);const{flags}=this;flags.pf2e.favoredWeaponRank=0,flags.pf2e.freeCrafting??=!1,flags.pf2e.quickAlchemy??=!1,flags.pf2e.sheetTabs=foundry.utils.mergeObject(CHARACTER_SHEET_TABS.reduce((tabs,tab)=>({...tabs,[tab]:!0}),{}),flags.pf2e.sheetTabs??{}),flags.pf2e.showBasicUnarmed??=!0;const isGradual=game.pf2e.settings.variants.gab,allowedBoosts=[1,5,10,15,20].reduce((result,level)=>{const allowed=(()=>this.level===0&&level===1?4:isGradual?4-Math.clamped(level-this.level,0,4):this.level>=level?4:0)();return result[level]=allowed,result},{}),manualAttributes=Object.keys(this.system.abilities??{}).length>0;this.system.abilities=mapToObj(Array.from(ATTRIBUTE_ABBREVIATIONS),a=>[a,foundry.utils.mergeObject({mod:0},this.system.abilities?.[a]??{})]);const systemData=this.system,existingBoosts=systemData.build?.attributes?.boosts,isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);systemData.build={attributes:{manual:manualAttributes,keyOptions:[],boosts:{ancestry:[],background:[],class:null,1:existingBoosts?.[1]?.slice(0,allowedBoosts[1])??[],5:existingBoosts?.[5]?.slice(0,allowedBoosts[5])??[],10:existingBoosts?.[10]?.slice(0,allowedBoosts[10])??[],15:existingBoosts?.[15]?.slice(0,allowedBoosts[15])??[],20:existingBoosts?.[20]?.slice(0,allowedBoosts[20])??[]},allowedBoosts,flaws:{ancestry:[]},apex:isABP?systemData.build?.attributes?.apex??null:null}},systemData.saves=foundry.utils.mergeObject(mapToObj(SAVE_TYPES,t=>[t,{rank:0,ability:SAVING_THROW_DEFAULT_ATTRIBUTES[t]}]),systemData.saves??{});const{details}=this.system;for(const property of["ancestry","heritage","background","class","deity"])this[property]=null,property==="deity"?details.deities={primary:null,secondary:null,domains:{}}:property!=="background"&&(details[property]=null);details.alliance=ALLIANCES.has(details.alliance)?details.alliance:this.hasPlayerOwner?"party":"opposition";const attributes=this.system.attributes;attributes.ac={},attributes.polymorphed=!1,attributes.battleForm=!1,attributes.classDC=null,attributes.spellDC=null,attributes.classOrSpellDC={rank:0,value:0};const perception=attributes.perception??={ability:"wis",rank:0};perception.ability="wis",perception.rank??=0;const hitPoints=this.system.attributes.hp;hitPoints.recoveryMultiplier=1,hitPoints.recoveryAddend=0,attributes.ancestryhp=0,attributes.classhp=0;const{skills}=this.system;for(const key of SKILL_ABBREVIATIONS){const skill=skills[key];skill.ability=SKILL_EXPANDED[SKILL_DICTIONARY[key]].attribute,skill.armor=["dex","str"].includes(skill.ability)}attributes.familiarAbilities={value:0},systemData.proficiencies={...systemData.proficiencies,classDCs:{}},systemData.proficiencies.spellcasting??={rank:0};const{resources}=this.system;resources.heroPoints.max=3,resources.investiture={value:0,max:10},resources.focus={value:resources.focus?.value||0,max:0,cap:3},resources.crafting=foundry.utils.mergeObject({infusedReagents:{value:0,max:0}},resources.crafting??{}),resources.crafting.infusedReagents.max=0,this.system.traits.size=new ActorSizePF2e({value:"med"});const attacks=systemData.proficiencies.attacks??={};for(const category of keys.strict(CONFIG.PF2E.weaponCategories))attacks[category]={rank:attacks[category]?.rank??0,custom:!!attacks[category]?.custom,immutable:!!attacks[category]?.custom};const defenses=systemData.proficiencies.defenses??={};for(const category of ARMOR_CATEGORIES)defenses[category]={rank:defenses[category]?.rank??0,immutable:["light-barding","heavy-barding"].includes(category)};systemData.crafting=foundry.utils.mergeObject({formulas:[],entries:{}},systemData.crafting??{});for(const formula of this.system.crafting.formulas)formula.deletable=!0;this.rollOptions.all[`self:level:${this.level}`]=!0}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const attribute of Object.values(this.system.abilities))attribute.mod=Math.trunc(attribute.mod)||0;if(this.setNumericRollOptions(),this.deity?.setFavoredWeaponRank(),this.spellcasting.some(e=>e.isInnate)){const spellcasting=this.system.proficiencies.spellcasting;spellcasting.rank=Math.max(spellcasting.rank,this.level>=12?2:1)}}prepareDataFromItems(){super.prepareDataFromItems(),this.setAttributeModifiers()}prepareDerivedData(){super.prepareDerivedData(),imposeOversizedWeaponCondition(this);const systemData=this.system,{synthetics}=this;if(game.pf2e.variantRules.AutomaticBonusProgression.concatModifiers(this),systemData.details.xp.pct=Math.min(Math.round(systemData.details.xp.value*100/systemData.details.xp.max),99.5),systemData.pfs.levelBump){const params={slug:"level-bump",label:"PF2E.PFS.LevelBump",modifier:1};this.synthetics.modifiers.all.push(()=>new ModifierPF2e(params)),this.synthetics.modifiers.damage.push(()=>new ModifierPF2e(params))}{const ancestryHP=systemData.attributes.ancestryhp,classHP=systemData.attributes.classhp,hitPoints=systemData.attributes.hp,modifiers=[new ModifierPF2e("PF2E.AncestryHP",ancestryHP,"untyped")];if(game.pf2e.settings.variants.stamina){const halfClassHp=Math.floor(classHP/2);systemData.attributes.hp.sp={value:systemData.attributes.hp.sp?.value??0,max:(halfClassHp+systemData.abilities.con.mod)*this.level},systemData.resources.resolve={value:systemData.resources.resolve?.value??0,max:systemData.abilities[systemData.details.keyability.value].mod},modifiers.push(new ModifierPF2e("PF2E.ClassHP",halfClassHp*this.level,"untyped"))}else{modifiers.push(new ModifierPF2e("PF2E.ClassHP",classHP*this.level,"untyped")),delete systemData.resources.resolve;const conHP=systemData.abilities.con.mod*Math.max(this.level,1);modifiers.push(new ModifierPF2e({slug:"hp-con",label:"PF2E.AbilityCon",ability:"con",type:"ability",modifier:conHP,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,["con-based"],"hp-con")}))}const hpRollOptions=this.getRollOptions(["hp"]);modifiers.push(...extractModifiers(synthetics,["hp"],{test:hpRollOptions}));const perLevelRollOptions=this.getRollOptions(["hp-per-level"]);modifiers.push(...extractModifiers(synthetics,["hp-per-level"],{test:perLevelRollOptions}).map(clone=>(clone.modifier*=this.level,clone)));const stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hitPoints,{overwrite:!1});if(systemData.pfs.levelBump){const hitPointsBump=Math.max(10,stat.totalModifier*.1);stat.push(new ModifierPF2e("PF2E.PFS.LevelBump",hitPointsBump,"untyped"))}stat.max=stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", "),systemData.attributes.hp=stat,setHitPointsRollOptions(this)}this.prepareFeats(),this.prepareSaves(),this.prepareMartialProficiencies(),this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",rank:systemData.attributes.perception.rank,domains:["perception","all"],check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"})),this.skills=this.prepareSkills(),this.system.traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.classDC=null,this.classDCs={};for(const[slug,classDC]of Object.entries(systemData.proficiencies.classDCs)){const statistic=this.prepareClassDC(slug,classDC);systemData.proficiencies.classDCs[slug]=foundry.utils.mergeObject(classDC,statistic.getTraceData({value:"dc"})),this.classDCs[slug]=statistic,classDC.primary&&(this.classDC=statistic)}systemData.attributes.classDC=Object.values(systemData.proficiencies.classDCs).find(c=>c.primary)??null,systemData.attributes.classDC&&(systemData.attributes.classOrSpellDC=pick(systemData.attributes.classDC,["rank","value"]));const armorStatistic=this.createArmorStatistic();this.armorClass=armorStatistic.dc,systemData.attributes.ac=armorStatistic.getTraceData();const{heldShield}=this;if(heldShield?.speedPenalty){const speedPenalty=new ModifierPF2e(heldShield.name,heldShield.speedPenalty,"untyped");speedPenalty.predicate.push({not:"self:shield:ignore-speed-penalty"}),this.synthetics.modifiers.speed??=[],this.synthetics.modifiers.speed.push(()=>speedPenalty)}const speeds=systemData.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]),systemData.actions=this.prepareStrikes(),this.flags.pf2e.highestWeaponDamageDice=Math.max(...systemData.actions.filter(s=>s.ready).map(s=>s.item.system.damage.dice),0);const initiativeSkill=systemData.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData();const{crafting}=this.system.resources;crafting.infusedReagents.max=Math.floor(crafting.infusedReagents.max)||0,crafting.infusedReagents.value=Math.clamped(crafting.infusedReagents.value,0,crafting.infusedReagents.max),systemData.attributes.familiarAbilities.value>0&&(this.rollOptions.all["self:has-familiar"]=!0)}setAttributeModifiers(){const{build}=this.system;if(!build.attributes.manual){for(const section of["ancestry","background","class",1,5,10,15,20]){const boosts=build.attributes.boosts[section];if(typeof boosts=="string"){const ability=this.system.abilities[boosts];ability.mod+=ability.mod>=4?.5:1}else if(Array.isArray(boosts))for(const abbrev of boosts){const ability=this.system.abilities[abbrev];ability.mod+=ability.mod>=4?.5:1}const flaws=section==="ancestry"?build.attributes.flaws[section]:[];for(const abbrev of flaws){const ability=this.system.abilities[abbrev];ability.mod-=1}}const isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);if(build.attributes.apex&&(!isABP||this.level>=17)){const attribute=this.system.abilities[build.attributes.apex];attribute.mod=Math.max(attribute.mod+1,4)}}for(const ability of Object.values(this.system.abilities))ability.mod=Math.clamped(ability.mod,-5,10),ability.base=Math.trunc(ability.mod)}setNumericRollOptions(){const rollOptionsAll=this.rollOptions.all,perceptionRank=this.system.attributes.perception.rank;rollOptionsAll[`perception:rank:${perceptionRank}`]=!0;for(const key of ATTRIBUTE_ABBREVIATIONS){const mod=this.abilities[key].mod;rollOptionsAll[`attribute:${key}:mod:${mod}`]=!0}for(const key of SKILL_ABBREVIATIONS){const rank=this.system.skills[key].rank;rollOptionsAll[`skill:${key}:rank:${rank}`]=!0}for(const key of keys.strict(CONFIG.PF2E.weaponCategories)){const rank=this.system.proficiencies.attacks[key].rank;rollOptionsAll[`attack:${key}:rank:${rank}`]=!0}for(const key of ARMOR_CATEGORIES){const rank=this.system.proficiencies.defenses[key].rank;rollOptionsAll[`defense:${key}:rank:${rank}`]=!0}for(const key of SAVE_TYPES){const rank=this.system.saves[key].rank;rollOptionsAll[`save:${key}:rank:${rank}`]=!0}const{handsFree,handsReallyFree}=this;this.attributes.handsFree=handsFree,rollOptionsAll[`hands-free:${handsFree}`]=!0,rollOptionsAll[`hands-free:but-really:${handsReallyFree}`]=!0}createArmorStatistic(){const{synthetics,wornArmor}=this;this.system.proficiencies.defenses["light-barding"].rank||=this.traits.has("animal")&&!isReallyPC(this)?Math.max(this.system.proficiencies.defenses["light-barding"].rank,1):0;const modifiers=[],dexCapSources=[{value:1/0,source:""},...synthetics.dexterityModifierCaps];wornArmor&&dexCapSources.push({value:Number(wornArmor.dexCap??0),source:wornArmor.name});const dexCap=dexCapSources.reduce((lowest,candidate)=>lowest.value>candidate.value?candidate:lowest),dexModifier=createAttributeModifier({actor:this,attribute:"dex",domains:["all","ac","dex-based"],max:dexCap.value}),attributeModifier=modifiers.filter(m=>m.type==="ability"&&!!m.ability).reduce((best,modifier)=>modifier.modifier>best.modifier?modifier:best,dexModifier),proficiency=Object.entries(this.system.proficiencies.defenses).filter(([key,proficiency2])=>wornArmor?wornArmor.category===key?!0:proficiency2.definition?.test(wornArmor.getRollOptions("item"))??!1:key==="unarmored").map(([_k,v])=>v).reduce((best,p)=>p.rank>best.rank?p:best,{rank:0});return new ArmorStatistic(this,{rank:proficiency.rank,attribute:attributeModifier.ability,modifiers:[attributeModifier]})}prepareSaves(){const systemData=this.system,{wornArmor}=this,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),modifiers=[],selectors=[saveType,`${save.ability}-based`,"saving-throw","all"];if(wornArmor?.system.runes.resilient&&wornArmor.isInvested){const value=wornArmor.system.runes.resilient;modifiers.push(new ModifierPF2e({slug:"resilient",label:wornArmor.name,type:"item",modifier:value}))}if(saveType==="reflex"&&wornArmor?.traits.has("bulwark")){const slug="bulwark",bulwarkModifier=new ModifierPF2e({slug,type:"untyped",label:CONFIG.PF2E.armorTraits.bulwark,modifier:3,predicate:["damaging-effect"],adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,selectors,slug)});modifiers.push(bulwarkModifier),(this.synthetics.modifierAdjustments[saveType]??=[]).push({slug:"dex",test:options=>new PredicatePF2e("damaging-effect").test(options),suppress:!0})}const stat=new Statistic(this,{slug:saveType,label:saveName,attribute:save.ability,rank:save.rank,modifiers,domains:selectors,check:{type:"saving-throw"}});saves[saveType]=stat,this.system.saves[saveType]=foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData())}this.saves=saves}prepareSkills(){const systemData=this.system,{synthetics,wornArmor}=this,skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const skill=systemData.skills[shortForm],longForm=SKILL_DICTIONARY[shortForm],label=CONFIG.PF2E.skillList[longForm]??longForm,domains=[longForm,`${skill.ability}-based`,"skill-check",`${skill.ability}-skill-check`,"all"],modifiers=[],strengthRequirement=wornArmor?.strength;if(typeof strengthRequirement=="number"&&this.system.abilities.str.mod>=strengthRequirement)for(const selector of["skill-check","initiative"]){const rollOptions=this.rollOptions[selector]??={};rollOptions["armor:strength-requirement-met"]=!0}if(skill.armor&&typeof wornArmor?.strength=="number"&&wornArmor.checkPenalty<0){const slug="armor-check-penalty",armorCheckPenalty=new ModifierPF2e({slug,label:"PF2E.ArmorCheckPenalty",modifier:wornArmor.checkPenalty,type:"untyped",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,slug)});armorCheckPenalty.predicate.push({nor:["attack","armor:ignore-check-penalty"]}),["acrobatics","athletics"].includes(longForm)?armorCheckPenalty.predicate.push({nor:["armor:strength-requirement-met","armor:trait:flexible"]}):longForm==="stealth"&&wornArmor.traits.has("noisy")?armorCheckPenalty.predicate.push({nand:["armor:strength-requirement-met","armor:ignore-noisy-penalty"]}):armorCheckPenalty.predicate.push({not:"armor:strength-requirement-met"}),modifiers.push(armorCheckPenalty)}longForm==="athletics"&&modifiers.push(createForceOpenPenalty(this,domains));const statistic=new Statistic(this,{slug:longForm,label,rank:skill.rank,attribute:skill.ability,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic,this.system.skills[shortForm]=foundry.utils.mergeObject(this.system.skills[shortForm],statistic.getTraceData()),builtSkills},{});for(const loreItem of this.itemTypes.lore){const longForm=sluggify(loreItem.name),rank=loreItem.system.proficient.value,statistic=new Statistic(this,{slug:longForm,label:loreItem.name,rank,attribute:"int",domains:[longForm,"skill-check","lore-skill-check","int-skill-check","all"],lore:!0,check:{type:"skill-check"}});skills[longForm]=statistic,this.system.skills[longForm]={armor:!1,ability:"int",rank,lore:!0,itemID:loreItem.id,...statistic.getTraceData()}}return skills}prepareSpeed(movementType){const statistic=super.prepareSpeed(movementType);if(!statistic)return null;const{wornArmor}=this,basePenalty=wornArmor?.speedPenalty??0,strength=this.system.abilities.str.mod,requirement=wornArmor?.strength??null,penaltyValue=Math.min(typeof requirement=="number"&&strength>=requirement?Math.min(basePenalty+5,0):basePenalty,0),derivedFromLand=!!("derivedFromLand"in statistic&&statistic.derivedFromLand),modifierName=wornArmor?.name??"PF2E.ArmorSpeedLabel",slug="armor-speed-penalty",armorPenalty=penaltyValue&&!derivedFromLand?new ModifierPF2e({slug,label:modifierName,modifier:penaltyValue,type:"untyped",predicate:new PredicatePF2e({not:"armor:ignore-speed-penalty"}),adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all-speeds","speed",`${movementType}-speed`],slug)}):null;armorPenalty&&(statistic.push(armorPenalty),statistic.calculateTotal(new Set(this.getRollOptions(["all-speeds","speed",`${movementType}-speed`]))));const hinderingPenalty=createHinderingPenalty(this);return hinderingPenalty&&statistic.push(hinderingPenalty),statistic}prepareFeats(){this.pfsBoons=[],this.deityBoonsCurses=[],this.feats=new CharacterFeats(this);for(const section of game.pf2e.settings.campaign.sections)this.feats.createGroup(section);this.feats.assignToSlots();const feats=this.itemTypes.feat.filter(f=>["pfsboon","deityboon","curse"].includes(f.category)).sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats)feat.category==="pfsboon"?this.pfsBoons.push(feat):this.deityBoonsCurses.push(feat)}prepareClassDC(slug,classDC){classDC.ability??="str",classDC.rank??=0,classDC.primary??=!1;const classNames=CONFIG.PF2E.classTraits;return classDC.label=classDC.label??classNames[slug]??slug.titleCase(),new Statistic(this,{slug,label:classDC.label,attribute:classDC.ability,rank:classDC.rank,domains:["class",slug,"all"],check:{type:"check"}})}prepareStrikes({includeBasicUnarmed=!0}={}){const{itemTypes,synthetics}=this,handwrapsSlug="handwraps-of-mighty-blows",handwraps=itemTypes.weapon.find(w=>w.slug===handwrapsSlug&&w.category==="unarmed"&&w.isEquipped&&w.isInvested),unarmedRunes=foundry.utils.deepClone(handwraps?._source.system.runes)??{potency:0,striking:0,property:[]},basicUnarmed=includeBasicUnarmed?(()=>{const source={_id:"xxPF2ExUNARMEDxx",name:game.i18n.localize("PF2E.WeaponTypeUnarmed"),type:"weapon",img:"icons/skills/melee/unarmed-punch-fist.webp",system:{slug:"basic-unarmed",category:"unarmed",baseItem:null,bonus:{value:0},damage:{dice:1,die:"d4",damageType:"bludgeoning"},equipped:{carryType:"worn",inSlot:!0,handsHeld:0},group:"brawling",traits:{value:["agile","finesse","nonlethal","unarmed"]},usage:{value:"worngloves"},runes:unarmedRunes}};return new WeaponPF2e(source,{parent:this})})():null;if(handwraps){for(const[slug,weapon]of synthetics.strikes.entries())if(weapon.category==="unarmed"){const clone=weapon.clone({system:{runes:unarmedRunes}},{keepId:!0});synthetics.strikes.set(slug,clone),clone.name=clone._source.name}}const ammos=[...itemTypes.consumable.filter(i=>i.category==="ammo"&&!i.isStowed),...itemTypes.weapon.filter(w=>w.system.usage.canBeAmmo)],offensiveCategories=keys.strict(CONFIG.PF2E.weaponCategories),weapons=compact([itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[],this.itemTypes.shield.filter(s=>!s.isStowed&&!s.isBroken&&!s.isDestroyed).map(s=>s.generateWeapon())].flat()),{handsReallyFree}=this;return weapons.map(w=>this.prepareStrike(w,{categories:offensiveCategories,handsReallyFree,ammos})).sort((a,b)=>a.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/g,"").localeCompare(b.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/gi,""),game.i18n.lang)).sort((a,b)=>a.slug==="basic-unarmed"?1:b.slug==="basic-unarmed"?-1:0).sort((a,b)=>a.item.isHeld===b.item.isHeld?0:a.item.isHeld?-1:1).sort((a,b)=>a.ready===b.ready?0:a.ready?-1:1)}prepareStrike(weapon,{categories,handsReallyFree,ammos=[]}){const{synthetics}=this,modifiers=[],systemData=this.system,strikeAdjustments=[synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(weapon.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustWeapon?.(weapon);const weaponRollOptions=weapon.getRollOptions("item"),weaponTraits2=weapon.traits,{proficiencies}=systemData,categoryRank=proficiencies.attacks[weapon.category]?.rank??0,groupRank=proficiencies.attacks[`weapon-group-${weapon.group}`]?.rank??0,baseWeapon=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType,baseWeaponRank=proficiencies.attacks[`weapon-base-${baseWeapon}`]?.rank??0,equivalentCategories=Object.values(proficiencies.attacks).flatMap(p=>p&&"sameAs"in p&&(p.definition?.test(weaponRollOptions)??!0)?`item:category:${p.sameAs}`:[]),weaponProficiencyOptions=new Set(weaponRollOptions.concat(equivalentCategories)),syntheticRanks=compact(Object.values(proficiencies.attacks)).filter(p=>p.immutable&&(p.definition?.test(weaponProficiencyOptions)??!0)).map(p=>p.rank),proficiencyRank=Math.max(categoryRank,groupRank,baseWeaponRank,...syntheticRanks),meleeOrRanged=weapon.isMelee?"melee":"ranged",baseOptions=new Set(["action:strike","self:action:slug:strike",`item:proficiency:rank:${proficiencyRank}`,PROFICIENCY_RANK_OPTION[proficiencyRank],...weaponTraits2,meleeOrRanged]),attackDomains=getStrikeAttackDomains(weapon,proficiencyRank,baseOptions),{defaultAttribute}=weapon;modifiers.push(createAttributeModifier({actor:this,attribute:defaultAttribute,domains:attackDomains})),weapon.isMelee&&weaponTraits2.has("finesse")&&modifiers.push(createAttributeModifier({actor:this,attribute:"dex",domains:attackDomains})),weapon.isRanged&&weaponTraits2.has("brutal")&&modifiers.push(createAttributeModifier({actor:this,attribute:"str",domains:attackDomains})),modifiers.push(createProficiencyModifier({actor:this,rank:proficiencyRank,domains:attackDomains}));const initialRollOptions=new Set([...baseOptions,...this.getRollOptions(attackDomains),...weaponRollOptions]),ABP=game.pf2e.variantRules.AutomaticBonusProgression;if(weapon.group==="bomb"&&!ABP.isEnabled(this)){const attackBonus=Number(weapon.system.bonus?.value)||0;attackBonus!==0&&modifiers.push(new ModifierPF2e("PF2E.ItemBonusLabel",attackBonus,"item"))}const weaponPotency=(()=>{const potency=attackDomains.flatMap(key=>foundry.utils.deepClone(synthetics.weaponPotency[key]??[])).filter(wp=>wp.predicate.test(initialRollOptions));return weapon.system.runes.potency>0&&potency.push({label:"PF2E.Item.Weapon.Rune.Potency",bonus:weapon.system.runes.potency,type:"item",predicate:new PredicatePF2e}),potency.length>0?potency.reduce((highest,current)=>highest.bonus>current.bonus?highest:current):null})();weaponPotency&&(modifiers.push(new ModifierPF2e(weaponPotency.label,weaponPotency.bonus,weaponPotency.type)),!weapon.isMagical&&(weaponPotency.type==="item"||!ABP.isEnabled(weapon.actor))&&weapon.system.traits.value.push("magical"),weapon.flags.pf2e.attackItemBonus=weaponPotency.bonus);const shoddyPenalty=createShoddyPenalty(this,weapon,attackDomains);shoddyPenalty&&modifiers.push(shoddyPenalty),modifiers.push(...PCAttackTraitHelpers.createAttackModifiers({item:weapon,domains:attackDomains}),...extractModifiers(synthetics,attackDomains,{injectables:{weapon},resolvables:{weapon}}));const auxiliaryActions=[],isRealItem=this.items.has(weapon.id);if(weapon.system.traits.toggles.modular.options.length>0&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"modular"})),isRealItem&&weapon.category!=="unarmed"){const traitsArray=weapon.system.traits.value,{usage}=weapon.system,weaponAsShield=weapon.shield,canWield2H=usage.hands===2||usage.hands===1&&this.handsFree>0&&!!weaponAsShield||traitsArray.some(t=>t.startsWith("fatal-aim"))||traitsArray.some(t=>t.startsWith("two-hand"));switch(weapon.carryType){case"held":{if(weaponAsShield){const hasShieldRaised=!!this.rollOptions.all["self:effect:raise-a-shield"],hasGreaterCover=!!this.rollOptions.all["self:cover-level:greater"];if(!hasShieldRaised)auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"raise-a-shield"}));else if(weaponAsShield.isTowerShield&&weaponAsShield.isRaised){const action22=hasGreaterCover?"end-cover":"take-cover",annotation="tower-shield";auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:action22,annotation}))}}weapon.handsHeld===2?auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"grip",hands:1})):weapon.handsHeld===1&&canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"grip",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"sheathe",hands:0})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"drop",hands:0}));break}case"worn":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:2}));break}case"stowed":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"retrieve",hands:1}));break}case"dropped":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:2}));break}}}const weaponSlug=weapon.slug??sluggify(weapon.name),flavor=this.getStrikeDescription(weapon),rollOptions=[...this.getRollOptions(attackDomains),...weaponRollOptions,...weaponTraits2,meleeOrRanged],strikeStat=new StatisticModifier(weaponSlug,modifiers,rollOptions),altUsages=weapon.getAltUsages().map(w=>this.prepareStrike(w,{categories,handsReallyFree})),versatileLabel=__name2(damageType=>{switch(damageType){case"bludgeoning":return CONFIG.PF2E.weaponTraits["versatile-b"];case"piercing":return CONFIG.PF2E.weaponTraits["versatile-p"];case"slashing":return CONFIG.PF2E.weaponTraits["versatile-s"];default:return CONFIG.PF2E.weaponTraits[`versatile-${damageType}`]??CONFIG.PF2E.damageTypes[damageType]}},"versatileLabel"),handsAvailable=!weapon.system.graspingAppendage||handsReallyFree>0,actionTraits2=["attack",weapon.baseType==="alchemical-bomb"?"manipulate":[]].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(weapon,actionTraits2);const ready2=weapon.isEquipped&&handsAvailable||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&handsReallyFree>0,action2=foundry.utils.mergeObject(strikeStat,{label:weapon.name,quantity:weapon.quantity,ready:ready2,domains:attackDomains,visible:weapon.slug!=="basic-unarmed"||this.flags.pf2e.showBasicUnarmed,glyph:"A",item:weapon,type:"strike",...flavor,options:Array.from(baseOptions),traits:actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),handsAvailable,weaponTraits:Array.from(weaponTraits2).map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits)).sort((a,b)=>a.label.localeCompare(b.label)),variants:[],selectedAmmoId:weapon.system.selectedAmmoId,altUsages,auxiliaryActions,versatileOptions:weapon.system.traits.toggles.versatile.options.map(o=>({value:o,selected:weapon.system.traits.toggles.versatile.selection===o,label:versatileLabel(o),glyph:DAMAGE_TYPE_ICONS[o]}))});if(action2.versatileOptions.length>0&&action2.versatileOptions.unshift({value:weapon.system.damage.damageType,selected:weapon.system.traits.toggles.versatile.selection===null,label:CONFIG.PF2E.damageTypes[weapon.system.damage.damageType],glyph:DAMAGE_TYPE_ICONS[weapon.system.damage.damageType]}),weapon.requiresAmmo){const compatible=ammos.filter(a=>a.isAmmoFor(weapon)),incompatible=ammos.filter(a=>!a.isAmmoFor(weapon)),{ammo}=weapon,selected=ammo?{id:ammo.id,compatible:ammo.isAmmoFor(weapon)}:null;action2.ammunition={compatible,incompatible,selected}}action2.breakdown=action2.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ");const maps=calculateMAPs(weapon,{domains:attackDomains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),createMapLabel=__name2(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],new Set(rollOptions));const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(action2.totalModifier+penalty),penalty})},"createMapLabel"),labels=[()=>signedInteger(action2.totalModifier),()=>createMapLabel("map1"),()=>createMapLabel("map2")],checkModifiers=[(statistic,otherModifiers)=>new CheckModifier("strike",statistic,otherModifiers),(statistic,otherModifiers)=>new CheckModifier("strike-map1",statistic,[...otherModifiers,createMapModifier("map1")]),(statistic,otherModifiers)=>new CheckModifier("strike-map2",statistic,[...otherModifiers,createMapModifier("map2")])];action2.variants=[0,1,2].map(mapIncreases=>({get label(){return labels[mapIncreases]()},roll:async(params={})=>{if(params.options??=[],params.consumeAmmo??=weapon.requiresAmmo,weapon.requiresAmmo&¶ms.consumeAmmo&&!weapon.ammo)return ui.notifications.warn(game.i18n.format("PF2E.Strike.Ranged.NoAmmo",{weapon:weapon.name,actor:this.name})),null;const context=await this.getCheckContext({item:weapon,domains:attackDomains,statistic:action2,target:{token:params.target??game.user.targets.first()??null},defense:"armor",options:new Set([...baseOptions,...params.options]),viewOnly:params.getFormula,traits:actionTraits2});if(action2.traits=context.traits.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=context.self.item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}for(const rule of this.rules.filter(r=>!r.ignored))rule.beforeRoll?.(attackDomains,context.options);const dc=params.dc??context.dc,notes=extractNotes(context.self.actor.synthetics.rollNotes,attackDomains),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,attackDomains,context.options),dosAdjustments=[getPropertyRuneDegreeAdjustments(context.self.item),extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,attackDomains)].flat(),title=game.i18n.format(weapon.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:weapon.name}),checkContext={type:"attack-roll",identifier:`${weapon.id}.${weaponSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,target:context.target,item:context.self.item,altUsage:params.altUsage??null,damaging:context.self.item.dealsDamage,domains:attackDomains,options:context.options,notes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments,mapIncreases};if(params.consumeAmmo&&!this.consumeAmmo(context.self.item,params))return null;const check=checkModifiers[mapIncreases](context.self.statistic??action2,context.self.modifiers),roll=await CheckPF2e.roll(check,checkContext,params.event,params.callback);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains:attackDomains,rollOptions:context.options});return roll}})),action2.attack=action2.roll=action2.variants[0].roll;for(const method of["damage","critical"])action2[method]=async(params={})=>{const domains=getStrikeDamageDomains(weapon,proficiencyRank);params.options=new Set(params.options??[]);const targetToken=params.target??game.user.targets.first()??null,context=await this.getDamageRollContext({item:weapon,viewOnly:params.getFormula??!1,statistic:action2,target:{token:targetToken},domains,outcome:method==="damage"?"success":"criticalSuccess",options:new Set([...baseOptions,...params.options]),traits:actionTraits2,checkContext:params.checkContext});if(!context.self.item.dealsDamage)return params.getFormula?"":(ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null);const outcome=method==="damage"?"success":"criticalSuccess",{self,target,options}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options,domains,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.calculate({weapon:context.self.item,actor:context.self.actor,weaponPotency,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)};return action2}getStrikeDescription(weapon){const flavor={description:"PF2E.Strike.Default.Description",criticalSuccess:"PF2E.Strike.Default.CriticalSuccess",success:"PF2E.Strike.Default.Success"},traits=weapon.traits;return traits.has("unarmed")?(flavor.description="PF2E.Strike.Unarmed.Description",flavor.success="PF2E.Strike.Unarmed.Success"):[...traits].some(trait=>trait.startsWith("thrown-")||trait==="combination")?(flavor.description="PF2E.Strike.Combined.Description",flavor.success="PF2E.Strike.Combined.Success"):weapon.isMelee?(flavor.description="PF2E.Strike.Melee.Description",flavor.success="PF2E.Strike.Melee.Success"):(flavor.description="PF2E.Strike.Ranged.Description",flavor.success="PF2E.Strike.Ranged.Success"),flavor}async getRollContext(params){const context=await super.getRollContext(params);return params.statistic instanceof StatisticModifier&&context.self.item?.isOfType("weapon")&&PCAttackTraitHelpers.adjustWeapon(context.self.item),context}consumeAmmo(weapon,params){const ammo=weapon.ammo;if(ammo){if(ammo.quantity<1)return ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.NotEnoughAmmo")),!1;{const existingCallback=params.callback;return params.callback=async roll=>{existingCallback?.(roll),await weapon.consumeAmmo()},!0}}else return!0}prepareMartialProficiencies(){for(const key of["attacks","defenses"]){const proficiencies=this.system.proficiencies[key],linkedProficiencies=Object.values(proficiencies).filter(p=>!!p?.sameAs&&p.sameAs in proficiencies);for(const proficiency of linkedProficiencies){const category=proficiencies[proficiency.sameAs??""];proficiency.rank=(()=>{const maxRankIndex=PROFICIENCY_RANKS.indexOf(proficiency.maxRank??"legendary");return Math.min(category?.rank??0,maxRankIndex)})()}const allProficiencies=Object.entries(proficiencies);for(const[_key,proficiency]of allProficiencies){if(!proficiency)continue;const duplicates=allProficiencies.flatMap(([k,p])=>p&&proficiency!==p&&proficiency.rank>=p.rank&&"definition"in proficiency&&"definition"in p&&proficiency.sameAs===p.sameAs&&equals(p.definition??[],[...proficiency.definition??[]])?k:[]);for(const duplicate of duplicates)delete proficiencies[duplicate];const proficiencyBonus=createProficiencyModifier({actor:this,rank:proficiency.rank,domains:[]});proficiency.value=proficiencyBonus.value,proficiency.breakdown=`${proficiencyBonus.label} ${signedInteger(proficiencyBonus.value)}`}}}async toggleInvested(itemId){const item=this.inventory.get(itemId);if(!item?.traits.has("invested"))throw ErrorPF2e("Unexpected error toggling item investment");const invested=item.isInvested;if(!invested&&!item.isEquipped){const newCarryType=item.system.usage.type==="carried"?"worn":item.system.usage.type;await this.adjustCarryType(item,{carryType:newCarryType,handsHeld:item.system.usage.hands,inSlot:!0})}return!!await item.update({"system.equipped.invested":!invested})}async addAttackProficiency(key){const currentProficiencies=this.system.proficiencies.attacks;if(key in currentProficiencies)return;const newProficiency={rank:1,custom:!0};await this.update({[`system.proficiencies.attacks.${key}`]:newProficiency})}async _preUpdate(changed,options,user){const systemData=this.system;if(typeof changed.system?.resources?.crafting?.infusedReagents?.value=="number"&&(changed.system.resources.crafting.infusedReagents.value=Math.max(0,Math.floor(changed.system.resources.crafting.infusedReagents.value))||0),changed.system?.details?.level||changed.system?.build?.attributes){const level=changed.system?.details?.level;typeof level?.value=="number"&&(level.value=Math.clamped(Number(level.value)||0,0,30)||0);const hpMaxDifference=this.clone(changed).hitPoints.max-this.hitPoints.max;if(hpMaxDifference!==0){options.allowHPOverage=!0;const currentHP=this.hitPoints.value,newHP=Math.max(currentHP+hpMaxDifference,currentHP===0?0:1);changed.system=foundry.utils.mergeObject(changed.system??{},{attributes:{hp:{value:newHP}}})}}game.pf2e.settings.variants.stamina&&(changed.system?.attributes?.hp?.sp&&(changed.system.attributes.hp.sp.value=Math.floor(Math.clamped(changed.system.attributes.hp.sp?.value??0,0,systemData.attributes.hp.sp?.max??0))||0),changed.system?.resources?.resolve&&(changed.system.resources.resolve.value=Math.floor(Math.clamped(changed.system.resources.resolve.value??0,0,systemData.resources.resolve?.max??0))||0));const xp=changed.system?.details?.xp??{};typeof xp.value=="number"&&(xp.value=Math.max(xp.value,0)),typeof xp.max=="number"&&(xp.max=Math.max(xp.max,1));const newLevel=changed.system?.details?.level?.value??this.level,actorClass=this.class;if(actorClass&&newLevel!==this.level){const current=this.itemTypes.feat.filter(feat=>feat.category==="classfeature");if(newLevel>this.level){const classFeaturesToCreate=(await actorClass.createGrantedItems({level:newLevel})).filter(feature=>feature.system.level.value>this.level&&!current.some(currentFeature=>currentFeature.sourceId===feature.flags.core?.sourceId)).map(i=>i.toObject());await this.createEmbeddedDocuments("Item",classFeaturesToCreate,{keepId:!0,render:!1})}else if(newLevel<this.level){const classFeaturestoDelete=current.filter(f=>f.level>newLevel&&!f.grantedBy).map(f=>f.id);await this.deleteEmbeddedDocuments("Item",classFeaturestoDelete,{render:!1})}}for(const property of["playerNumber","characterNumber"])if(typeof changed.system?.pfs?.[property]=="number"){const[min,max]=property==="playerNumber"?[1,9999999]:[2001,9999];changed.system.pfs[property]=Math.clamped(changed.system.pfs[property]||0,min,max)}else changed.system?.pfs&&changed.system.pfs[property]!==null&&(changed.system.pfs[property]=this.system.pfs[property]??null);return super._preUpdate(changed,options,user)}}class FamiliarPF2e extends CreaturePF2e{static{__name(this,"FamiliarPF2e")}static{__name2(this,"FamiliarPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action"]}get master(){if(!game.ready||!this.system.master.id)return null;const master=game.actors.get(this.system.master.id??"");return master?.isOfType("character")?(master.familiar??=this,master):null}get masterAttributeModifier(){return this.system.master.ability||="cha",this.master?.system.abilities[this.system.master.ability].mod??0}get masterAbilityModifier(){return this.masterAttributeModifier}get combatant(){return this.master?.combatant??null}reset({fromMaster=!1}={}){super.reset(),fromMaster&&this.sheet.render()}prepareBaseData(){const systemData=this.system;systemData.details.level={value:0},systemData.traits={value:["minion"],senses:[{type:"lowLightVision",label:CONFIG.PF2E.senses.lowLightVision,value:""}],size:new ActorSizePF2e({value:"tiny"})},super.prepareBaseData();const isItemBonus=new PredicatePF2e(["bonus:type:item"]);this.synthetics.modifierAdjustments.all.push({slug:null,test:options=>isItemBonus.test(options),suppress:!0}),systemData.attributes.flanking.canFlank=!1,systemData.attributes.perception={},systemData.attributes.speed={value:25,label:game.i18n.localize("PF2E.SpeedTypesLand"),otherSpeeds:[]},systemData.skills={},systemData.saves={fortitude:{},reflex:{},will:{}},systemData.traits=foundry.utils.mergeObject(systemData.traits,{dv:[],di:[],dr:[]});const{master}=this;systemData.details.level.value=master?.level??0,this.rollOptions.all[`self:level:${this.level}`]=!0,systemData.details.alliance=master?.alliance??"party",master&&(this.flags.pf2e.rollOptions.all=foundry.utils.mergeObject(this.flags.pf2e.rollOptions.all,createEncounterRollOptions(master)))}prepareRuleElements(){return this.master?super.prepareRuleElements():[]}prepareDerivedData(){super.prepareDerivedData();const{master}=this,systemData=this.system,{attributes,traits}=systemData;traits.value=[...this.traits].sort();const{level,masterAttributeModifier}=this,masterLevel=game.pf2e.settings.variants.pwol.enabled?0:level,{synthetics}=this,speeds=attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const hitPoints=new HitPointsStatistic(this,{baseMax:level*5});this.system.attributes.hp=hitPoints.getTraceData(),setHitPointsRollOptions(this);const masterModifier=master?new ModifierPF2e({label:"PF2E.Actor.Familiar.Master.ArmorClass",slug:"base",modifier:master.armorClass.modifiers.filter(m=>m.enabled&&!["status","circumstance"].includes(m.type)).reduce((total,modifier)=>total+modifier.value,0)}):null,statistic=new ArmorStatistic(this,{modifiers:compact([masterModifier])});this.armorClass=statistic.dc,systemData.attributes.ac=statistic.getTraceData(),this.saves=SAVE_TYPES.reduce((partialSaves,saveType)=>{const source=master?.saves[saveType]?.modifiers.filter(m=>!["status","circumstance"].includes(m.type))??[],totalMod=applyStackingRules(source),attribute=CONFIG.PF2E.savingThrowDefaultAttributes[saveType],selectors=[saveType,`${attribute}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:game.i18n.localize(CONFIG.PF2E.saves[saveType]),domains:selectors,modifiers:[new ModifierPF2e(`PF2E.MasterSavingThrow.${saveType}`,totalMod,"untyped")],check:{type:"saving-throw"}});return{...partialSaves,[saveType]:stat}},{}),this.system.saves=SAVE_TYPES.reduce((partial,saveType)=>({...partial,[saveType]:this.saves[saveType].getTraceData()}),{}),traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.attackStatistic=new Statistic(this,{slug:"attack-roll",label:"PF2E.Familiar.AttackRoll",modifiers:[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")],check:{type:"attack-roll"}}),this.system.attack=this.attackStatistic.getTraceData();{const domains=["perception","wis-based","all"],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped"),new ModifierPF2e(`PF2E.MasterAbility.${systemData.master.ability}`,masterAttributeModifier,"untyped")];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",domains,modifiers,check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const longForm=SKILL_DICTIONARY[shortForm],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")];if(["acr","ste"].includes(shortForm)){const label2=`PF2E.MasterAbility.${systemData.master.ability}`;modifiers.push(new ModifierPF2e(label2,masterAttributeModifier,"untyped"))}const attribute=SKILL_EXPANDED[longForm].attribute,domains=[longForm,`${attribute}-based`,"skill-check","all"],label=CONFIG.PF2E.skills[shortForm]??longForm,statistic2=new Statistic(this,{slug:longForm,label,attribute,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic2,this.system.skills[shortForm]=statistic2.getTraceData(),builtSkills},{})}_onDelete(options,userId){this.master&&(this.master.familiar=null),super._onDelete(options,userId)}}const identifySkills=new Map([["aberration",["occultism"]],["animal",["nature"]],["astral",["occultism"]],["beast",["arcana","nature"]],["celestial",["religion"]],["construct",["arcana","crafting"]],["dragon",["arcana"]],["elemental",["arcana","nature"]],["ethereal",["occultism"]],["fey",["nature"]],["fiend",["religion"]],["fungus",["nature"]],["humanoid",["society"]],["monitor",["religion"]],["ooze",["occultism"]],["plant",["nature"]],["spirit",["occultism"]],["undead",["religion"]]]);function toKnowledgeDC(dc,rarity,loreAdjustment="normal"){const rarityAdjustment=rarityToDCAdjustment(rarity),start=combineDCAdjustments(rarityAdjustment,loreAdjustment),progression=createDifficultyScale(dc,start);return{dc:adjustDC(dc,start),progression,start}}__name(toKnowledgeDC,"toKnowledgeDC"),__name2(toKnowledgeDC,"toKnowledgeDC");function creatureIdentificationDCs(creature,{pwol=!1}={}){const{level,rarity}=creature,dc=calculateDC(level,{pwol}),traits=creature.system.traits.value;return{skills:Array.from(new Set(traits.flatMap(t=>identifySkills.get(t)??[]))),standard:toKnowledgeDC(dc,rarity,"normal"),lore:[toKnowledgeDC(dc,rarity,"easy"),toKnowledgeDC(dc,rarity,"very-easy")]}}__name(creatureIdentificationDCs,"creatureIdentificationDCs"),__name2(creatureIdentificationDCs,"creatureIdentificationDCs");class NPCPF2e extends CreaturePF2e{static{__name(this,"NPCPF2e")}static{__name2(this,"NPCPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","spellcastingEntry","spell","action","melee","lore"]}get baseLevel(){return this._source.system.details.level.value}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get description(){return this.system.details.publicNotes}get isElite(){return this.attributes.adjustment==="elite"}get isWeak(){return this.attributes.adjustment==="weak"}get identificationDCs(){const pwol=game.pf2e.settings.variants.pwol.enabled;return creatureIdentificationDCs(this,{pwol})}get isLootable(){const npcsAreLootable=game.settings.get("pf2e","automation.lootableNPCs");return this.isDead&&(npcsAreLootable||this.flags.pf2e.lootable)}get visible(){return super.visible&&this.prototypeToken.actorLink||this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.isLootable}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.lootable??=!1;const systemData=this.system;systemData.actions=[];for(const key of SAVE_TYPES)systemData.saves[key].ability=CONFIG.PF2E.savingThrowDefaultAttributes[key];const{attributes,details}=systemData;attributes.perception.ability="wis",attributes.reach={base:SIZE_TO_REACH[this.size],manipulate:SIZE_TO_REACH[this.size]},details.alliance===void 0&&(details.alliance=this.hasPlayerOwner?"party":"opposition"),attributes.hp.negativeHealing=systemData.traits.value.includes("undead"),attributes.flanking.flankable=!systemData.traits.value.includes("troop");const{level}=details;level.base=Math.clamped(level.value,-1,100),level.value=this.isElite?level.base+1:this.isWeak?level.base-1:level.base,this.rollOptions.all[`self:level:${level.value}`]=!0,attributes.spellDC=null,attributes.classDC=(()=>{const pwol=game.pf2e.settings.variants.pwol.enabled,levelBasedDC=calculateDC(level.base,{pwol,rarity:this.rarity});return{value:this.isElite?levelBasedDC+2:this.isWeak?levelBasedDC-2:levelBasedDC}})(),attributes.classOrSpellDC={value:attributes.classDC.value},this.system.spellcasting=foundry.utils.mergeObject({rituals:{dc:0}},this.system.spellcasting),this.system.resources.focus=foundry.utils.mergeObject({value:0,max:0,cap:3},this.system.resources.focus)}prepareDerivedData(){super.prepareDerivedData();const{system}=this,{synthetics}=this,{modifierAdjustments}=synthetics,baseLevel=this.system.details.level.base;this.synthetics.modifiers.hp??=[],this.isElite?(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base+2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.EliteLabel",this.getHpAdjustment(baseLevel,"elite"),"untyped"))):this.isWeak&&(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base-2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.WeakLabel",this.getHpAdjustment(baseLevel,"weak")*-1,"untyped"))),system.details.level.base=baseLevel;for(const ability of Object.values(this.system.abilities))ability.mod=Math.trunc(Number(ability.mod))||0;{const base=system.attributes.hp.max,modifiers=[extractModifiers(this.synthetics,["hp"],{test:this.getRollOptions(["hp"])}),extractModifiers(this.synthetics,["hp-per-level"],{test:this.getRollOptions(["hp-per-level"])}).map(modifier=>(modifier.modifier*=this.level,modifier))].flat(),hpData=foundry.utils.deepClone(system.attributes.hp),stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hpData,{overwrite:!1});stat.base=base,stat.max=stat.max+stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=[game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base}),...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)].join(", "),system.attributes.hp=stat,setHitPointsRollOptions(this)}const speeds=system.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.ac.value-10,adjustments:extractModifierAdjustments(modifierAdjustments,["all","ac","dex-based"],"base")})],details:system.attributes.ac.details});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves();{const domains=["perception","wis-based","all"];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.perception.value,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"perception-check"}}),system.attributes.perception=foundry.utils.mergeObject(system.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=this.prepareSkills();const generatedMelee=Array.from(synthetics.strikes.values()).flatMap(w=>w.toNPCAttacks({keepId:!0}));for(const item of[...this.itemTypes.melee,...generatedMelee])system.actions.push(strikeFromMeleeItem(item));const initiativeSkill=system.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData()}prepareSaves(){const systemData=this.system,{modifierAdjustments}=this.synthetics,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value,ability=save.ability,domains=[saveType,`${ability}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:saveName,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"saving-throw"}});saves[saveType]=stat,foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData()),systemData.saves[saveType].base=base}this.saves=saves}prepareSkills(){const{system}=this,{modifierAdjustments}=this.synthetics;system.skills={};function createTrace(stat,item){const{attribute,shortForm}=objectHasKey(SKILL_EXPANDED,stat.slug)?SKILL_EXPANDED[stat.slug]:{attribute:"int",shortForm:stat.slug};system.skills[shortForm]={...stat.getTraceData(),base:item?.system.mod.value,isLore:!!stat.lore,itemID:item?.id,ability:attribute,visible:stat.proficient,variants:Object.values(item?.system.variants??{})}}__name(createTrace,"createTrace"),__name2(createTrace,"createTrace");const skills={};for(const skill of SKILL_LONG_FORMS){const{attribute,shortForm}=SKILL_EXPANDED[skill],domains=[skill,`${attribute}-based`,"skill-check",`${attribute}-skill-check`,"all"],name2=game.i18n.localize(`PF2E.Skill${SKILL_DICTIONARY[shortForm].capitalize()}`),statistic=new Statistic(this,{slug:skill,label:name2,attribute,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.abilities[attribute].mod,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],lore:!1,proficient:!1,check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic)}for(const item of this.itemTypes.lore){const skill=sluggify(item.name),attribute=objectHasKey(SKILL_EXPANDED,skill)?SKILL_EXPANDED[skill].attribute:"int",label=objectHasKey(CONFIG.PF2E.skillList,skill)?CONFIG.PF2E.skillList[skill]:item.name,base=item.system.mod.value,domains=[skill,`${attribute}-based`,"skill-check","lore-skill-check",`${attribute}-skill-check`,"all"],statistic=new Statistic(this,{slug:skill,label,attribute,lore:!objectHasKey(SKILL_EXPANDED,skill),domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic,item)}return skills}async getAttackEffects(attack){const notes=[];attack.description&¬es.push(new RollNotePF2e({selector:"all",visibility:"gm",text:attack.description}));const formatItemName=__name2(item=>{if(item.isOfType("consumable")){const button=createHTMLElement("button",{dataset:{action:"consume",item:item.id}});return button.style.width="auto",button.style.lineHeight="14px",button.innerHTML=game.i18n.localize("PF2E.ConsumableUseLabel"),`${item.name} - ${game.i18n.localize("TYPES.Item.consumable")} (${item.quantity}) ${button.outerHTML}`}return item.name},"formatItemName"),formatNoteText=__name2(item=>{const rollData=item.getRollData();return TextEditor.enrichHTML(item.description,{rollData,async:!0})},"formatNoteText");for(const attackEffect of attack.attackEffects){const item=this.items.find(i=>i.type!=="melee"&&(i.slug??sluggify(i.name))===sluggify(attackEffect));if(item){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(item),text:await formatNoteText(item)});notes.push(note)}else{const packItem=(await game.packs.get("pf2e.bestiary-ability-glossary-srd",{strict:!0}).getDocuments({system:{slug:attackEffect}}))[0];if(packItem instanceof ItemPF2e){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(packItem),text:await formatNoteText(packItem)});notes.push(note)}}}return notes}getHpAdjustment(level,adjustment){if(adjustment==="elite"){if(level>=20)return 30;if(level<=19&&level>=5)return 20;if(level<=4&&level>=2)return 15;if(level<=1)return 10}else if(adjustment==="weak"){if(level>=21)return 30;if(level<=20&&level>=6)return 20;if(level<=5&&level>=3)return 15;if(level===1||level===2)return 10}return 0}async applyAdjustment(adjustment){const{isElite,isWeak}=this;if(isElite&&adjustment==="elite"||isWeak&&adjustment==="weak"||!isElite&&!isWeak&&!adjustment)return;const currentHPAdjustment=(()=>isElite?this.getHpAdjustment(this.baseLevel,"elite"):isWeak?this.getHpAdjustment(this.baseLevel,"weak"):0)(),newHPAdjustment=this.getHpAdjustment(this.baseLevel,adjustment),currentHP=this.system.attributes.hp.value,maxHP=this.system.attributes.hp.max,newHP=(()=>{if(isElite){if(adjustment==="weak")return currentHP-currentHPAdjustment-newHPAdjustment;if(!adjustment)return currentHP-currentHPAdjustment}else if(isWeak){if(adjustment==="elite")return this.system.attributes.hp.max=maxHP+currentHPAdjustment+newHPAdjustment,currentHP+currentHPAdjustment+newHPAdjustment;if(!adjustment)return this.system.attributes.hp.max=maxHP+currentHPAdjustment,currentHP+currentHPAdjustment}else{if(adjustment==="elite")return this.system.attributes.hp.max=currentHP+newHPAdjustment,currentHP+newHPAdjustment;if(adjustment==="weak")return currentHP-newHPAdjustment}return currentHP})();await this.update({"system.attributes.hp.value":Math.max(0,newHP),"system.attributes.adjustment":adjustment})}variantClone(params){const source=this._source,changes={name:params.name??this.name,system:{details:{publicNotes:params.description??source.system.details.publicNotes}},img:params.img?.actor??source.img,prototypeToken:{texture:{src:params.img?.token??source.prototypeToken.texture.src}}};return this.clone(changes,{save:params.save,keepId:params.keepId})}}function resolveKingdomBoosts(entry,choices){const notFreeBoosts=entry.boosts.filter(b=>b!=="free");return uniq([notFreeBoosts,choices].flat()).filter(b=>b!==entry.flaw).slice(0,entry.boosts.length)}__name(resolveKingdomBoosts,"resolveKingdomBoosts"),__name2(resolveKingdomBoosts,"resolveKingdomBoosts");function calculateKingdomCollectionData(kingdom){const commodityTypes=["luxuries","lumber","ore","stone"];return{formula:`${kingdom.resources.dice.number}d${kingdom.resources.dice.faces}`,commodities:mapToObj(commodityTypes,type=>{const value=kingdom.resources.workSites[type];return[type,value.value+value.resource*2]})}}__name(calculateKingdomCollectionData,"calculateKingdomCollectionData"),__name2(calculateKingdomCollectionData,"calculateKingdomCollectionData");async function importDocuments(actor,items,skipDialog){const createData=items.filter(d=>!actor.items.some(i=>i.sourceId===d.uuid)).map(d=>d.toObject()),incomingDataByUUID=mapToObj(items,d=>[d.uuid,d.toObject(!0)]),updateData=compact(actor.itemTypes.campaignFeature.map(d=>{const incoming=d.sourceId&&incomingDataByUUID[d.sourceId];if(!incoming)return null;const data=pick(incoming,["name","img","system"]),diff=foundry.utils.diffObject(d.toObject(!0),data);return isEmpty(diff)?null:{_id:d.id,...diff}}));!updateData.length&&!createData.length||!skipDialog&&!await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.Kingdom.ImportDialog.Title"),content:game.i18n.format("PF2E.Kingmaker.Kingdom.ImportDialog.Content",{added:createData.length,updated:updateData.length})})||(await actor.updateEmbeddedDocuments("Item",updateData),await actor.createEmbeddedDocuments("Item",createData))}__name(importDocuments,"importDocuments"),__name2(importDocuments,"importDocuments");const KINGDOM_ABILITIES=["culture","economy","loyalty","stability"],KINGDOM_LEADERSHIP=["ruler","counselor","general","emissary","magister","treasurer","viceroy","warden"],KINGDOM_COMMODITIES=["food","luxuries","lumber","ore","stone"],KINGDOM_SKILLS=["agriculture","arts","boating","defense","engineering","exploration","folklore","industry","intrigue","magic","politics","scholarship","statecraft","trade","warfare","wilderness"],KINGDOM_LEADERSHIP_ABILITIES={ruler:"loyalty",counselor:"culture",general:"stability",emissary:"loyalty",magister:"culture",treasurer:"economy",viceroy:"economy",warden:"stability"},KINGDOM_SKILL_ABILITIES={agriculture:"stability",arts:"culture",boating:"economy",defense:"stability",engineering:"stability",exploration:"economy",folklore:"culture",industry:"economy",intrigue:"loyalty",magic:"culture",politics:"loyalty",scholarship:"culture",statecraft:"loyalty",trade:"economy",warfare:"loyalty",wilderness:"stability"},KINGDOM_ABILITY_LABELS=mapToObj(KINGDOM_ABILITIES,a=>[a,`PF2E.Kingmaker.Abilities.${a}`]),KINGDOM_COMMODITY_LABELS=mapToObj(KINGDOM_COMMODITIES,c=>[c,`PF2E.Kingmaker.Kingdom.Commodity.${c}`]),KINGDOM_RUIN_LABELS={culture:"PF2E.Kingmaker.Kingdom.Ruin.corruption",economy:"PF2E.Kingmaker.Kingdom.Ruin.crime",stability:"PF2E.Kingmaker.Kingdom.Ruin.decay",loyalty:"PF2E.Kingmaker.Kingdom.Ruin.strife"},KINGDOM_SKILL_LABELS=mapToObj(KINGDOM_SKILLS,a=>[a,`PF2E.Kingmaker.Skills.${a}`]),CONTROL_DC_BY_LEVEL=[14,15,16,18,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],KINGDOM_SIZE_DATA={1:{faces:4,type:"territory",controlMod:0,storage:4},10:{faces:6,type:"province",controlMod:1,storage:8},25:{faces:8,type:"state",controlMod:2,storage:12},50:{faces:10,type:"country",controlMod:3,storage:16},100:{faces:12,type:"dominion",controlMod:4,storage:20}},KINGDOM_SETTLEMENT_TYPES=["village","town","city","metropolis"],KINGDOM_SETTLEMENT_TYPE_LABELS=mapToObj(KINGDOM_SETTLEMENT_TYPES,size=>[size,`PF2E.Kingmaker.Settlement.Type.${size}`]),KINGDOM_SETTLEMENT_TYPE_DATA={village:{blocks:1,population:[0,400],level:[1,1],consumption:1,maxItemBonus:1,influence:0},town:{blocks:4,population:[401,2e3],level:[2,4],consumption:2,maxItemBonus:1,influence:1},city:{blocks:9,population:[2001,25e3],level:[5,9],consumption:4,maxItemBonus:2,influence:2},metropolis:{blocks:1/0,population:[25001,1/0],level:[10,1/0],consumption:6,maxItemBonus:3,influence:3}},vacancyLabel=__name2(role=>game.i18n.format("PF2E.Kingmaker.Kingdom.VacantRole",{role:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${role}`)}),"vacancyLabel"),VACANCY_PENALTIES={ruler:()=>({modifiers:{"kingdom-check":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:-1}],"control-dc":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:2}]}}),counselor:()=>({modifiers:{"culture-based":[{slug:"vacancy",label:vacancyLabel("counselor"),modifier:-1}]}}),general:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("general"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("general"),getNewValue:()=>-4}]}}),emissary:()=>({modifiers:{"loyalty-based":[{slug:"vacancy",label:vacancyLabel("emissary"),modifier:-1}]}}),magister:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("magister"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("magister"),getNewValue:()=>-4}]}}),treasurer:()=>({modifiers:{"economy-based":[{slug:"vacancy",label:vacancyLabel("treasurer"),modifier:-1}]}}),viceroy:()=>({modifiers:{"stability-based":[{slug:"vacancy",label:vacancyLabel("viceroy"),modifier:-1}]}}),warden:()=>({modifiers:{"kingdom-check":[{slug:"vacancy",label:vacancyLabel("warden"),modifier:0}]},adjustments:{"kingdom-check":[{slug:"vacancy",test:options=>[...options].includes("region"),relabel:vacancyLabel("warden"),getNewValue:()=>-4}]}})};function getKingdomCHGData(){const localize=localizer("PF2E.Kingmaker");return{charter:{conquest:{name:localize("Charter.conquest.Name"),description:localize("Charter.conquest.Description"),img:"/icons/weapons/swords/sword-guard-steel-green.webp",boosts:["loyalty","free"],flaw:"culture"},expansion:{name:localize("Charter.expansion.Name"),description:localize("Charter.expansion.Description"),img:"/icons/skills/trades/woodcutting-logging-axe-stump.webp",boosts:["culture","free"],flaw:"stability"},exploration:{name:localize("Charter.exploration.Name"),description:localize("Charter.exploration.Description"),img:"/icons/tools/navigation/map-chart-tan.webp",boosts:["stability","free"],flaw:"economy"},grant:{name:localize("Charter.grant.Name"),description:localize("Charter.grant.Description"),img:"/icons/skills/trades/academics-merchant-scribe.webp",boosts:["economy","free"],flaw:"loyalty"},open:{name:localize("Charter.open.Name"),description:localize("Charter.open.Description"),img:"/icons/sundries/documents/document-sealed-brown-red.webp",boosts:["free"],flaw:null}},heartland:{forestOrSwamp:{name:localize("Heartland.forestOrSwamp.Name"),description:localize("Heartland.forestOrSwamp.Description"),img:"/icons/environment/wilderness/tree-oak.webp",boosts:["culture"]},hillOrPlain:{name:localize("Heartland.hillOrPlain.Name"),description:localize("Heartland.hillOrPlain.Description"),img:"/icons/environment/creatures/horses.webp",boosts:["loyalty"]},lakeOrRiver:{name:localize("Heartland.lakeOrRiver.Name"),description:localize("Heartland.lakeOrRiver.Description"),img:"/icons/environment/settlement/bridge-stone.webp",boosts:["economy"]},mountainOrRuins:{name:localize("Heartland.mountainOrRuins.Name"),description:localize("Heartland.mountainOrRuins.Description"),img:"/icons/environment/wilderness/cave-entrance-mountain.webp",boosts:["stability"]}},government:{despotism:{name:localize("Government.despotism.Name"),description:localize("Government.despotism.Description"),img:"/icons/environment/settlement/pyramid.webp",boosts:["stability","economy","free"],skills:["intrigue","warfare"],feat:"Compendium.pf2e.kingmaker-features.Item.WGpkcIChjIk1i0q0"},feudalism:{name:localize("Government.feudalism.Name"),description:localize("Government.feudalism.Description"),img:"/icons/environment/settlement/watchtower-cliff.webp",boosts:["stability","culture","free"],skills:["defense","trade"],feat:"Compendium.pf2e.kingmaker-features.Item.JYY8vQxPe9AIGTvv"},oligarchy:{name:localize("Government.oligarchy.Name"),description:localize("Government.oligarchy.Description"),img:"/icons/environment/settlement/house-manor.webp",boosts:["loyalty","economy","free"],skills:["arts","industry"],feat:"Compendium.pf2e.kingmaker-features.Item.9dkyZ7r1z7loOxI7"},republic:{name:localize("Government.republic.Name"),description:localize("Government.republic.Description"),img:"/icons/environment/settlement/gazebo.webp",boosts:["stability","economy","free"],skills:["engineering","politics"],feat:"Compendium.pf2e.kingmaker-features.Item.BChcBEZpcqMnLISC"},thaumocracy:{name:localize("Government.thaumocracy.Name"),description:localize("Government.thaumocracy.Description"),img:"/icons/environment/settlement/wizard-castle.webp",boosts:["economy","culture","free"],skills:["folklore","magic"],feat:"Compendium.pf2e.kingmaker-features.Item.nDDEbrWj2JouxlRw"},yeomanry:{name:localize("Government.yeomanry.Name"),description:localize("Government.yeomanry.Description"),img:"/icons/environment/settlement/house-farmland-small.webp",boosts:["loyalty","culture","free"],skills:["agriculture","wilderness"],feat:"Compendium.pf2e.kingmaker-features.Item.WFng3pxgEAdpdy1p"}}}}__name(getKingdomCHGData,"getKingdomCHGData"),__name2(getKingdomCHGData,"getKingdomCHGData");const KINGDOM_TRAITS=["commerce","leadership","region","civic","army"];class KingdomSheetPF2e extends ActorSheetPF2e{static{__name(this,"KingdomSheetPF2e")}static{__name2(this,"KingdomSheetPF2e")}selectedFilter=null;focusElement=null;#editingSettlements={};constructor(actor,options){super(actor,options)}get kingdom(){const campaign=this.actor.campaign;if(!(campaign instanceof Kingdom))throw this.close(),ErrorPF2e("Only actors with kingdom data is supported");return campaign}get title(){return this.kingdom.name}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"kingdom"],width:720,height:620,template:"systems/pf2e/templates/actors/party/kingdom/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{campaign:!0,tab:this._tabs[0].active}})}}),buttons}async getData(options){const data=await super.getData(options),kingdom=this.kingdom,settlementEntries=pipe(Object.entries(this.kingdom.settlements),filter(entry=>!!entry[1]),sortBy(entry=>entry[1].sort));return{...data,actor:this.actor,kingdom:this.kingdom,nationTypeLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.NationType.${kingdom.nationType}`),abilities:KINGDOM_ABILITIES.map(slug=>({...this.kingdom.abilities[slug],slug,label:game.i18n.localize(KINGDOM_ABILITY_LABELS[slug]),ruinLabel:game.i18n.localize(KINGDOM_RUIN_LABELS[slug])})),commodities:KINGDOM_COMMODITIES.map(type=>({...kingdom.resources.commodities[type],type,label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type]),workSites:{label:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Name`),description:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Description`),hasResource:["lumber","ore","stone"].includes(type),value:kingdom.resources.workSites[type].value,resource:kingdom.resources.workSites[type].resource}})),resourceDice:{...kingdom.resources.dice,icon:fontAwesomeIcon(`dice-d${kingdom.resources.dice.faces}`).outerHTML,bonusAdjustment:getAdjustment(kingdom.resources.dice.bonus,kingdom._source.resources.dice.bonus),penaltyAdjustment:getAdjustment(kingdom.resources.dice.penalty,kingdom._source.resources.dice.penalty)},leadership:KINGDOM_LEADERSHIP.map(slug=>{const data2=this.kingdom.leadership[slug],document2=fromUuidSync(data2.uuid??""),actor=document2 instanceof ActorPF2e?document2:null;return{...data2,slug,label:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${slug}`),actor,img:actor?.prototypeToken.texture.src??actor?.img??ActorPF2e.DEFAULT_ICON,abilityLabel:game.i18n.localize(KINGDOM_ABILITY_LABELS[KINGDOM_LEADERSHIP_ABILITIES[slug]]),penaltyLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.VacancyPenalty.${slug}`)}}),actions:sortBy(kingdom.activities,a=>a.name).map(item=>({item,traits:createSheetTags(CONFIG.PF2E.kingmakerTraits,item.system.traits.value.filter(t=>t!=="downtime"))})),skills:sortBy(Object.values(this.kingdom.skills),s=>s.label),feats:[kingdom.features,kingdom.feats,kingdom.bonusFeats],actionFilterChoices:KINGDOM_TRAITS.map(trait=>({label:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[trait]),value:trait,selected:!1})),settlements:await Promise.all(settlementEntries.map(async([id,data2])=>this.#prepareSettlement(id,data2))),eventText:await TextEditor.enrichHTML(kingdom.event.text,{async:!0,rollData:this.actor.getRollData()}),settlementTypes:KINGDOM_SETTLEMENT_TYPE_LABELS,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS}}async#prepareSettlement(id,settlement){const data=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type],levelRange=data.level[1]===1/0?`${data.level[0]}+`:data.level[0]===data.level[1]?String(data.level[0]):data.level.join("-"),populationRange=data.population[1]===1/0?`${data.population[0]}+`:data.population.join("-");return{...settlement,id,description:await TextEditor.enrichHTML(settlement.description,{async:!0,rollData:this.actor.getRollData()}),editing:this.#editingSettlements[id]??!1,blocks:data.blocks===1/0?"10+":data.blocks,populationRange,levelRange,typeLabel:KINGDOM_SETTLEMENT_TYPE_LABELS[settlement.type],storage:KINGDOM_COMMODITIES.map(type=>({type,value:settlement.storage[type],label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type])}))}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.focusElement&&(htmlQuery(html,this.focusElement)?.focus(),this.focusElement=null);for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",()=>actor?.sheet.render(!0))}for(const button of htmlQueryAll(html,"[data-action=builder]")){const tab=button.dataset.tab??null;button.addEventListener("click",()=>{new KingdomBuilder(this.kingdom).render(!0,{tab})})}const{fame}=this.kingdom.resources,famePips=htmlQuery(html,"[data-action=adjust-fame]");famePips?.addEventListener("click",async()=>{const newValue=Math.min(fame.value+1,fame.max);await this.kingdom.update({"resources.fame.value":newValue})}),famePips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(fame.value-1,0);await this.kingdom.update({"resources.fame.value":newValue})});for(const leader of htmlQueryAll(html,".leader[data-role]")){const{role,uuid}=leader.dataset;if(htmlQuery(leader,"[data-action=remove-leader]")?.addEventListener("click",()=>{this.kingdom.update({[`leadership.${role}`]:null})}),uuid)for(const clickable of htmlQueryAll(leader,"[data-action=open-sheet]"))clickable.addEventListener("click",()=>fromUuid(uuid).then(a=>a?.sheet.render(!0)));const vacantEl=htmlQuery(leader,".vacant[title]");if(vacantEl){const lines=vacantEl.title.split(/;\s*/).map(l=>createHTMLElement("li",{children:[l]})),content=createHTMLElement("ul",{children:lines});$(vacantEl).tooltipster({content,contentAsHTML:!0,side:"right",theme:"crb-hover"})}}for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event2=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event2,{type:"check"}))})}htmlQuery(html,"[data-action=collect]")?.addEventListener("click",async()=>{ChatMessagePF2e.create({speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.kingdom.name},content:await renderTemplate("systems/pf2e/templates/actors/party/kingdom/collection.hbs",{...calculateKingdomCollectionData(this.kingdom)})})}),this.filterActions(this.selectedFilter,{instant:!0}),htmlQuery(html,".filters")?.addEventListener("click",event2=>{const filterButton=htmlClosest(event2.target,".choice");filterButton&&this.filterActions(filterButton.dataset.slug??null)}),$html.find("[data-tooltip-content]").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120});for(const customModifierEl of htmlQueryAll(html,".modifiers-tooltip")){const stat=customModifierEl.dataset.stat;if(!stat)continue;for(const removeButton of htmlQueryAll(customModifierEl,"[data-action=remove-modifier]")){const slug=removeButton.dataset.slug??"";removeButton.addEventListener("click",()=>{this.kingdom.removeCustomModifier(stat,slug)})}const modifierValueEl=htmlQuery(customModifierEl,".add-modifier input[type=number]");htmlQuery(customModifierEl,"[data-action=increment]")?.addEventListener("click",()=>{modifierValueEl?.stepUp()}),htmlQuery(customModifierEl,"[data-action=decrement]")?.addEventListener("click",()=>{modifierValueEl?.stepDown()}),htmlQuery(customModifierEl,"[data-action=create-custom-modifier]")?.addEventListener("click",()=>{const modifier=modifierValueEl?.valueAsNumber||1,type=htmlQuery(customModifierEl,".add-modifier-type")?.value??"",label=htmlQuery(customModifierEl,".add-modifier-name")?.value?.trim()??game.i18n.localize(`PF2E.ModifierType.${type}`);if(!setHasElement(MODIFIER_TYPES,type)){ui.notifications.error("Type is required.");return}this.kingdom.addCustomModifier(stat,{label,modifier,type})})}htmlQuery(html,"[data-action=add-settlement]")?.addEventListener("click",()=>{const id=foundry.utils.randomID();this.#editingSettlements[id]=!0,this.focusElement=`[name="settlements.${id}.name"]`,this.kingdom.update({[`settlements.${id}`]:{}})});for(const settlementElement of htmlQueryAll(html,".settlement"))this.#activateSettlementEvents(settlementElement);for(const link of htmlQueryAll(html,"[data-action=browse-feats]")){const maxLevel=Number(link.dataset.level)||this.kingdom.level;link.addEventListener("click",async()=>{const compendiumTab=game.pf2e.compendiumBrowser.tabs.campaignFeature,filter2=await compendiumTab.getFilterData(),levels=filter2.sliders.level;levels.values.max=Math.min(maxLevel,levels.values.upperLimit),levels.isExpanded=levels.values.max!==levels.values.upperLimit,filter2.checkboxes.category.options["kingdom-feat"].selected=!0,filter2.checkboxes.category.selected.push("kingdom-feat"),filter2.checkboxes.category.isExpanded=!0,compendiumTab.open(filter2)})}htmlQuery(html,"[data-action=random-event]")?.addEventListener("click",()=>{new Statistic(this.actor,{slug:"random-event",label:"Random Kingdom Event",check:{type:"flat-check"}}).roll({dc:this.kingdom.event.dc})}),htmlQuery(html,"[data-action=reset-event-dc]")?.addEventListener("click",()=>{this.kingdom.update({event:{dc:16}})});const settlementList=htmlQuery(html,".settlement-list");settlementList&&Sortable.create(settlementList,{...SORTABLE_BASE_OPTIONS,handle:".drag-handle",onEnd:event2=>{const settlements=this.kingdom.settlements,settlementsWithIds=Object.entries(settlements).map(([id,value])=>({id,...value})),settlement=settlementsWithIds.find(s=>s.id===event2.item.dataset.settlementId),newIndex=event2.newDraggableIndex;if(!settlement||newIndex===void 0){this.render();return}const siblings=sortBy(settlementsWithIds.filter(s=>s!==settlement),s=>s.sort);siblings.splice(newIndex,0,settlement);const updates=mapToObj.indexed(siblings,(s,index)=>[`settlements.${s.id}.sort`,index]);this.kingdom.update(updates)}})}#activateSettlementEvents(settlementElement){const id=settlementElement.dataset.settlementId??null;if(id===null)return;const rerenderSettlement=__name2(async()=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;const newHTML=await renderTemplate("systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs",{...await this.getData(),settlement:await this.#prepareSettlement(id,settlement)}),newElement=createHTMLElement("div",{innerHTML:newHTML}).firstElementChild;newElement instanceof HTMLElement&&(newElement.classList.toggle("expanded",settlementElement.classList.contains("expanded")),settlementElement.replaceWith(newElement),super.activateListeners($(newElement)),this.#activateSettlementEvents(newElement),this.#editingSettlements[id]&&!newElement.classList.contains("expanded")&&this.itemRenderer.toggleSummary(newElement,{visible:!0}))},"rerenderSettlement");htmlQuery(settlementElement,"[data-action=edit-settlement]")?.addEventListener("click",()=>{this.#editingSettlements[id]=!0,rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=finish-settlement]")?.addEventListener("click",async()=>{this.#editingSettlements[id]=!1,await this.saveEditor(`settlements.${id}.description`),rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=delete-settlement]")?.addEventListener("click",async event2=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;(event2?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`<p>${game.i18n.format("PF2E.DeleteQuestion",{name:`"${settlement.name}"`})}</p>`}))&&this.kingdom.update({[`settlements.-=${id}`]:null})})}filterActions(trait,options={}){const html=this.element.get(0),duration=.4;this.selectedFilter=trait;const animateElement=__name2((element,visible)=>{options.instant?element.hidden=!visible:visible&&element.hidden?gsap.fromTo(element,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration}):!visible&&!element.hidden&&gsap.to(element,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{element.hidden=!0,this.itemRenderer.toggleSummary(element,{visible:!1,instant:!0})}})},"animateElement");for(const action2 of this.kingdom.activities){const element=htmlQuery(html,`[data-item-id="${action2.id}"]`),visible=!trait||tupleHasValue(action2.system.traits.value,trait);element&&animateElement(element,visible)}for(const summary of htmlQueryAll(html,".phase-summary"))animateElement(summary,summary.dataset.phase===trait);for(const choice of htmlQueryAll(html,".filters .choice")){const active=choice.dataset.slug?choice.dataset.slug===trait:trait===null;choice.classList.toggle("active",active)}const actionsList=htmlQuery(html,".actions-list");actionsList&&(actionsList.scrollTop=0)}async _onDropItem(event2,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event2,data);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const slotData=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null};return(slotData.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats).insertFeat(item,slotData.slotId)}return super._onDropItem(event2,data)}async _onSortItem(event2,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const featSlot=this.#getFeatSlotData(event2);if(!featSlot)return[];const group=featSlot.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return group.insertFeat(item,featSlot.slotId)}return super._onSortItem(event2,itemSource)}async _onDropActor(event2,data){await super._onDropActor(event2,data);const actor=fromUuidSync(data.uuid),closestLeader=htmlClosest(event2.target,".leader[data-role]");if(actor instanceof CreaturePF2e&&closestLeader){const role=String(closestLeader.dataset.role),uuid=actor.uuid;this.kingdom.update({leadership:{[role]:{uuid}}})}}#getFeatSlotData(event2){const groupId=event2.target?.closest("[data-group-id]")?.dataset.groupId,slotId=event2.target?.closest("[data-slot-id]")?.dataset.slotId;return typeof groupId=="string"?{slotId,groupId}:null}_disableFields(form){for(const gmOnlyField of htmlQueryAll(form,"input, textarea, [data-access=owner]"))gmOnlyField instanceof HTMLTextAreaElement?gmOnlyField.readOnly=!0:(gmOnlyField instanceof HTMLInputElement||gmOnlyField instanceof HTMLButtonElement)&&(gmOnlyField.disabled=!0)}async _updateObject(_event,formData){if(!this.actor.id)return;const data=foundry.utils.expandObject(formData);for(const abilitySlug of KINGDOM_ABILITIES){const ability=data.abilities?.[abilitySlug];ability?.penalty&&(ability.penalty=-Math.abs(ability.penalty))}return this.kingdom.update(data)}}const KINGDOM_BUILD_CATEGORIES=["charter","heartland","government"],KINGDOM_BOOST_LEVELS=[1,5,10,15,20];class KingdomBuilder extends FormApplication{static{__name(this,"KingdomBuilder")}static{__name2(this,"KingdomBuilder")}selected={charter:null,heartland:null,government:null};static get defaultOptions(){return{...super.defaultOptions,classes:["sheet","kingdom-builder"],title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),template:"systems/pf2e/templates/actors/party/kingdom/builder.hbs",width:560,height:"auto",submitOnChange:!0,closeOnSubmit:!1,tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}static showToPlayers(options){const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:options.uuid,options:{campaign:"builder",tab:options.tab}})}constructor(kingdom){super(kingdom),kingdom.actor.apps[this.appId]=this}get id(){return`kingdom-builder-${this.actor.id}`}get kingdom(){return this.object}get actor(){return this.object.actor}get isEditable(){return this.actor.isOwner}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&(buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{KingdomBuilder.showToPlayers({uuid:this.actor.uuid,tab:this._tabs[0].active})}}),this.kingdom.active==="building"&&buttons.unshift({label:"PF2E.Kingmaker.KingdomBuilder.CancelCreation",class:"cancel",icon:"fa-solid fa-times",onclick:async()=>{await this.kingdom.update({active:!1})}})),buttons}async getData(){const database=getKingdomCHGData(),getActiveForCategory=__name2(category=>{const active=this.kingdom.build[category];return active?active?.id??Object.entries(database[category]).find(([_,entry])=>entry?.name===active.name)?.[0]??null:null},"getActiveForCategory");for(const category of KINGDOM_BUILD_CATEGORIES)this.selected[category]??=getActiveForCategory(category);const categories=await pipe(KINGDOM_BUILD_CATEGORIES,map(async category=>{const selected=this.selected[category],entries=database[category],buildEntry=entries[selected??""]??Object.values(entries)[0],featItem=await(async()=>{try{return buildEntry?.feat?await fromUuid(buildEntry.feat):null}catch(ex){return console.error(ex),null}})(),result={selected,active:getActiveForCategory(category),buildEntry,featLink:featItem?await TextEditor.enrichHTML(featItem.link,{async:!0}):null,stale:!equals(buildEntry,this.kingdom.build[category])};return[category,result]}),items=>Promise.all(items).then(result=>fromPairs(result))),{build}=this.kingdom,finished=!!(build.charter&&build.heartland&&build.government);return{options:{editable:this.isEditable},kingdom:this.kingdom,database,categories,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS,build:this.#prepareAbilityBuilder(),finished}}#prepareAbilityBuilder(){function createButtons(){return Array.from(KINGDOM_ABILITIES).reduce((accumulated,ability)=>(accumulated[ability]={ability},accumulated),{})}__name(createButtons,"createButtons"),__name2(createButtons,"createButtons");const choices=this.kingdom.build.boosts,mainBoosts=mapToObj(KINGDOM_BUILD_CATEGORIES,prop=>{const buildItem=this.kingdom[prop];if(!buildItem)return[prop,null];const buttons=createButtons(),selectedChoices=objectHasKey(choices,prop)?choices[prop]:[],boosts=resolveKingdomBoosts(buildItem,selectedChoices),remaining=Math.max(0,buildItem.boosts.length-boosts.length);for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability);ability===buildItem.flaw?buttons[ability].flaw={selected:!0,locked:!0}:(selected||buildItem.boosts.includes("free"))&&(buttons[ability].boost={selected,locked:buildItem.boosts.includes(ability),disabled:!selected&&!remaining})}return[prop,{buttons,remaining}]}),levelBoosts=mapToObj(KINGDOM_BOOST_LEVELS,level=>{const eligible=this.kingdom.level>=level,buttons=createButtons(),boosts=this.kingdom.build.boosts[level],remaining=eligible?Math.max(0,2-boosts.length):0;for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability)&&eligible;buttons[ability].boost={selected,disabled:!selected&&!remaining}}return[level,{buttons,remaining,eligible}]});return{...mainBoosts,levelBoosts}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const categoryEl of htmlQueryAll(html,"[data-category]")){const category=categoryEl.dataset.category??null;if(!tupleHasValue(KINGDOM_BUILD_CATEGORIES,category))continue;for(const choiceElement of htmlQueryAll(categoryEl,".choice"))choiceElement.addEventListener("click",evt=>{const slug=htmlClosest(evt.target,"[data-slug]")?.dataset.slug;category&&objectHasKey(this.selected,category)&&(this.selected[category]=slug??null,this.render())});const saveCategory=__name2(async()=>{const database=getKingdomCHGData(),id=this.selected[category]??"",selected=database[category][id];selected&&(this.selected[category]=null,await this.kingdom.update({[`build.${category}`]:{id,...selected},[`build.boosts.${category}`]:[]}))},"saveCategory");htmlQuery(categoryEl,"[data-action=set]")?.addEventListener("click",()=>{saveCategory()}),htmlQuery(categoryEl,"[data-action=save-and-continue]")?.addEventListener("click",async event2=>{event2.preventDefault(),event2.stopPropagation(),await saveCategory();const activeTab=this._tabs[0].active,idx=KINGDOM_BUILD_CATEGORIES.indexOf(activeTab),newTab=KINGDOM_BUILD_CATEGORIES[idx+1]??"ability";this._tabs[0].activate(newTab,{triggerCallback:!0})})}for(const button of htmlQueryAll(html,".ability-builder [data-section] .boost")){const sectionId=htmlClosest(button,"[data-section]")?.dataset.section,ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BUILD_CATEGORIES,sectionId)||button.addEventListener("click",()=>{const object=this.kingdom[sectionId],current=this.kingdom.build.boosts[sectionId],maxBoosts=object?.boosts.length;if(!object)return;const boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).filter(a=>!object.boosts.includes(a)&&object.flaw!==a).slice(0,maxBoosts);this.kingdom.update({[`build.boosts.${sectionId}`]:boosts})})}for(const button of htmlQueryAll(html,".ability-builder [data-level] .boost")){const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BOOST_LEVELS,level)||button.addEventListener("click",()=>{const current=this.kingdom.build.boosts[level],boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).slice(0,2);this.kingdom.update({[`build.boosts.${level}`]:boosts})})}htmlQuery(html,"[data-action=complete]")?.addEventListener("click",async()=>{this.close(),await this.kingdom.update({active:!0}),await this.kingdom.importActivities(),new KingdomSheetPF2e(this.actor).render(!0)})}async _updateObject(_event,formData){if(this.actor.id)return this.object.update(formData)}async _render(force,options){if(this.kingdom.active===!1){this.close({force:!0});return}await super._render(force,options),options?.tab&&this._tabs.at(0)?.activate(options.tab,{triggerCallback:!0})}}const{fields}=foundry.data;function buildKingdomCHGSchema(){return{id:new fields.StringField({required:!1,initial:void 0,blank:!1}),name:new fields.StringField({required:!0,nullable:!1,blank:!1}),img:new fields.StringField({required:!0,nullable:!1}),description:new fields.StringField({required:!0,nullable:!1}),boosts:new fields.ArrayField(new fields.StringField({choices:[...KINGDOM_ABILITIES,"free"],nullable:!1}))}}__name(buildKingdomCHGSchema,"buildKingdomCHGSchema"),__name2(buildKingdomCHGSchema,"buildKingdomCHGSchema");const KINGDOM_BUILD_SCHEMA={manual:new fields.BooleanField({required:!0,nullable:!1,initial:!1}),charter:new fields.SchemaField({...buildKingdomCHGSchema(),flaw:new fields.StringField({choices:KINGDOM_ABILITIES,required:!0,nullable:!0})},{nullable:!0,initial:null}),heartland:new fields.SchemaField(buildKingdomCHGSchema(),{nullable:!0,initial:null}),government:new fields.SchemaField({...buildKingdomCHGSchema(),skills:new fields.ArrayField(new fields.StringField({required:!0,nullable:!1,choices:KINGDOM_SKILLS})),feat:new fields.StringField({required:!0,nullable:!0})},{nullable:!0,initial:null}),skills:new fields.SchemaField(mapToObj(KINGDOM_SKILLS,skill=>{const schema=new fields.SchemaField({rank:new fields.NumberField({initial:0,min:0,max:4,required:!0,nullable:!1})});return[skill,schema]})),boosts:new fields.SchemaField(mapToObj(["charter","heartland","government","1","5","10","15","20"],category=>{const schema=new fields.ArrayField(new fields.StringField({choices:KINGDOM_ABILITIES,nullable:!1}));return[category,schema]}))},KINGDOM_RESOURCES_SCHEMA={dice:new fields.SchemaField({number:new fields.NumberField,faces:new fields.NumberField,bonus:new fields.NumberField({required:!0,nullable:!1,initial:0}),penalty:new fields.NumberField({required:!0,nullable:!1,initial:0})}),fame:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:3})}),commodities:new fields.SchemaField(mapToObj(KINGDOM_COMMODITIES,type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:0})});return[type,schema]})),points:new fields.NumberField({min:0,required:!1,nullable:!1,initial:0}),workSites:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0}),resource:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0})});return[type,schema]}))},KINGDOM_SETTLEMENT_SCHEMA={name:new fields.StringField({required:!0,blank:!0,nullable:!1,initial:""}),type:new fields.StringField({required:!1,nullable:!1,choices:KINGDOM_SETTLEMENT_TYPES,initial:"village"}),level:new fields.NumberField({min:1,initial:1,max:30,nullable:!1}),overcrowded:new fields.BooleanField,description:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""}),sort:new fields.IntegerSortField,consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),reduction:new fields.NumberField({required:!1,nullable:!1,initial:0}),total:new fields.NumberField({required:!1,nullable:!1,initial:0})}),storage:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.NumberField({required:!1,nullable:!1,min:0,initial:0});return[type,schema]}))},KINGDOM_SCHEMA={type:new fields.StringField({choices:["kingmaker"],required:!0,nullable:!1,initial:"kingmaker"}),active:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["building"],initial:void 0}),new StrictBooleanField({initial:!1,required:!1,nullable:!1})],{required:!1,nullable:!1,initial:!1}),name:new fields.StringField({required:!0,nullable:!1,initial:""}),img:new fields.FilePathField({categories:["IMAGE"],required:!0,nullable:!1,initial:"systems/pf2e/icons/default-icons/kingdom.svg"}),capital:new fields.StringField({initial:"",required:!0}),size:new fields.NumberField({initial:1,min:1,required:!0,nullable:!1}),level:new fields.NumberField({required:!0,nullable:!1,min:1,max:20,initial:1}),xp:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:1e3})}),aspiration:new fields.StringField({choices:["fame","infamy"],required:!0,nullable:!1,initial:"fame"}),abilities:new fields.SchemaField(mapToObj(KINGDOM_ABILITIES,ability=>{const schema=new fields.SchemaField({value:new fields.NumberField({initial:10,required:!1,nullable:!1}),mod:new fields.NumberField({initial:0,required:!1,nullable:!1}),ruin:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:10})}),penalty:new fields.NumberField({initial:0,required:!1,nullable:!1})});return[ability,schema]})),build:new fields.SchemaField(KINGDOM_BUILD_SCHEMA),customModifiers:new fields.ObjectField({initial:{}}),leadership:new fields.SchemaField(mapToObj(KINGDOM_LEADERSHIP,role=>{const schema=new fields.SchemaField({uuid:new fields.StringField({required:!1,nullable:!0,initial:null}),vacant:new fields.BooleanField({initial:!0}),invested:new fields.BooleanField({required:!1,initial:!1})});return[role,schema]})),resources:new fields.SchemaField(KINGDOM_RESOURCES_SCHEMA),settlements:new RecordField(new fields.StringField({required:!0,nullable:!1,blank:!1}),new fields.SchemaField(KINGDOM_SETTLEMENT_SCHEMA,{required:!0}),{required:!1,nullable:!1,initial:{}}),consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),settlement:new fields.NumberField({min:0,initial:0}),army:new fields.NumberField({min:0,initial:0}),value:new fields.NumberField({min:0,initial:0})}),unrest:new fields.SchemaField({value:new fields.NumberField({integer:!0,min:0,max:99,required:!1,nullable:!1,initial:0}),anarchyThreshold:new fields.NumberField({integer:!0,required:!1,nullable:!1,initial:20})}),event:new fields.SchemaField({dc:new fields.NumberField({required:!1,nullable:!1,min:0,max:20,initial:16}),text:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""})}),module:new fields.ObjectField({required:!1,initial:{}})},{DataModel:DataModel$1}=foundry.abstract;class Kingdom extends DataModel$1{static{__name(this,"Kingdom")}static{__name2(this,"Kingdom")}static defineSchema(){return KINGDOM_SCHEMA}get actor(){return this.parent}get extraItemTypes(){return["campaignFeature","effect"]}get activities(){return this.actor.itemTypes.campaignFeature.filter(k=>k.category==="kingdom-activity")}get charter(){return this.build.charter}get heartland(){return this.build.heartland}get government(){return this.build.government}createSidebarButtons(){if(!this.active&&!game.user.isGM)return[];const hoverIcon=this.active==="building"?"wrench":this.active?null:"plus",icon=createHTMLElement("a",{classes:["create-button"],children:compact([fontAwesomeIcon("crown"),hoverIcon?fontAwesomeIcon(hoverIcon):null]),dataset:{tooltip:game.i18n.localize(`PF2E.Kingmaker.SIDEBAR.${this.active===!0?"OpenSheet":"CreateKingdom"}`)}});return icon.addEventListener("click",async event2=>{if(event2.stopPropagation(),!this.active)await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),content:`<p>${game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.ActivationMessage")}</p>`})&&(await this.update({active:"building"}),KingdomBuilder.showToPlayers({uuid:this.actor.uuid}),new KingdomBuilder(this).render(!0));else{const type=this.active===!0?null:"builder";this.renderSheet({type})}}),[icon]}async collect(){const{formula,commodities}=calculateKingdomCollectionData(this),roll=await new Roll(formula).evaluate({async:!0});await roll.toMessage({flavor:game.i18n.localize("PF2E.Kingmaker.Kingdom.Resources.Points"),speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.name}},{rollMode:"publicroll"}),this.update({resources:{points:roll.total,commodities:mapValues$1(commodities,(incoming,type)=>{const current=this.resources.commodities[type];return{value:Math.min(current.value+incoming,current.max)}})}})}async addCustomModifier(stat,data){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(data.label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===data.label)){data.type=setHasElement(MODIFIER_TYPES,data.type)?data.type:"untyped";const modifier=new ModifierPF2e({...data,custom:!0}).toObject();await this.update({[`customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async update(data){const expanded=foundry.utils.expandObject(data),updateData=foundry.utils.mergeObject(expanded,expanded.system?.campaign??{});delete updateData.system,await this.actor.update({"system.campaign":updateData}),updateData.level&&await this.updateFeatures(updateData.level)}prepareBaseData(){const{synthetics}=this.actor,{build}=this;if(!build.manual){for(const ability of KINGDOM_ABILITIES)this.abilities[ability].value=10;for(const category of["charter","heartland","government"]){const data=build[category],chosen=build.boosts[category];if(!data)continue;"flaw"in data&&data.flaw&&(this.abilities[data.flaw].value-=2);const activeBoosts=resolveKingdomBoosts(data,chosen);for(const ability of activeBoosts)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}const activeLevels=[1,5,10,15,20].filter(l=>this.level>=l);for(const level of activeLevels){const chosen=build.boosts[level].slice(0,2);for(const ability of chosen)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}}for(const ability of KINGDOM_ABILITIES)this.abilities[ability].mod=(this.abilities[ability].value-10)/2;if(build.government&&build.government.skills.length>0)for(const skill of build.government.skills)build.skills[skill].rank=Math.max(1,build.skills[skill].rank);const customModifiers=this.customModifiers??={};for(const selector of Object.keys(customModifiers)){const modifiers=customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));(synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}const sizeData=Object.entries(KINGDOM_SIZE_DATA).findLast(([size])=>this.size>=Number(size))?.[1]??KINGDOM_SIZE_DATA[1];this.nationType=sizeData.type,this.resources.dice.faces=sizeData.faces,sizeData.controlMod&&(synthetics.modifiers["control-dc"]??=[]).push(()=>new ModifierPF2e({slug:"size",label:"Size Modifier",modifier:sizeData.controlMod}));for(const ability of KINGDOM_ABILITIES){const penalty=this.abilities[ability].penalty;penalty&&(synthetics.modifiers[`${ability}-based`]??=[]).push(()=>new ModifierPF2e({slug:"ruin",type:"item",label:KINGDOM_RUIN_LABELS[ability],modifier:penalty}))}for(const role of KINGDOM_LEADERSHIP){const data=this.leadership[role],actor=fromUuidSync(data.uuid??"");if(actor instanceof ActorPF2e?actor.hasPlayerOwner||(data.vacant=!1):data.vacant=!0,data.vacant){const penalties=VACANCY_PENALTIES[role]();for(const[selector,entries]of Object.entries(penalties.adjustments??{}))(synthetics.modifierAdjustments[selector]??=[]).push(...entries);for(const[selector,entries]of Object.entries(penalties.modifiers??{}))(synthetics.modifiers[selector]??=[]).push(...entries.map(e=>()=>new ModifierPF2e(e)))}if(data.invested){const ability=KINGDOM_LEADERSHIP_ABILITIES[role];(synthetics.modifiers[`${ability}-skill-check`]??=[]).push(()=>new ModifierPF2e({slug:"invested",label:"PF2E.Kingmaker.Kingdom.Invested",type:"status",modifier:1}))}}if(this.unrest.value>0){const modifier=-([1,5,10,15].findLastIndex(t=>this.unrest.value>=t)+1);(synthetics.modifiers["kingdom-check"]??=[]).push(()=>new ModifierPF2e({slug:"unrest",label:"PF2E.Kingmaker.Kingdom.Unrest",type:"status",modifier}))}const settlements=compact(Object.values(this.settlements));for(const settlement of settlements){if(!settlement)continue;const typeData=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type];settlement.consumption.base=typeData.consumption,settlement.consumption.total=Math.max(0,typeData.consumption-settlement.consumption.reduction)}for(const[type,value]of Object.entries(this.resources.commodities)){const settlementStorage=sumBy(settlements,s=>s.storage[type]);value.max=sizeData.storage+settlementStorage}}prepareDerivedData(){const{synthetics}=this.actor,{consumption,resources}=this;resources.dice.number=Math.max(0,this.level+4+resources.dice.bonus-resources.dice.penalty);const settlements=compact(Object.values(this.settlements));consumption.settlement=sumBy(settlements,s=>s.consumption.total);const computedConsumption=consumption.base+consumption.settlement+consumption.army-this.resources.workSites.food.value;consumption.value=Math.max(0,computedConsumption);const controlMod=CONTROL_DC_BY_LEVEL[Math.clamped(this.level-1,0,19)]-10;this.control=new Statistic(this.actor,{slug:"control",label:"PF2E.Kingmaker.Kingdom.ControlDC",domains:["control-dc"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:controlMod})]}),this.skills=mapToObj(KINGDOM_SKILLS,skill=>{const ability=KINGDOM_SKILL_ABILITIES[skill],abilityMod=this.abilities[ability].mod,rank=this.build.skills[skill].rank,domains=["kingdom-check",`${ability}-based`,`${ability}-skill-check`,skill],statistic=new Statistic(this.actor,{slug:skill,rank,label:KINGDOM_SKILL_LABELS[skill],domains,modifiers:[new ModifierPF2e({slug:ability,label:KINGDOM_ABILITY_LABELS[ability],modifier:abilityMod,type:"ability",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,ability)}),createProficiencyModifier({actor:this.actor,rank,domains,level:this.level})],check:{type:"skill-check"}});return[skill,statistic]});const evenLevels=new Array(this.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);this.features=new FeatGroup(this.actor,{id:"features",label:"Kingdom Features",level:this.level}),this.feats=new FeatGroup(this.actor,{id:"kingdom",label:"Kingdom Feats",slots:[{id:"government",label:"G"},...evenLevels],featFilter:["traits-kingdom"],level:this.level}),this.bonusFeats=new FeatGroup(this.actor,{id:"bonus",label:"PF2E.FeatBonusHeader",featFilter:["traits-kingdom"],level:this.level});const allFeatures=this.actor.itemTypes.campaignFeature,features=sortBy(allFeatures.filter(f=>f.isFeature),f=>f.level??1,f=>f.name),feats=sortBy(allFeatures.filter(f=>f.isFeat),f=>f.sort);for(const feature of features)this.features.assignFeat(feature);for(const feat of feats)this.feats.assignFeat(feat)||this.bonusFeats.assignFeat(feat)}getRollOptions(){const prefix="kingdom";return compact([this.unrest.value?`${prefix}:unrest:${this.unrest.value}`:null])}getRollData(){return{kingdom:this}}async importActivities({skipDialog=!1}={}){const pack=game.packs.get("pf2e.kingmaker-features");if(!pack)throw ErrorPF2e("Could not load kingdom features compendium");await this.updateFeatures(this.level);const documents=(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-activity");await importDocuments(this.actor,documents,skipDialog)}async updateFeatures(level){const featuresToDelete=this.actor.itemTypes.campaignFeature.filter(f=>f.isFeature).filter(f=>(f.level??0)>level).map(f=>f.id),featuresToAdd=await(async()=>{const pack=game.packs.get("pf2e.kingmaker-features");return pack?(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-feature").filter(d=>level>=(d.level??0)).filter(d=>!this.actor.items.some(i=>i.sourceId===d.uuid)).map(i=>i.toObject()):(console.error("PF2E System | Could not load kingdom features compendium"),[])})();await this.actor.deleteEmbeddedDocuments("Item",featuresToDelete),await this.actor.createEmbeddedDocuments("Item",featuresToAdd)}getStatistic(slug){return this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:null}renderSheet(options={}){options.type==="builder"?new KingdomBuilder(this).render(!0):new KingdomSheetPF2e(this.actor).render(!0,{tab:options.tab})}_preUpdate(changed){const actor=this.actor,feat=changed.build?.government?.feat;feat&&(console.log("Replacing feat"),fromUuid(feat).then(async f=>{if(!(f instanceof CampaignFeaturePF2e))return;const currentGovernmentFeat=actor.itemTypes.campaignFeature.find(f2=>f2.system.location==="government"),newFeat=f.clone({"system.location":"government"});await currentGovernmentFeat?.delete(),await actor.createEmbeddedDocuments("Item",[newFeat.toObject()])}))}}const BASIC_WAR_ACTIONS_FOLDER="Vqp8b64uH35zkncy",ALIGNMENTS=new Set(["LG","NG","CG","LN","N","CN","LE","NE","CE"]),ARMY_TYPES=["infantry","cavalry","siege","skirmisher"],ARMY_STATS={scouting:[0,7,8,9,11,12,14,15,16,18,19,21,22,23,25,26,28,29,30,32,33],standardDC:[0,15,16,18,19,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],ac:[0,16,18,19,21,22,24,25,27,28,30,31,33,34,36,37,39,40,42,43,45],strongSave:[0,10,11,12,14,15,17,18,19,21,22,24,25,26,28,29,30,32,33,35,36],weakSave:[0,4,5,6,8,9,11,12,13,15,16,18,19,20,22,23,25,26,27,29,30],attack:[0,9,11,12,14,15,17,18,20,21,23,24,26,27,29,30,32,33,35,36,38],maxTactics:[0,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6]};function getArmyGearData(){return{...mapToObj(["melee","ranged"],type=>[`additional-${type}`,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Description",traits:["army"],level:1,price:10}]),...mapToObj(["melee","ranged"],type=>[type,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.MagicWeapons.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.MagicWeapons.Description",traits:["army","magical"],ranks:[{price:20,level:2},{price:40,level:10},{price:60,level:16}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Description`}))}]),potions:{img:"icons/consumables/potions/bottle-round-corked-orante-red.webp",name:"PF2E.Kingmaker.Army.Gear.Potions.Name",description:"PF2E.Kingmaker.Army.Gear.Potions.Description",traits:["army","consumable","healing","magical","potion"],level:1,price:15},armor:{img:"icons/equipment/shield/heater-wooden-brown-axe.webp",name:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Name"),description:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Description"),traits:["army","magical"],ranks:[{price:25,level:5},{price:50,level:11},{price:75,level:18}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Description`}))}}}__name(getArmyGearData,"getArmyGearData"),__name2(getArmyGearData,"getArmyGearData");class ArmyPF2e extends ActorPF2e{static{__name(this,"ArmyPF2e")}static{__name2(this,"ArmyPF2e")}get allowedItemTypes(){return["campaignFeature","effect"]}get underRoutThreshold(){return this.hitPoints.value<=this.system.attributes.hp.routThreshold}get kingdom(){if(this.alliance==="party"){const campaign=game.actors.party?.campaign;return campaign instanceof Kingdom?campaign:null}return null}get maxTactics(){return ARMY_STATS.maxTactics[this.level]}prepareBaseData(){super.prepareBaseData(),this.system.ac.value??=this._source.system.ac.value??=ARMY_STATS.ac[this.level],this.system.scouting??=this._source.system.scouting??=ARMY_STATS.scouting[this.level],this.system.details.level.value=Math.clamped(this.system.details.level.value,1,20),this.system.resources.potions.max=3,this.system.saves.strongSave=this.system.saves.maneuver>=this.system.saves.morale?"maneuver":"morale",this.system.traits.senses=[],this.system.details.alliance=this.hasPlayerOwner?"party":"opposition",this.rollOptions.all[`self:trait:${this.system.traits.type}`]=!0,this.rollOptions.all["self:under-rout-threshold"]=this.underRoutThreshold}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData(),this.prepareSynthetics(),this.system.consumption=Math.max(0,this.system.consumption),this.itemTypes.campaignFeature.some(f=>f.slug==="darkvision")?this.system.traits.senses.push(new CreatureSensePF2e({type:"darkvision"})):this.itemTypes.campaignFeature.some(f=>f.slug==="low-light-vision")&&this.system.traits.senses.push(new CreatureSensePF2e({type:"lowLightVision"})),this.tactics=new FeatGroup(this,{id:"tactics",label:"PF2E.Kingmaker.Army.Tactics",slots:range(0,this.maxTactics).map(idx=>({id:String(idx),label:""}))}),this.bonusTactics=new FeatGroup(this,{id:"bonus",label:"PF2E.Kingmaker.Army.TacticsFree"});const expectedAC=ARMY_STATS.ac[this.level],acAdjustment=this.system.ac.value-expectedAC;this.armorClass=new ArmorStatistic(this,{modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:expectedAC-10}),acAdjustment&&new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:acAdjustment}),this.system.ac.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:this.system.ac.potency})])}).dc,this.system.ac.value=this.armorClass.value;const baseScouting=ARMY_STATS.scouting[this.level],scoutAdjustment=this.system.scouting-baseScouting;this.scouting=new Statistic(this,{slug:"scouting",label:"PF2E.Kingmaker.Army.Scouting",domains:["scouting"],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseScouting}),scoutAdjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:scoutAdjustment}):null])}),this.system.scouting=this.scouting.mod;for(const saveType of["maneuver","morale"]){const baseValue=(this.system.saves.strongSave===saveType?ARMY_STATS.strongSave:ARMY_STATS.weakSave)[this.level],adjustment=this.system.saves[saveType]-baseValue;this[saveType]=new Statistic(this,{slug:saveType,label:`PF2E.Kingmaker.Army.Save.${saveType}`,domains:["saving-throw",saveType],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseValue}),adjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:adjustment}):null])})}this.initiative=new ActorInitiative(this,{statistic:"scouting"}),this.strikes=flatMapToObj(["melee","ranged"],t=>this.system.weapons[t]?[[t,this.prepareArmyStrike(t)]]:[]);for(const tactic of this.itemTypes.campaignFeature.filter(i=>i.category==="army-tactic"))this.tactics.assignFeat(tactic)||this.bonusTactics.assignFeat(tactic)}async usePotion(){const newPotions=Math.max(0,this.system.resources.potions.value-1),newHP=Math.min(this.attributes.hp.value+1,this.attributes.hp.max);await this.update({"system.attributes.hp.value":newHP,"system.resources.potions.value":newPotions}),await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor:this,token:this.token}),flavor:createHTMLElement("div",{children:[createHTMLElement("strong",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionHeader")]}),document.createElement("hr")]}).outerHTML,content:createHTMLElement("p",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionContent")]}).outerHTML,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}prepareArmyStrike(type){const synthetics=this.synthetics,data=this.system.weapons[type];if(data===null)return null;const attackDomains=["attack","attack-roll",`${type}-attack-roll`],maps=(()=>{const baseMap={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty",map1:-5,map2:-10},optionSet=new Set(this.getRollOptions(attackDomains)),maps2=this.synthetics.multipleAttackPenalties??{},fromSynthetics=attackDomains.flatMap(d=>maps2[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)})(),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),statistic=new Statistic(this,{slug:`${type}-strike`,label:data.name,domains:attackDomains,rollOptions:[`item:${type}`],check:{type:"attack-roll"},modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:ARMY_STATS.attack[this.level]}),data.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:data.potency}),new ModifierPF2e({slug:"concealed",label:"PF2E.Kingmaker.Army.Condition.concealed.name",type:"circumstance",modifier:-2,predicate:["target:effect:concealed"],hideIfDisabled:!0})])}),dealDamage=__name2(async(params={},outcome="success")=>{const targetToken=params.target??game.user.targets.first()??null,domains=["damage","strike-damage",`${type}-damage`],context=await this.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:statistic.check,target:{token:targetToken},domains,outcome,checkContext:params.checkContext,options:new Set}),damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,...eventToRollParams(params.event,{type:"damage"})},{formula,breakdown}=createDamageFormula({base:[{modifier:outcome==="success"?1:2,damageType:"untyped",category:null}],modifiers:extractModifiers(context.self.actor.synthetics,domains,{test:context.options}),dice:extractDamageDice(context.self.actor.synthetics.damageDice,domains,{test:context.options,resolvables:{target:context.target?.actor??null}}),ignoredResistances:[]}),template={name:"Army damage",materials:[],modifiers:[],damage:{roll:new DamageRoll(formula),breakdown}};return DamagePF2e.roll(template,damageContext)},"dealDamage");return{slug:`${type}-strike`,label:data.name,type:"strike",glyph:"A",variants:[0,1,2].map(idx=>{const mapModifier=idx===0?null:createMapModifier(`map${idx}`),penalty=mapModifier?.modifier??0;return{label:idx===0?signedInteger(statistic.mod):game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(statistic.mod+penalty),penalty}),mod:statistic.mod,roll:async params=>{const targetToken=params.target??game.user.targets.find(t=>!!t.actor?.isOfType("army")),roll=await statistic.roll({identifier:type,action:"army-strike",melee:type==="melee",modifiers:mapModifier?[mapModifier]:[],target:targetToken?.actor,dc:{slug:"ac"},damaging:!0,extraRollOptions:["origin:action:slug:army-strike"],...eventToRollParams(params.event,{type:"check"})});if(roll&&type==="ranged"){const newAmmo=Math.max(0,this.system.resources.ammunition.value-1);this.update({"system.resources.ammunition.value":newAmmo})}return roll}}}),damage:params=>dealDamage(params,"success"),critical:params=>dealDamage(params,"criticalSuccess")}}updateLevel(newLevel){newLevel=Math.clamped(newLevel,1,20);const currentLevel=this.system.details.level.value,strongSave=this.system.saves.strongSave,strongSaveDifference=ARMY_STATS.strongSave[newLevel]-ARMY_STATS.strongSave[currentLevel],weakSaveDifference=ARMY_STATS.weakSave[newLevel]-ARMY_STATS.weakSave[currentLevel];return this.update({system:{ac:{value:this.system.ac.value+(ARMY_STATS.ac[newLevel]-ARMY_STATS.ac[currentLevel])},details:{level:{value:newLevel}},saves:{maneuver:this.system.saves.maneuver+(strongSave==="maneuver"?strongSaveDifference:weakSaveDifference),morale:this.system.saves.morale+(strongSave==="morale"?strongSaveDifference:weakSaveDifference)},scouting:this.system.scouting+(ARMY_STATS.scouting[newLevel]-ARMY_STATS.scouting[currentLevel])}})}checkItemValidity(source){if(source.type==="campaignFeature"&&source.system?.category==="army-tactic"){const validArmyTypes=ARMY_TYPES.filter(t=>source.system?.traits?.value?.includes(t));if(validArmyTypes.length>0&&!validArmyTypes.includes(this.system.traits.type))return ui.notifications.error(game.i18n.format("PF2E.Kingmaker.Army.Error.InvalidTacticType",{name:source.name,type:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[this.system.traits.type])})),!1}return super.checkItemValidity(source)}getStatistic(slug){return tupleHasValue(["scouting","morale","maneuver"],slug)?this[slug]:this.kingdom?.getStatistic(slug)??super.getStatistic(slug)}_preUpdate(changed,options,user){if(typeof changed?.system?.attributes?.hp?.value=="number"){const max=Number(changed.system.attributes.hp.max??this.system.attributes.hp.max);changed.system.attributes.hp.value=Math.clamped(changed.system.attributes.hp.value,0,max)}return super._preUpdate(changed,options,user)}}class HazardPF2e extends ActorPF2e{static{__name(this,"HazardPF2e")}static{__name2(this,"HazardPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action","melee"]}get rarity(){return this.system.traits.rarity}get isComplex(){return this.system.details.isComplex}get hardness(){return Math.abs(this.system.attributes.hardness)}get hasDefenses(){return!!(this.hitPoints?.max||this.attributes.ac.value)}get canAttack(){return this.itemTypes.melee.length>0}get emitsSound(){const{emitsSound}=this.system.attributes;return!this.isDead&&typeof emitsSound=="boolean"?emitsSound:!!game.combats.active?.started&&game.combats.active.combatants.some(c=>c.actor===this)}isAffectedBy(effect){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,effect)?effect:isObject(effect)?effect.system.persistent?.damageType??null:null;if(!this.system.attributes.hasHealth&&damageType)return!1;const{weaknesses,resistances}=this.system.attributes;return damageType&&["vitality","void"].includes(damageType)?weaknesses.some(w=>w.type===damageType)||resistances.some(r=>r.type===damageType):super.isAffectedBy(effect)}prepareBaseData(){super.prepareBaseData();const{attributes,details}=this.system;if(attributes.hp.negativeHealing=!1,attributes.hp.brokenThreshold=Math.floor(attributes.hp.max/2),attributes.hasHealth=attributes.hp.max>0,attributes.immunities.some(i=>i.type==="object-immunities")||attributes.immunities.unshift(new Immunity({type:"object-immunities",source:"TYPES.Actor.hazard"})),this.isComplex){attributes.stealth.value??=0;const partialAttributes=this.system.attributes;partialAttributes.initiative={statistic:"stealth",tiebreakPriority:this.hasPlayerOwner?2:1}}details.alliance=null}prepareDerivedData(){super.prepareDerivedData();const{system}=this;if(this.prepareSynthetics(),setHitPointsRollOptions(this),this.skills={stealth:new Statistic(this,{slug:"stealth",label:CONFIG.PF2E.skillList.stealth,domains:["stealth","dex-based","skill-check","dex-skill-check","all"],modifiers:[new ModifierPF2e({label:"PF2E.ModifierTitle",slug:"base",type:"untyped",modifier:system.attributes.stealth.value??0})],check:{type:"skill-check"}})},system.attributes.initiative&&(this.initiative=new ActorInitiative(this,{statistic:"stealth"}),system.attributes.initiative=this.initiative.getTraceData()),this.hasDefenses){const baseModifier=new ModifierPF2e({slug:"base",label:"PF2E.BaseModifier",modifier:system.attributes.ac.value-10}),statistic=new ArmorStatistic(this,{rank:1,modifiers:[baseModifier]});this.armorClass=statistic.dc,system.attributes.ac=statistic.getTraceData()}this.saves=this.prepareSaves(),this.system.actions=this.itemTypes.melee.map(m=>strikeFromMeleeItem(m))}prepareData(){super.prepareData();const weaknessesAndResistances=new Set([this.system.attributes.weaknesses.map(w=>w.type),this.system.attributes.resistances.map(r=>r.type)].flat()),objectImmunities=this.system.attributes.immunities.find(i=>i.type==="object-immunities");for(const wrType of["bleed","mental","poison","spirit"])weaknessesAndResistances.has(wrType)&&objectImmunities?.exceptions.push(wrType)}prepareSaves(){const{system}=this;return SAVE_TYPES.reduce((saves,saveType)=>{const save=system.saves[saveType],label=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value;if(!base)return saves;const statistic=new Statistic(this,{slug:saveType,label,attribute:CONFIG.PF2E.savingThrowDefaultAttributes[saveType],domains:[saveType,"saving-throw"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base})],check:{type:"saving-throw"}});return this.system.saves[saveType]=foundry.utils.mergeObject(save,statistic.getTraceData()),saves[saveType]=statistic,saves},{})}}class LootPF2e extends ActorPF2e{static{__name(this,"LootPF2e")}static{__name2(this,"LootPF2e")}armorClass=null;get allowedItemTypes(){return["physical"]}get isLoot(){return this.system.lootSheetType==="Loot"}get isMerchant(){return this.system.lootSheetType==="Merchant"}get hiddenWhenEmpty(){return this.isLoot&&this.system.hiddenWhenEmpty}get canHostRuleElements(){return!1}get canAct(){return!1}isAffectedBy(){return!1}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return action2==="update"?this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED:super.canUserModify(user,action2)}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(this.isOwner&&targetActor.isOwner))return super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isMerchant&&item.isOfType("physical")){const itemValue=CoinsPF2e.fromPrice(item.price,quantity);if(await targetActor.inventory.removeCoins(itemValue))return await item.actor.inventory.addCoins(itemValue),super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isLoot)throw ErrorPF2e("Loot transfer failed");return null}return super.transferItemToActor(targetActor,item,quantity,containerId,newStack)}async toggleTokenHiding(){if(!this.hiddenWhenEmpty||!this.isOwner)return;const hiddenStatus=this.items.size===0,promises=game.scenes.map(s=>[s,s.tokens.filter(t=>t.actor===this)]).map(([scene,tokenDocs])=>scene.updateEmbeddedDocuments("Token",tokenDocs.map(tokenDoc=>({_id:tokenDoc.id,hidden:hiddenStatus}))));await Promise.allSettled(promises)}prepareDerivedData(){this.rules=[],super.prepareDerivedData()}_onCreate(data,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreate(data,options,userId)}_onUpdate(changed,options,userId){game.user.id===userId&&changed.system?.hiddenWhenEmpty!==void 0&&this.toggleTokenHiding(),super._onUpdate(changed,options,userId)}_onCreateDescendantDocuments(parent,collection,documents,result,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreateDescendantDocuments(parent,collection,documents,result,options,userId)}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId)}}const{DataModel}=foundry.abstract;class InvalidCampaign extends DataModel{static{__name(this,"InvalidCampaign")}static{__name2(this,"InvalidCampaign")}type="invalid";actor;options;constructor(actor,options){super(),this.actor=actor,this.options=options}static defineSchema(){return{}}createSidebarButtons(){const icon=createHTMLElement("a",{children:[fontAwesomeIcon("warning",{fixedWidth:!0})]});return icon.title=game.i18n.localize("PF2E.Actor.Party.InvalidCampaign.Hint"),game.user.isGM?icon.addEventListener("click",()=>{new Dialog({title:game.i18n.format("PF2E.Actor.Party.InvalidCampaign.Title",{party:this.actor.name}),content:game.i18n.format(`PF2E.Actor.Party.InvalidCampaign.Message.${this.options.reason}`,{current:this.actor.system.campaign?.type??"",...this.options}),buttons:{yes:{icon:fontAwesomeIcon("trash").outerHTML,label:game.i18n.localize("Yes"),callback:async()=>{await this.actor.update({"system.-=campaign":null}),ui.sidebar.render()}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}}}).render(!0)}):icon.style.pointerEvents="none",[icon]}}class PartyPF2e extends ActorPF2e{static{__name(this,"PartyPF2e")}static{__name2(this,"PartyPF2e")}armorClass=null;get active(){return game.actors.party===this}get baseAllowedItemTypes(){return["physical"]}get allowedItemTypes(){return[...this.baseAllowedItemTypes,...this.campaign?.extraItemTypes??[]]}get canAct(){return!1}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.members.some(m=>m.canUserModify(user,action2))}isAffectedBy(){return!1}validate(options){if(!super.validate(options))return!1;const changes=options?.changes??{};return!(changes.system?.campaign&&!this.campaign?.validate({...options,changes:changes.system.campaign}))}updateSource(data,options){if(!this.campaign)return super.updateSource(data,options);const expanded=foundry.utils.expandObject(data??{}),campaignDiff=expanded?.system?.campaign?this.campaign.updateSource(expanded.system.campaign,options):{},diff=super.updateSource(data,options);return isEmpty(campaignDiff)?diff:foundry.utils.mergeObject(diff,campaignDiff)}prepareRuleElements(){return this.items.contents.filter(item=>!item.isOfType("physical")).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}_initialize(options){super._initialize(options),Object.defineProperty(this.system,"campaign",{writable:!0,enumerable:!1})}prepareBaseData(){this.system.details.level={value:0},super.prepareBaseData(),this.members=this.system.details.members.map(m=>fromUuidSync(m.uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature")).sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));for(const member of this.members)member?.parties.add(this);this.system.details.alliance=this.members.some(m=>m.alliance==="party")?"party":this.members.some(m=>m.alliance==="opposition")?"opposition":null;const campaignType=game.settings.get("pf2e","campaignType");if(campaignType!=="none"){const typeMatches=this.system.campaign?.type===campaignType;if(this.system.campaign&&!typeMatches)this.campaign=new InvalidCampaign(this,{campaignType,reason:"mismatch"});else try{this.campaign?.type!==campaignType?this.campaign=new Kingdom(foundry.utils.deepClone(this._source.system.campaign),{parent:this}):(Kingdom.cleanData(this.campaign._source),this.campaign.reset()),this.campaign.prepareBaseData?.(),this.system.campaign=this.campaign}catch(err){console.error(err),this.campaign=new InvalidCampaign(this,{campaignType,reason:"error"})}}else this.campaign=null;const partyLevel=Math.round(meanBy(this.members.filter(m=>m.isOfType("character")),m=>m.level));this.system.details.level.value=partyLevel}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData();const travelSpeed=Math.min(...this.members.map(m=>m.attributes.speed.total));this.attributes.speed={total:travelSpeed},this.prepareSynthetics(),this.campaign?.prepareDerivedData?.()}async addMembers(...membersToAdd){const existing=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)),existingUUIDs=new Set(existing.map(data=>data.uuid)),newMembers=membersToAdd.filter(a=>a.uuid.startsWith("Actor.")&&!existingUUIDs.has(a.uuid));for(const member of newMembers){const allianceUpdate=member.isOfType("character","npc")?{"system.details.alliance":member._source.system.details.alliance??"party"}:{};await member.update({folder:null,...allianceUpdate})}const members=[...existing,...newMembers.map(m=>({uuid:m.uuid}))];await this.update({system:{details:{members}}}),await resetActors(newMembers)}async removeMembers(...remove2){const uuids=remove2.map(d=>typeof d=="string"?d:d.uuid),members=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)).filter(m=>!tupleHasValue(uuids,m.uuid));await this.update({system:{details:{members}}})}async addToCombat(options={}){const promises=this.members.map(a=>CombatantPF2e.fromActor(a,!0,{combat:options.combat}));return(await Promise.all(promises)).filter(c=>!!c)}getRollOptions(domains){return super.getRollOptions(domains).concat(this.campaign?.getRollOptions?.()??[])}getRollData(){return foundry.utils.mergeObject(super.getRollData(),this.campaign?.getRollData?.()??{})}reset({actor=!1}={}){actor?this._resetAndRerenderDebounced():super.reset()}getStatistic(slug){const statistic=super.getStatistic(slug);return statistic||(this.campaign?.getStatistic?.(slug)??null)}_resetAndRerenderDebounced=foundry.utils.debounce(()=>{super.reset(),this.sheet.render(!1,{actor:!0})},50);async _preUpdate(changed,options,user){const members=this.members,newMemberUUIDs=changed?.system?.details?.members?.map(m=>m?.uuid);if(newMemberUUIDs){const deletedMembers=members.filter(m=>m?.uuid&&!newMemberUUIDs.includes(m.uuid));options.removedMembers=deletedMembers.map(m=>m.uuid)}return changed.system?.campaign&&this.campaign&&this.campaign.type!=="invalid"&&(changed.system.campaign.type=this.campaign.type,this.campaign._preUpdate?.(changed.system.campaign)),super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const removedCreatures=(options.removedMembers??[]).map(uuid=>fromUuidSync(uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature"));for(const actor of removedCreatures)actor.parties.delete(this);if(resetActors(removedCreatures),changed.system?.details?.members&&game.combat)for(const encounter of game.combats)encounter.reset(),ui.combat.render();game.ready&&changed.system?.campaign&&game.actors.get(this.id)===this&&ui.actors.render()}_onDelete(options,userId){super._onDelete(options,userId);for(const member of this.members)member.parties.delete(this);resetActors(this.members),ui.actors.saveActivePartyFolderState()}}class VehiclePF2e extends ActorPF2e{static{__name(this,"VehiclePF2e")}static{__name2(this,"VehiclePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","action"]}get dimensions(){return{length:this.system.details.space.long,width:this.system.details.space.wide,height:this.system.details.space.high}}get hardness(){return this.system.attributes.hardness}getTokenDimensions(dimensions=this.dimensions){return{width:Math.max(Math.round(dimensions.width/5),1),height:Math.max(Math.round(dimensions.length/5),1)}}prepareBaseData(){super.prepareBaseData(),this.system.details.alliance=null;const{size}=this.system.traits,{dimensions}=this;if(size.length=dimensions.length,size.width=dimensions.width,this.prototypeToken.flags?.pf2e?.linkToActorSize){const{width,height}=this.getTokenDimensions();this.prototypeToken.width=width,this.prototypeToken.height=height}}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){if(super.prepareDerivedData(),this.prepareSynthetics(),this.hasCondition("broken"))for(const selector of["ac","saving-throw"]){const modifiers=this.synthetics.modifiers[selector]??=[],brokenModifier=new ModifierPF2e({slug:"broken",label:"PF2E.ConditionTypeBroken",modifier:-2,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,[selector],"broken")});modifiers.push(()=>brokenModifier)}const{attributes}=this,hitPoints=new HitPointsStatistic(this,{baseMax:attributes.hp.max});attributes.hp=foundry.utils.mergeObject(hitPoints.getTraceData(),{brokenThreshold:Math.floor(hitPoints.max/2)}),setHitPointsRollOptions(this);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:this.system.attributes.ac.value-10,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all","ac"],"base")})]});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves()}prepareSaves(){const{synthetics}=this,slug="fortitude",domains=[slug,"saving-throw","all"],modifiers=[new ModifierPF2e({label:"PF2E.ModifierTitle",slug,type:"untyped",modifier:this.system.saves.fortitude.value}),...extractModifiers(synthetics,domains)],fortitude=new Statistic(this,{slug:"fortitude",label:CONFIG.PF2E.saves.fortitude,modifiers,domains,check:{type:"saving-throw"}});this.saves={fortitude},this.system.saves.fortitude=foundry.utils.mergeObject(this.system.saves.fortitude,fortitude.getTraceData())}async _preUpdate(changed,options,user){const result=await super._preUpdate(changed,options,user);if(result===!1)return result;if(this.prototypeToken.flags?.pf2e?.linkToActorSize){const{space}=this.system.details,spaceUpdates={width:changed.system?.details?.space?.wide??space.wide,length:changed.system?.details?.space?.long??space.long},tokenDimensions=this.getTokenDimensions(spaceUpdates);if(changed.prototypeToken=foundry.utils.mergeObject(changed.prototypeToken??{},tokenDimensions),canvas.scene){const updates=this.getActiveTokens().filter(token=>token.document.linkToActorSize).map(token=>({_id:token.id,...tokenDimensions}));await TokenDocumentPF2e.updateDocuments(updates,{parent:canvas.scene})}}}}function extractModifiers(synthetics,selectors,options={}){const{modifierAdjustments,modifiers:syntheticModifiers}=synthetics,modifiers=Array.from(new Set(selectors)).flatMap(s=>syntheticModifiers[s]??[]).flatMap(d=>d(options)??[]);for(const modifier of modifiers)modifier.adjustments=extractModifierAdjustments(modifierAdjustments,selectors,modifier.slug);return modifiers}__name(extractModifiers,"extractModifiers"),__name2(extractModifiers,"extractModifiers");function extractModifierAdjustments(adjustmentsRecord,selectors,slug){return Array.from(new Set(selectors.flatMap(s=>adjustmentsRecord[s]??[]))).filter(a=>[slug,null].includes(a.slug))}__name(extractModifierAdjustments,"extractModifierAdjustments"),__name2(extractModifierAdjustments,"extractModifierAdjustments");function extractNotes(rollNotes,selectors){return selectors.flatMap(s=>(rollNotes[s]??[]).map(n=>n.clone()))}__name(extractNotes,"extractNotes"),__name2(extractNotes,"extractNotes");function extractDamageDice(deferredDice,selectors,options){return selectors.flatMap(s=>deferredDice[s]??[]).flatMap(d=>d(options)??[])}__name(extractDamageDice,"extractDamageDice"),__name2(extractDamageDice,"extractDamageDice");function processDamageCategoryStacking(base,options){const{dice}=options,groupedModifiers=groupBy$1(options.modifiers,m=>m.category==="persistent"?"persistent":"main"),modifiers=[...new StatisticModifier("damage",groupedModifiers.main??[],options.test).modifiers,...new StatisticModifier("persistent",groupedModifiers.persistent??[],options.test).modifiers],allPersistent=base.length>0&&base.every(b=>b.category==="persistent");return{modifiers:allPersistent?modifiers.filter(m=>m.category==="persistent"):modifiers,dice:allPersistent?dice.filter(m=>m.category==="persistent"):dice}}__name(processDamageCategoryStacking,"processDamageCategoryStacking"),__name2(processDamageCategoryStacking,"processDamageCategoryStacking");async function extractEphemeralEffects({affects,origin,target,item,domains,options}){if(!(origin&&target))return[];const[effectsFrom,effectsTo]=affects==="target"?[origin,target]:[target,origin],fullOptions=[...options,effectsFrom.getRollOptions(domains),effectsTo.getSelfRollOptions(affects)].flat(),resolvables=item?item.isOfType("spell")?{spell:item}:{weapon:item}:{};return(await Promise.all(domains.flatMap(s=>effectsFrom.synthetics.ephemeralEffects[s]?.[affects]??[]).map(d=>d({test:fullOptions,resolvables})))).flatMap(e=>e??[])}__name(extractEphemeralEffects,"extractEphemeralEffects"),__name2(extractEphemeralEffects,"extractEphemeralEffects");function extractRollTwice(rollTwices,selectors,options){const twices=selectors.flatMap(s=>rollTwices[s]??[]).filter(rt=>rt.predicate?.test(options)??!0);return twices.length===0||twices.some(rt=>rt.keep==="higher")&&twices.some(rt=>rt.keep==="lower")?!1:twices.at(0)?.keep==="higher"?"keep-higher":"keep-lower"}__name(extractRollTwice,"extractRollTwice"),__name2(extractRollTwice,"extractRollTwice");function extractRollSubstitutions(substitutions,domains,rollOptions){return domains.flatMap(d=>foundry.utils.deepClone(substitutions[d]??[])).filter(s=>s.predicate?.test(rollOptions)??!0)}__name(extractRollSubstitutions,"extractRollSubstitutions"),__name2(extractRollSubstitutions,"extractRollSubstitutions");function extractDegreeOfSuccessAdjustments(synthetics,selectors){return Object.values(pick(synthetics.degreeOfSuccessAdjustments,selectors)).flat()}__name(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments"),__name2(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments");function isBracketedValue(value){return isObject$1(value)&&Array.isArray(value.brackets)}__name(isBracketedValue,"isBracketedValue"),__name2(isBracketedValue,"isBracketedValue");async function processPreUpdateActorHooks(changed,{pack}){const actorId=String(changed._id),actor=pack?await game.packs.get(pack)?.getDocument(actorId):game.actors.get(actorId);if(!(actor instanceof ActorPF2e))return;const rules=actor.rules.filter(r=>!!r.preUpdateActor);if(rules.length===0)return;actor.flags.pf2e.rollOptions=actor.clone(changed,{keepId:!0}).flags.pf2e.rollOptions;const createDeletes=(await Promise.all(rules.map(r=>actor.items.has(r.item.id)?r.preUpdateActor():new Promise(()=>({create:[],delete:[]}))))).reduce((combined,cd)=>(combined.create.push(...cd.create),combined.delete.push(...cd.delete),combined),{create:[],delete:[]});createDeletes.delete=uniq(createDeletes.delete).filter(id=>actor.items.has(id)),createDeletes.create.length>0&&await actor.createEmbeddedDocuments("Item",createDeletes.create,{keepId:!0,render:!1}),createDeletes.delete.length>0&&await actor.deleteEmbeddedDocuments("Item",createDeletes.delete,{render:!1})}__name(processPreUpdateActorHooks,"processPreUpdateActorHooks"),__name2(processPreUpdateActorHooks,"processPreUpdateActorHooks");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"]);class ModifierPF2e{static{__name(this,"ModifierPF2e")}static{__name2(this,"ModifierPF2e")}slug;label;modifier;#originalValue;type;ability;adjustments;force;enabled;ignored;rule;source;custom;damageType;damageCategory;predicate;critical;traits;hideIfDisabled;kind;constructor(...args){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]}:args[0];if(this.label=game.i18n.localize(params.label??params.name),this.slug=sluggify(params.slug??this.label),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=foundry.utils.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.traits=foundry.utils.deepClone(params.traits??[]),this.hideIfDisabled=params.hideIfDisabled??!1,this.modifier=params.modifier,this.rule=params.rule??null,Object.defineProperty(this,"rule",{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):signedInteger(this.modifier)}clone(options={}){const clone=this.modifier===this.#originalValue?new ModifierPF2e(this):new ModifierPF2e({...this,modifier:this.#originalValue});return options.test&&clone.test(options.test),clone}getRollOptions(){const options=["slug","type","value"].map(p=>`${this.kind}:${p}:${this[p]}`);return this.type==="ability"&&this.ability&&options.push(`modifier:ability:${this.ability}`),new Set(options)}test(options){if(this.predicate.length===0)return;const rollOptions=this.rule?[...options,...this.rule.item.getRollOptions("parent")]:options;this.ignored=!this.predicate.test(rollOptions)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate],rule:this.rule?.toObject(),item:void 0})}toString(){return this.label}}function createAttributeModifier({actor,attribute,domains,max}){const withAttributeBased=domains.includes(`${attribute}-based`)?domains:[...domains,`${attribute}-based`],modifierValue=actor.abilities[attribute].mod,cappedValue=Math.min(modifierValue,max??modifierValue);return new ModifierPF2e({slug:attribute,label:CONFIG.PF2E.abilities[attribute],modifier:cappedValue,type:"ability",ability:attribute,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,withAttributeBased,attribute)})}__name(createAttributeModifier,"createAttributeModifier"),__name2(createAttributeModifier,"createAttributeModifier");function createProficiencyModifier({actor,rank,domains,level,addLevel}){rank=Math.clamped(rank,0,4),addLevel??=rank>0;const pwolVariant=game.pf2e.settings.variants.pwol.enabled,baseBonuses=pwolVariant?game.pf2e.settings.variants.pwol.modifiers:[0,2,4,6,8],addedLevel=addLevel&&!pwolVariant?level??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{static{__name(this,"StatisticModifier")}static{__name2(this,"StatisticModifier")}slug;_modifiers;breakdown="";notes;constructor(slug,modifiers=[],rollOptions=new Set){rollOptions=rollOptions instanceof Set?rollOptions:new Set(rollOptions),this.slug=slug;const seen=modifiers.reduce((result,modifier)=>((!result[modifier.slug]?.enabled||Math.abs(modifier.modifier)>Math.abs(result[modifier.slug].modifier))&&(result[modifier.slug]=modifier),result),{});this._modifiers=Object.values(seen),this.calculateTotal(rollOptions)}get modifiers(){return[...this._modifiers]}push(modifier){const existingIdx=this._modifiers.findIndex(o=>o.slug===modifier.slug),existing=this._modifiers[existingIdx];return existing?Math.abs(modifier.modifier)>Math.abs(existing.modifier)&&(this._modifiers[existingIdx]=modifier,this.calculateTotal()):(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)}}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.test([...rollOptions,...modifier.getRollOptions()]));if(adjustments.some(a=>a.suppress)){modifier.ignored=!0;continue}const resolvedAdjustment=adjustments.reduce((resolved,adjustment)=>{const newValue=adjustment.getNewValue?.(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)=>adjustment.getDamageType?.(damageType)??damageType,modifier.damageType)}}__name(adjustModifiers,"adjustModifiers"),__name2(adjustModifiers,"adjustModifiers");class CheckModifier extends StatisticModifier{static{__name(this,"CheckModifier")}static{__name2(this,"CheckModifier")}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)}}class DamageDicePF2e{static{__name(this,"DamageDicePF2e")}static{__name2(this,"DamageDicePF2e")}selector;slug;label;diceNumber;dieSize;critical;category;damageType;override;ignored;enabled;custom;predicate;constructor(params){if(params.selector)this.selector=params.selector;else throw ErrorPF2e("`selector` is mandatory");if(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.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.critical=this.category==="splash"?!!params.critical:params.critical??null,this.predicate=params.predicate instanceof PredicatePF2e?params.predicate:new PredicatePF2e(params.predicate??[]),this.enabled=params.enabled??this.predicate.test([]),this.ignored=params.ignored??!this.enabled}test(options){this.enabled=this.predicate.test(options),this.ignored=!this.enabled}clone(){return new DamageDicePF2e(this)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate]})}}function isCheckContextFlag(flag){return!!flag&&!tupleHasValue(["damage-roll","spell-cast"],flag.type)}__name(isCheckContextFlag,"isCheckContextFlag"),__name2(isCheckContextFlag,"isCheckContextFlag");async function createSelfEffectMessage(item,rollMode="roll"){if(!item.system.selfEffect)throw ErrorPF2e(["Only actions with self-applied effects can be passed to `ActorPF2e#useAction`.","Support will be expanded at a later time."].join(" "));const{actor,actionCost}=item,token=actor.getActiveTokens(!0,!0).shift()??null,speaker=ChatMessagePF2e.getSpeaker({actor,token}),flavor=await renderTemplate("systems/pf2e/templates/chat/action/flavor.hbs",{action:{title:item.name,glyph:getActionGlyph(actionCost)},item,traits:item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits))}),previewLength=100,descriptionPreview=(()=>{if(item.actor.pack)return null;const tempDiv=document.createElement("div"),documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],linkPattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g");return tempDiv.innerHTML=item.description.replace(linkPattern,(_match,...args)=>args[3]),tempDiv.innerText.slice(0,previewLength)})(),description={full:descriptionPreview&&descriptionPreview.length<previewLength?item.description:null,preview:descriptionPreview},content=await renderTemplate("systems/pf2e/templates/chat/action/self-effect.hbs",{actor:item.actor,description}),flags={pf2e:{context:{type:"self-effect",item:item.id}}},messageData=ChatMessagePF2e.applyRollMode({speaker,flavor,content,flags},rollMode);return ChatMessagePF2e.create(messageData)}__name(createSelfEffectMessage,"createSelfEffectMessage"),__name2(createSelfEffectMessage,"createSelfEffectMessage");async function applyDamageFromMessage({message,multiplier=1,addend=0,promptModifier=!1,rollIndex=0}){if(promptModifier)return shiftAdjustDamage(message,multiplier,rollIndex);const tokens=htmlQuery(ui.chat.element[0],`li.chat-message[data-message-id="${message.id}"]`)?.dataset.actorIsTarget&&message.token?[message.token]:game.user.getActiveTokens();if(tokens.length===0){ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0});return}const shieldBlockRequest=CONFIG.PF2E.chatDamageButtonShieldToggle,roll=message.rolls.at(rollIndex);if(!(roll instanceof DamageRoll))throw ErrorPF2e("Unexpected error retrieving damage roll");let damage=multiplier<0?multiplier*roll.total+addend:roll.alter(multiplier,addend);const messageRollOptions=[...message.flags.pf2e.context?.options??[]],originRollOptions=messageRollOptions.filter(o=>o.startsWith("self:")).map(o=>o.replace(/^self/,"origin")),messageItem=message.item;for(const token of tokens){if(!token.actor)continue;messageRollOptions.some(o=>o.startsWith("target"))||messageRollOptions.push(...token.actor.getSelfRollOptions("target"));const domain=multiplier>0?"damage-received":"healing-received",ephemeralEffects=multiplier>0?await extractEphemeralEffects({affects:"target",origin:message.actor,target:token.actor,item:message.item,domains:[domain],options:messageRollOptions}):[],contextClone=token.actor.getContextualClone(originRollOptions,ephemeralEffects),applicationRollOptions=new Set([...messageRollOptions.filter(o=>!/^(?:self|target):/.test(o)),...originRollOptions,...contextClone.getSelfRollOptions()]),outcome=message.flags.pf2e.context?.outcome,breakdown=[],rolls=[];if(typeof damage=="number"&&damage<0){const critical=outcome==="criticalSuccess",resolvables=(()=>messageItem?.isOfType("spell")?{spell:messageItem}:messageItem?.isOfType("weapon")?{weapon:messageItem}:{})(),damageDice=extractDamageDice(contextClone.synthetics.damageDice,[domain],{resolvables,test:applicationRollOptions}).filter(d=>(d.critical===null||d.critical===critical)&&d.predicate.test(applicationRollOptions));for(const dice of damageDice){const formula=`${dice.diceNumber}${dice.dieSize}[${dice.label}]`,roll2=await new Roll(formula).evaluate({async:!0});roll2._formula=`${dice.diceNumber}${dice.dieSize}`,await roll2.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor:dice.label,speaker:ChatMessage.getSpeaker({token})}),breakdown.push(`${dice.label} ${dice.diceNumber}${dice.dieSize}`),rolls.push(roll2)}rolls.length&&(damage-=rolls.map(roll2=>roll2.total).reduce((previous,current)=>previous+current));const modifiers=extractModifiers(contextClone.synthetics,[domain],{resolvables}).filter(m=>(m.critical===null||m.critical===critical)&&m.predicate.test(applicationRollOptions));damage-=applyStackingRules(modifiers??[]),breakdown.push(...modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`))}const hasDamage=typeof damage=="number"?damage!==0:damage.total!==0,notes=(()=>hasDamage?extractNotes(contextClone.synthetics.rollNotes,[domain]).filter(n=>(!outcome||n.outcome.length===0||n.outcome.includes(outcome))&&n.predicate.test(applicationRollOptions)).map(note=>note.text):[])();await contextClone.applyDamage({damage,token,item:message.item,skipIWR:multiplier<=0,rollOptions:applicationRollOptions,shieldBlockRequest,breakdown,notes})}toggleOffShieldBlock(message.id)}__name(applyDamageFromMessage,"applyDamageFromMessage"),__name2(applyDamageFromMessage,"applyDamageFromMessage");async function shiftAdjustDamage(message,multiplier,rollIndex){const content=await renderTemplate("systems/pf2e/templates/chat/damage/adjustment-dialog.hbs"),AdjustmentDialog=class extends Dialog{static{__name(this,"AdjustmentDialog")}static{__name2(this,"AdjustmentDialog")}activateListeners($html){super.activateListeners($html),$html[0].querySelector("input")?.focus()}},isHealing=multiplier<0;new AdjustmentDialog({title:game.i18n.localize(isHealing?"PF2E.UI.shiftModifyHealingTitle":"PF2E.UI.shiftModifyDamageTitle"),content,buttons:{ok:{label:game.i18n.localize("PF2E.OK"),callback:async $dialog=>{const adjustment=(Number($dialog[0].querySelector("input")?.value)||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}},cancel:{label:"Cancel"}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){for(const app of["#chat-log","#chat-popout"]){const selector=`${app} > li.chat-message[data-message-id="${messageId}"] button[data-action=shield-block]`;htmlQuery(document.body,selector)?.classList.remove("shield-activated")}CONFIG.PF2E.chatDamageButtonShieldToggle=!1}__name(toggleOffShieldBlock,"toggleOffShieldBlock"),__name2(toggleOffShieldBlock,"toggleOffShieldBlock");function toggleClearTemplatesButton(message){if(!message||!canvas.ready)return;const selector=`li[data-message-id="${message.id}"] button[data-action=spell-template-clear]`;for(const chatLogDOM of htmlQueryAll(document.body,"#chat-log, #chat-popout")){const clearTemplatesButton=htmlQuery(chatLogDOM,selector);if(!clearTemplatesButton)continue;const hasMeasuredTemplates=!!canvas.scene?.templates.some(t=>t.message===message&&t.isOwner);clearTemplatesButton.classList.toggle("hidden",!hasMeasuredTemplates)}}__name(toggleClearTemplatesButton,"toggleClearTemplatesButton"),__name2(toggleClearTemplatesButton,"toggleClearTemplatesButton");const CanvasReady={listen:()=>{Hooks.once("canvasReady",async()=>{await game.pf2e.ConditionManager.initialize();const tokenActors=canvas.scene?.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",()=>{if(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.filter(t=>t.visible))token.renderFlags.set({redrawEffects:!0});for(const message of game.messages.contents.slice(-1*CONFIG.ChatMessage.batchSize/2))toggleClearTemplatesButton(message)}})}},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"})})}})}},DropCanvasData={listen:()=>{Hooks.on("dropCanvasData",(_canvas,data)=>{const actor=[...canvas.tokens.placeables].sort((a,b)=>b.document.sort-a.document.sort).find(token=>{const maximumX=token.x+(token.hitArea?.right??0),maximumY=token.y+(token.hitArea?.bottom??0);return data.x>=token.x&&data.y>=token.y&&data.x<=maximumX&&data.y<=maximumY})?.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=>foundry.utils.mergeObject(baseConditionSource,{system:{persistent:{formula:i.head.expression,damageType:i.type,dc:15}}}));return actor.createEmbeddedDocuments("Item",conditions),!1}return!0})}},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=interval.end?darknessLevelAtTime(interval.end):NaN,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)=>dtA<dtB?-1:dtA>dtB?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||{});class TimeOfDay{static{__name(this,"TimeOfDay")}static{__name2(this,"TimeOfDay")}constructor(hour,minute,second){this.hour=hour,this.minute=minute,this.second=second}static DAWN=new TimeOfDay(4,58,54);static NOON=new TimeOfDay(12,0,0);static DUSK=new TimeOfDay(18,34,6);static MIDNIGHT=new TimeOfDay(0,0,0);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}}class WorldClock extends Application{static{__name(this,"WorldClock")}static{__name2(this,"WorldClock")}ctrlKeyDown=!1;animateDarkness=animateDarkness;constructor(){super();const settingValue=game.settings.get("pf2e","worldClock.worldCreatedOn"),defaultValue=game.settings.settings.get("pf2e.worldClock.worldCreatedOn")?.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(){const sceneSetting=canvas.scene?.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 foundry.utils.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:ordinalString(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:"fa-solid 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",event2=>{const $button=$(event2.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",event2=>{const value=$html.find('input[type=number][name="diff-value"]').val(),unit=$html.find('select[name="diff-unit"]').val(),increment=($(event2.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,event2=>{const{originalEvent}=event2;if(!(originalEvent instanceof KeyboardEvent))return;const ctrlKeys=KeyboardManager.CONTROL_KEY_STRING==="\u2318"?["Control","Meta"]:["Control"];if(originalEvent.repeat||!ctrlKeys.includes(originalEvent.key)||!(event2.ctrlKey||this.ctrlKeyDown))return;const retractTime=this.ctrlKeyDown=event2.type==="keydown",{Advance,Retract,TimeOfDay:TimeOfDay2}=CONFIG.PF2E.worldClock.Button,advanceButtons=Array.from($html.get(0)?.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",event2=>{event2.preventDefault(),event2.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}}class SceneDarknessAdjuster extends Application{static{__name(this,"SceneDarknessAdjuster")}static{__name2(this,"SceneDarknessAdjuster")}static instance=new this;#slider;#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={}){return{...await super.getData(options),darknessSyncedToTime:!!game.scenes.viewed?.darknessSyncedToTime}}async render(force=!1,options={}){if(!game.scenes.viewed)return this;const bounds=ui.controls.element[0]?.querySelector("li[data-tool=darkness-adjuster]")?.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){if(!game.scenes.viewed)return;const slider=$html[0].querySelector(".slider");if(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:PipsMode.Range,density:5},step:.05}),game.scenes.viewed?.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)=>{index!==1&&$(thumb).attr({disabled:"disabled"}),game.scenes.viewed?.darknessSyncedToTime&&thumb.setAttribute("disabled","true")}),this.#slider.on("slide",(values,thumbNumber)=>{thumbNumber===1&&canvas.scene&&(this.#noRefreshHook=!0,canvas.colorManager.initialize({darknessLevel:Number(values[1])}),canvas.app.ticker.add(()=>{this.#noRefreshHook=!1}))}),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){if(!this.rendered||this.#noRefreshHook)return;const sliderValues=this.#slider?.get();if(this.#slider&&Array.isArray(sliderValues)){const currentValue=sliderValues[1],stepValue=Math.round(darkness*20)/20;stepValue!==currentValue&&(sliderValues[1]=stepValue,this.#slider.set(sliderValues))}}}const GetSceneControlButtons={listen:()=>{Hooks.on("getSceneControlButtons",controls=>{controls.find(c=>c.name==="token")?.tools?.push({name:"worldclock",title:"CONTROLS.WorldClock",icon:"fa-solid 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.pf2e.settings.rbv,toggle:!0,active:!1,onClick:()=>{const adjuster=SceneDarknessAdjuster.instance;adjuster.rendered?adjuster.close({force:!0}):adjuster.render(!0)}},gmVisionTool=(()=>{const binding=game.keybindings.actions.get("pf2e.gm-vision")?.editable?.[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:()=>{const newStatus=!game.settings.get("pf2e","gmVision");game.settings.set("pf2e","gmVision",newStatus);const toggle=ui.controls.control?.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)})}},I18nInit={listen:()=>{Hooks.once("i18nInit",()=>{new HomebrewElements().onInit()})}};class HotbarPF2e extends Hotbar{static{__name(this,"HotbarPF2e")}static{__name2(this,"HotbarPF2e")}async _onDrop(event2){const li=htmlClosest(event2.target,".macro"),slot=Number(li?.dataset.slot)||null;if(!slot)return;const data=TextEditor.getDragEventData(event2);if(!["Item","RollOption","Skill","Action"].includes(data.type??""))return super._onDrop(event2);if(Hooks.call("hotbarDrop",this,data,slot)!==!1)switch(data.type==="Item"&&data.itemType==="melee"&&typeof data.index=="number"&&(data.type="Action"),data.type){case"Item":{const itemId=data.id??(isObject(data.data)?data.data._id:null),uuid=data.uuid,prefix=typeof data.pack=="string"?`Compendium.${data.pack}`:typeof data.actorId=="string"?`Actor.${data.actorId}.Item`:"Item",item=await fromUuid(uuid??`${prefix}.${itemId}`);if(!(item instanceof ItemPF2e))return;if(item.isOfType("condition","effect"))return createToggleEffectMacro(item,slot);if(uuid?.startsWith("Compendium.")){ui.notifications.error("PF2E.Macro.NoCompendiumItem",{localize:!0});return}else return HotbarPF2e.#createItemMacro(item,slot)}case"RollOption":{const item=fromUuidSync(data.uuid??"");if(!(item instanceof ItemPF2e&&item.isEmbedded))throw ErrorPF2e("Unexpected error during macro creation");return this.#hasRollOptionData(data)?HotbarPF2e.#createRollOptionToggleMacro({...data,item},slot):void 0}case"Skill":{if(!(data.actorId&&setHasElement(SKILL_ABBREVIATIONS,data.skill)))return;const skillName=data.skillName??game.i18n.localize(CONFIG.PF2E.skills[data.skill]);return createSkillMacro(data.skill,skillName,data.actorId,slot)}case"Action":return typeof data.index!="number"&&!data.elementTrait?void 0:createActionMacro({actorUUID:data.actorUUID,actionIndex:data.index,slot,elementTrait:data.elementTrait})}}#hasRollOptionData(data){const{label,domain,option}=data;return typeof label=="string"&&label.length>0&&typeof domain=="string"&&domain.length>0&&typeof option=="string"&&option.length>0}static async#createItemMacro(item,slot){const command=`game.pf2e.rollItemMacro("${item.id}");`,macro=game.macros.find(m=>m.name===item.name&&m.command===command)??await MacroPF2e.create({command,name:item.name,type:"script",img:item.img,flags:{pf2e:{itemMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(macro??null,slot)}static async#createRollOptionToggleMacro(data,slot){const name2=game.i18n.format("PF2E.ToggleWithName",{property:data.label}),escapedName=new Handlebars.SafeString(data.label),{item,domain,option}=data,command=`const item = fromUuidSync("${item.uuid}");
|
|
if (!(item instanceof Item && item.isEmbedded && item.isOwner)) {
|
|
ui.notifications.error("PF2E.MacroActionNoActorError", { localize: true });
|
|
}
|
|
const result = await item.actor.toggleRollOption("${domain}", "${option}", "${item.id}");
|
|
const state = game.i18n.localize(result ? "PF2E.Macro.OptionToggle.On" : "PF2E.Macro.OptionToggle.Off");
|
|
const message = game.i18n.format("PF2E.Macro.OptionToggle.Notification", { toggle: "${escapedName}", state });
|
|
if (typeof result === "boolean") {
|
|
ui.notifications.info(message);
|
|
}`,toggleMacro=game.macros.find(m=>m.name===name2&&m.command===command)??await MacroPF2e.create({type:"script",name:name2,img:item.img,command},{renderSheet:!1})??null;await game.user.assignHotbarMacro(toggleMacro,slot)}}class ActorDirectoryPF2e extends ActorDirectory{static{__name(this,"ActorDirectoryPF2e")}static{__name2(this,"ActorDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/actor-document-partial.hbs";#extraFolders={};#renderedOnce=!1;#draggingParty=!1;static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.details.level.value","system.attributes.adjustment","system.details.members","system.campaign.type"),options}async getData(){const activeParty=game.actors.party;this.#renderedOnce||(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(this.#extraFolders[activeParty.id]=!0),this.#renderedOnce=!0);const parties=sortBy(this.documents.filter(a=>a.isOfType("party")&&a!==activeParty),p=>p.sort);return{...await super.getData(),activeParty,parties,placePartiesInSubfolder:parties.length>1,extraFolders:this.#extraFolders}}saveActivePartyFolderState(){game.settings.set("pf2e","activePartyFolderState",this.#extraFolders[game.actors.party?.id??""]??!0)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.actor"))game.actors.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.actor-level")?.remove();for(const folderLike of htmlQueryAll(html,".folder-like")){const header=htmlQuery(folderLike,":scope > header");if(!header)continue;for(const eventType of["dragenter","dragleave","dragend"])folderLike.addEventListener(eventType,event2=>{this.#onDragHighlightFolderLike(folderLike,event2)});header.addEventListener("click",event2=>{const folderEl=htmlClosest(event2.target,".folder-like"),entryId=htmlClosest(event2.target,"[data-entry-id]")?.dataset.entryId??"";folderEl&&entryId&&(event2.stopPropagation(),this.#extraFolders[entryId]=folderEl.classList.contains("collapsed"),folderEl.classList.toggle("collapsed",!this.#extraFolders[entryId]),this.popOut&&this.setPosition(),this.saveActivePartyFolderState())});const openSheetLink=htmlQuery(header,"a[data-action=open-sheet]");openSheetLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(openSheetLink,"[data-document-id]")?.dataset.documentId;game.actors.get(documentId??"")?.sheet.render(!0)});const createMemberLink=htmlQuery(header,"a[data-action=create-member]");createMemberLink?.addEventListener("click",async event2=>{event2.preventDefault(),event2.stopPropagation();const documentId=htmlClosest(createMemberLink,"[data-document-id]")?.dataset.documentId,party=game.actors.get(documentId??"");if(!party?.isOfType("party"))return;const button=event2.currentTarget,actor=await ActorPF2e.createDialog({},{width:320,left:window.innerWidth-630,top:button?.offsetTop??0,types:["creature"]});actor?.isOfType("creature")&&(this.#extraFolders[party.id]=!0,await party.addMembers(actor))});const createPartyLink=htmlQuery(header,"a[data-action=create-party]");createPartyLink?.addEventListener("click",async event2=>{event2.stopPropagation(),(await ActorPF2e.create({type:"party",name:"New Party"}))?.sheet.render(!0);const entryId=htmlClosest(createPartyLink,".folder-like")?.dataset.entryId;entryId&&(this.#extraFolders[entryId]=!0,this.render())});const activatePartyLink=htmlQuery(header,"a[data-action=activate-party]");activatePartyLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(activatePartyLink,"[data-document-id]")?.dataset.documentId??"";game.actors.has(documentId)&&(game.settings.set("pf2e","activeParty",documentId),this.saveActivePartyFolderState())})}this.#appendBrowseButton(html)}_onSearchFilter(event2,query,rgx,html){super._onSearchFilter(event2,query,rgx,html);const folderLikes=htmlQueryAll(html,".folder-like");for(const folderLike of folderLikes)if(query!==""&&htmlQueryAll(folderLike,".actor").some(li=>li.style.display!=="none")){folderLike.removeAttribute("style"),folderLike.classList.remove("collapsed");const folderLikeHeader=htmlQuery(folderLike,":scope > header");folderLikeHeader&&folderLikeHeader.removeAttribute("style")}else{const entryId=folderLike.dataset.entryId??"";folderLike.classList.toggle("collapsed",!this.#extraFolders[entryId])}}_onDragStart(event2){if(event2.target.dataset.entryId==="otherParties"){event2.preventDefault();return}super._onDragStart(event2);const fromParty=htmlClosest(event2.target,".party")?.dataset.documentId;if(fromParty){const data=JSON.parse(event2.dataTransfer.getData("text/plain"));data.fromParty=fromParty,this.#draggingParty=fromUuidSync(data.uuid)instanceof PartyPF2e,event2.dataTransfer.setData("text/plain",JSON.stringify(data))}else this.#draggingParty=!1}_onDragHighlight(event2){if(event2.type==="dragenter"&&this.#draggingParty)return event2.stopPropagation();super._onDragHighlight(event2)}#onDragHighlightFolderLike(folderLike,event2){event2.stopPropagation(),!this.#draggingParty&&(event2.type==="dragleave"&&document.elementFromPoint(event2.clientX,event2.clientY)?.closest(".folder-like")===folderLike||folderLike?.classList.toggle("droptarget",event2.type==="dragenter"))}async _handleDroppedEntry(target,data){await super._handleDroppedEntry(target,data);const toPartyId=htmlClosest(target,".party")?.dataset.documentId;if(toPartyId!==data.fromParty&&data.uuid){const toParty=game.actors.get(toPartyId??""),fromParty=game.actors.get(data.fromParty??""),actor=fromUuidSync(data.uuid);fromParty instanceof PartyPF2e&&await fromParty.removeMembers(data.uuid),toParty instanceof PartyPF2e&&actor instanceof CreaturePF2e&&await toParty.addMembers(actor)}}async _renderInner(data){const $element=await super._renderInner(data);if(game.actors.some(a=>a.isOfType("party"))){const partyHTML=await renderTemplate("systems/pf2e/templates/sidebar/party-document-partial.hbs",data);$element.find(".directory-list").prepend(partyHTML);for(const header of htmlQueryAll($element.get(0),".party")){const party=game.actors.get(header.dataset.documentId??""),sidebarButtons=party?.isOfType("party")?party.campaign?.createSidebarButtons?.()??[]:[];header.querySelector("header h3")?.after(...sidebarButtons)}}return $element}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Actor"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,".party .party-header",this._getPartyContextOptions())}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"PF2E.Actor.Party.Sidebar.RemoveMember",icon:fontAwesomeIcon("bus").outerHTML,condition:$li=>$li.closest(".party").length>0&&!$li.closest(".party-header").length,callback:$li=>{const actorId=$li.data("document-id"),partyId=$li.closest(".party").data("document-id"),actor=game.actors.get(actorId??""),party=game.actors.get(partyId??"");actor&&party instanceof PartyPF2e&&party.removeMembers(actor.uuid)}}),options}_getPartyContextOptions(){const allOptions=super._getEntryContextOptions(),relevantNames=["SIDEBAR.CharArt","SIDEBAR.TokenArt","OWNERSHIP.Configure","SIDEBAR.Delete"],relevantOptions=allOptions.filter(o=>relevantNames.includes(o.name));return relevantOptions.length!==relevantNames.length&&console.error("PF2E System | Failed to extract all sidebar options from the base options"),relevantOptions}#appendBrowseButton(html){if(!game.user.isGM)return;const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.BestiaryBrowser")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.openTab("bestiary")}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}class ItemDirectoryPF2e extends ItemDirectory{static{__name(this,"ItemDirectoryPF2e")}static{__name2(this,"ItemDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/item-document-partial.hbs";static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.level.value"),options}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.item"))game.items.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.item-level")?.remove();this.#appendBrowseButton(html)}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Item"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}#appendBrowseButton(html){const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.Title")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0,{focus:!0})}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}async function handleKingdomChatMessageEvents(options){const{event:event2,message}=options,party=message.actor??game.actors.party;if(!(!party?.isOfType("party")||!(party?.campaign instanceof Kingdom))&&htmlClosest(event2.target,"[data-action=kingdom-collect]")){if(!party.isOwner)return;await party.campaign.collect();const content=createHTMLElement("div",{innerHTML:message.content});htmlQuery(content,"[data-action=kingdom-collect]")?.replaceWith(createHTMLElement("div",{classes:["confirmation"],children:[fontAwesomeIcon("fa-check"),"Resources Collected"]})),message.update({content:content.innerHTML})}}__name(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents"),__name2(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents");class ChatLogPF2e extends ChatLog{static{__name(this,"ChatLogPF2e")}static{__name2(this,"ChatLogPF2e")}activateListeners($html){super.activateListeners($html);const html=$html[0],log=htmlQuery(html,"#chat-log");log&&(log.dataset.tooltipDirection="UP"),this.activateClickListener(html),html.addEventListener("dblclick",async event2=>{const{message}=ChatLogPF2e.#messageFromEvent(event2);if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2)})}activateClickListener(html){html.addEventListener("click",async event2=>{const{message,element:messageEl}=ChatLogPF2e.#messageFromEvent(event2);if(!message)return;if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2);const button=htmlClosest(event2.target,"button[data-action]");if(button){if(message.isDamageRoll){const button2=htmlClosest(event2.target,"button");if(!button2)return;if(button2.dataset.action==="shield-block")return this.#onClickShieldBlock(button2,messageEl);const actions=["apply-damage","apply-healing","double-damage","half-damage","triple-damage"];for(const action2 of actions)if(button2.dataset.action===action2){const index=htmlClosest(button2,".damage-application")?.dataset.rollIndex;return this.#onClickDamageButton(message,action2,event2.shiftKey,index)}}else if(button.dataset.action==="revert-damage"){const appliedDamageFlag=message?.flags.pf2e.appliedDamage;appliedDamageFlag&&await this.#onClickRevertDamage(appliedDamageFlag)&&(htmlQuery(messageEl,"span.statements")?.classList.add("reverted"),button.remove(),await message.update({"flags.pf2e.appliedDamage.isReverted":!0,content:htmlQuery(messageEl,".message-content")?.innerHTML??message.content}))}message&&messageEl&&handleKingdomChatMessageEvents({event:event2,message,messageEl})}})}_onDiceRollClick(event2){const message=ChatLogPF2e.#messageFromEvent(event2.originalEvent).message;if(message&&htmlClosest(event2.target,"button[data-action=set-as-initiative]"))event2.stopPropagation(),this.#onClickSetAsInitiative(message);else return super._onDiceRollClick(event2)}async _processDiceCommand(command,matches,chatData,createOptions){const rollData=(ChatMessage.getSpeakerActor(chatData.speaker??{})||game.user.character)?.getRollData()??{},rolls=[];for(const match of matches.filter(m=>!!m)){const[formula,flavor]=match.slice(2,4);flavor&&!chatData.flavor&&(chatData.flavor=flavor);const roll=(()=>{try{const damageRoll=new DamageRoll(formula,rollData);return looksLikeDamageRoll(damageRoll)?damageRoll:new Roll(formula,rollData)}catch{return new Roll(formula,rollData)}})();rolls.push(await roll.evaluate({async:!0}))}chatData.type=CONST.CHAT_MESSAGE_TYPES.ROLL,chatData.rolls=rolls.map(r=>r.toJSON()),chatData.sound=CONFIG.sounds.dice,chatData.content=rolls.reduce((t,r)=>t+r.total,0).toString(),createOptions.rollMode=objectHasKey(CONFIG.Dice.rollModes,command)?command:"roll"}static#messageFromEvent(event2){const element=htmlClosest(event2?.target,"li[data-message-id]"),messageId=element?.dataset.messageId??"",message=game.messages.get(messageId);return element&&message?{element,message}:{element:null,message:null}}#onClickDamageButton(message,action2,shiftKey,index){const multiplier=(()=>{switch(action2){case"apply-healing":return-1;case"half-damage":return .5;case"apply-damage":return 1;case"double-damage":return 2;case"triple-damage":return 3}})();applyDamageFromMessage({message,multiplier,addend:0,promptModifier:shiftKey,rollIndex:Number(index)||0})}async#onClickRevertDamage(flag){const actorOrToken=fromUuidSync(flag.uuid),actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken instanceof TokenDocumentPF2e?actorOrToken.actor:null;return actor?(await actor.undoDamage(flag),ui.notifications.info(game.i18n.format(`PF2E.RevertDamage.${flag.isHealing?"Healing":"Damage"}Message`,{actor:actor.name})),!0):!1}#onClickShieldBlock(shieldButton,messageEl){const getTokens=__name2(()=>{const tokens=game.user.getActiveTokens();return tokens.length||ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0}),tokens},"getTokens"),getNonBrokenShields=__name2(tokens=>tokens.find(t=>!!t.actor)?.actor?.itemTypes.shield.filter(s=>s.isEquipped&&!s.isBroken&&!s.isDestroyed)??[],"getNonBrokenShields");shieldButton.classList.contains("tooltipstered")||$(shieldButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,content:$(messageEl).find("div.hover-content"),contentAsHTML:!0,contentCloning:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",functionBefore:()=>{const tokens=getTokens();if(!tokens.length)return!1;const nonBrokenShields=getNonBrokenShields(tokens),hasMultipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");return hasMultipleShields&&!shieldActivated?!0:hasMultipleShields&&shieldButton.dataset.shieldId?(shieldButton.attributes.removeNamedItem("data-shield-id"),shieldButton.classList.remove("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!1,!0):(shieldButton.classList.toggle("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!CONFIG.PF2E.chatDamageButtonShieldToggle,!1)},functionFormat:(instance,_helper,$content)=>{const tokens=getTokens(),nonBrokenShields=getNonBrokenShields(tokens),multipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");if(multipleShields&&!shieldActivated){const content=$content[0],listEl=htmlQuery(content,"ul.shield-options");if(!listEl)return $content;const shieldList=[];for(const shield of nonBrokenShields){const input=document.createElement("input");input.classList.add("data"),input.type="radio",input.name="shield-id",input.value=shield.id,input.addEventListener("click",()=>{shieldButton.dataset.shieldId=input.value,shieldButton.classList.add("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!0,instance.close()});const shieldName=document.createElement("span");shieldName.classList.add("label"),shieldName.innerHTML=shield.name;const hardness=document.createElement("span");hardness.classList.add("tag");const hardnessLabel=game.i18n.localize("PF2E.HardnessLabel");hardness.innerHTML=`${hardnessLabel}: ${shield.hardness}`;const itemLi=document.createElement("li");itemLi.classList.add("item"),itemLi.append(input,shieldName,hardness),shieldList.push(itemLi)}listEl.replaceChildren(...shieldList)}return $content}}).tooltipster("open")}#onClickSender(message,event2){if(!canvas)return;const token=message.token?.object;if(token?.isVisible&&token.isOwner&&(token.controlled?token.release():token.control({releaseOthers:!event2.shiftKey}),event2.type==="dblclick")){const scale=Math.max(1,canvas.stage.scale.x);canvas.animatePan({...token.center,scale,duration:1e3})}}async#onClickSetAsInitiative(message){const{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:token.name,initiative:value}))}_getEntryContextOptions(){const canApplyDamage=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return canvas.tokens.controlled.length>0&&message.rolls.some(r=>r instanceof DamageRoll)},"canApplyDamage"),canApplyTripleDamage=__name2($li=>canApplyDamage($li)&&game.settings.get("pf2e","critFumbleButtons"),"canApplyTripleDamage"),canApplyInitiative=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),validActor=message.token?.actor?.type==="npc"&&(message.token.combatant?.initiative??null)===null,validRollType=message.isRoll&&message.isCheckRoll;return validActor&&validRollType},"canApplyInitiative"),canReroll=__name2($li=>game.messages.get($li[0].dataset.messageId,{strict:!0}).isRerollable,"canReroll"),canHeroPointReroll=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor}=message;return message.isRerollable&&!!actor?.isOfType("character")&&actor.heroPoints.value>0},"canHeroPointReroll"),canShowRollDetails=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return game.user.isGM&&!!message.flags.pf2e.context},"canShowRollDetails"),options=super._getEntryContextOptions();return options.push({name:"PF2E.ChatRollDetails.Select",icon:fontAwesomeIcon("search").outerHTML,condition:canShowRollDetails,callback:$li=>{game.messages.get($li[0].dataset.messageId,{strict:!0}).showDetails()}},{name:"PF2E.DamageButton.FullContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message})}},{name:"PF2E.DamageButton.HalfContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:.5})}},{name:"PF2E.DamageButton.DoubleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:2})}},{name:"PF2E.DamageButton.TripleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyTripleDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:3})}},{name:"PF2E.DamageButton.HealingContext",icon:fontAwesomeIcon("heart").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:-1})}},{name:"PF2E.ClickToSetInitiativeContext",icon:fontAwesomeIcon("swords").outerHTML,condition:canApplyInitiative,callback:async $li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:actor.name,initiative:value}))}},{name:"PF2E.RerollMenu.HeroPoint",icon:fontAwesomeIcon("hospital-symbol").outerHTML,condition:canHeroPointReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{heroPoint:!0})}},{name:"PF2E.RerollMenu.KeepNew",icon:fontAwesomeIcon("dice").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message)}},{name:"PF2E.RerollMenu.KeepLower",icon:fontAwesomeIcon("dice-one").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"lower"})}},{name:"PF2E.RerollMenu.KeepHigher",icon:fontAwesomeIcon("dice-six").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"higher"})}}),options}}class CompendiumMigrationStatus extends Application{static{__name(this,"CompendiumMigrationStatus")}static{__name2(this,"CompendiumMigrationStatus")}compendium;static get defaultOptions(){const options=super.defaultOptions;return options.template="systems/pf2e/templates/system/compendium-migration-status.hbs",options.classes=["compendium-migration-status"],options.height="auto",options.title=game.i18n.localize("PF2E.CompendiumMigrationStatus.Title"),options}constructor(compendium){super(),this.compendium=compendium}get id(){return`compendium-info-${this.compendium.metadata.id}`}async getData(options){const index=await this.compendium.getIndex({fields:[foundry.utils.randomID(),"system._migration","system.schema","data.schema"]}),schemaVersion=Math.min(...index.map(d=>{const system=d.system??d.data;return Number(system?._migration?.version??system?.schema?.version)})),foundryVersion=pipe(Object.entries(MigrationRunner.FOUNDRY_SCHEMA_VERSIONS),sortBy(([_,schema])=>schema),findLast(([_,schema])=>schemaVersion>=schema))?.[0]??game.i18n.localize("PF2E.CompendiumMigrationStatus.FoundryOld");return{...await super.getData(options),compendium:this.compendium,schemaVersion:Number.isNaN(schemaVersion)?game.i18n.localize("PF2E.CompendiumMigrationStatus.Invalid"):schemaVersion,foundryVersion,module:game.modules.get(this.compendium.metadata.packageName??""),updated:schemaVersion>=MigrationRunner.LATEST_SCHEMA_VERSION,size:index.contents.length}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=migrate]")?.addEventListener("click",async()=>{await new MigrationRunner(MigrationList.constructFromVersion(null)).runCompendiumMigration(this.compendium),this.render(!0)})}}class CompendiumDirectoryPF2e extends CompendiumDirectory{static{__name(this,"CompendiumDirectoryPF2e")}static{__name2(this,"CompendiumDirectoryPF2e")}static STOP_WORDS=new Set(["of","th","the"]);static searchEngine=new MiniSearch({fields:["name"],idField:"uuid",processTerm:t=>t.length>1&&!this.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0},storeFields:["uuid","img","name","type","documentType","packLabel"]});static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop.push({dragSelector:"ol.document-matches > li.match"}),{...options,filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],template:"systems/pf2e/templates/sidebar/compendium-directory.hbs"}}get#dragPreview(){const preview=document.createElement("div");preview.id="pack-search-drag-preview";const thumbnail=document.createElement("img"),title=document.createElement("h4");return preview.append(thumbnail,title),preview}async getData(options){return{...await super.getData(options),searchContents:game.user.settings.searchPackContents}}activateListeners($html){super.activateListeners($html),$html[0].querySelector("footer > button")?.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0)})}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"COMPENDIUM.MigrationStatus",icon:fontAwesomeIcon("info").outerHTML,condition:$li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0}),actorOrItem=compendium.documentClass===CONFIG.Actor.documentClass||compendium.documentClass===CONFIG.Item.documentClass,isSystemCompendium=compendium.metadata.packageType==="system";return game.user.isGM&&actorOrItem&&!isSystemCompendium},callback:async $li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0});new CompendiumMigrationStatus(compendium).render(!0)}}),options}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,"ol.document-matches > li",[{name:"COMPENDIUM.ImportEntry",icon:fontAwesomeIcon("download").outerHTML,condition:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");return game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}).documentClass.canUserCreate(game.user)},callback:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");const packCollection=game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}),worldCollection=game.collections.get(packCollection.documentName,{strict:!0}),indexData=fromUuidSync(uuid)??{_id:""};if(!("_id"in indexData&&typeof indexData._id=="string"))throw ErrorPF2e("Unexpected missing document _id");return worldCollection.importFromCompendium(packCollection,indexData._id,{},{renderSheet:!0})}}])}_onSearchFilter(event2,query,rgx,listElem){super._onSearchFilter(event2,query,rgx,listElem);const html=this.element[0],docMatches=query.length>0?this.constructor.searchEngine.search(query):[],{activeFilters}=this,filteredMatches=this.activeFilters.length>0?docMatches.filter(m=>activeFilters.includes(m.documentType)):docMatches,matchTemplate=htmlQuery(html,".compendium-search-match");if(!matchTemplate)throw ErrorPF2e("Match template not found");const listElements=filteredMatches.map(match=>{const li=matchTemplate.content.firstElementChild?.cloneNode(!0);li.dataset.uuid=match.uuid,li.dataset.score=match.score.toString();const thumbnail=li.querySelector("img");thumbnail&&(typeof match.img=="string"?thumbnail.src=game.pf2e.system.moduleArt.map.get(match.uuid)?.img??match.img:match.documentType==="JournalEntry"&&(thumbnail.src="icons/svg/book.svg")),li.addEventListener("click",async event22=>{event22.stopPropagation();const doc=await fromUuid(match.uuid);await doc?.sheet?.render(!0,{editable:doc.sheet.isEditable})});const anchor=li.querySelector("a"),details=li.querySelector("span"),systemType=["Actor","Item"].includes(match.documentType)?game.i18n.localize(`TYPES.${match.documentType}.${match.type}`):null;return anchor&&details&&(anchor.innerText=match.name,details.innerText=systemType?`${systemType} (${match.packLabel})`:`(${match.packLabel})`),li}),matchesList=htmlQuery(html,"ol.document-matches");if(matchesList){matchesList.replaceChildren(...listElements);for(const dragDrop of this._dragDrop)dragDrop.bind(matchesList)}}_canDragStart(){return!0}_onDragStart(event2){const dragElement=event2.currentTarget,{uuid}=dragElement.dataset;if(!uuid)return super._onDragStart(event2);const indexEntry=fromUuidSync(uuid);if(!indexEntry)throw ErrorPF2e("Unexpected error retrieving index data");document.querySelector("#pack-search-drag-preview")?.remove();const dragPreview=this.#dragPreview.cloneNode(!0),[img,title]=Array.from(dragPreview.childNodes);title.innerText=indexEntry.name??"",img.src="img"in indexEntry&&indexEntry.img?indexEntry.img:"icons/svg/book.svg",document.body.appendChild(dragPreview);const documentType=(()=>indexEntry instanceof foundry.abstract.Document?indexEntry.documentName:game.packs.get(indexEntry.pack??"")?.documentName??null)();documentType&&(event2.dataTransfer.setDragImage(dragPreview,75,25),event2.dataTransfer.setData("text/plain",JSON.stringify({type:documentType,uuid})))}compileSearchIndex(){console.debug("PF2e System | compiling search index");const packs=game.packs.filter(p=>p.index.size>0&&p.testUserPermission(game.user,"OBSERVER"));this.constructor.searchEngine.removeAll();for(const pack of packs){const contents=pack.index.map(i=>({...i,documentType:pack.metadata.type,packLabel:pack.metadata.label}));this.constructor.searchEngine.addAll(contents)}console.debug("PF2e System | Finished compiling search index")}}class EncounterTrackerPF2e extends CombatTracker{static{__name(this,"EncounterTrackerPF2e")}static{__name2(this,"EncounterTrackerPF2e")}async _renderInner(data,options){const $html=await super._renderInner(data,options);if(!game.user.isGM)return $html;const metrics=this.viewed?.metrics;if(!metrics)return $html;const localize=localizer("PF2E.Encounter.Metrics"),threat=(()=>{const label=game.i18n.localize(`PF2E.Encounter.Budget.Threats.${metrics.threat}`),tooltip=localize("Budget",metrics.budget),tempContainer=createHTMLElement("div",{innerHTML:localize("Threat",{threat:label})});return TextEditorPF2e.convertXMLNode(tempContainer,"threat",{classes:["value",metrics.threat]}),{label:tempContainer.innerHTML,tooltip}})(),award=(()=>{const label=localize("Award.Label",{xp:metrics.award.xp}),numRecipients=metrics.award.recipients.length,tooltip=localize(numRecipients===1?"Award.Tooltip.Singular":numRecipients===4?"Award.Tooltip.Four":"Award.Tooltip.Plural",{xpPerFour:metrics.budget.spent,recipients:numRecipients});return{label,tooltip}})(),threatAward=parseHTML(await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/threat-award.hbs",{threat,award})),html=$html[0];return htmlQuery(html,"nav.encounters")?.after(threatAward),$(html)}activateListeners($html){const html=$html[0],tracker=htmlQuery(html,"#combat-tracker");if(!tracker)throw ErrorPF2e("No tracker found");const encounter=this.viewed;if(!encounter)return super.activateListeners($html);const tokenSetsNameVisibility=game.pf2e.settings.tokens.nameVisibility,allyColor=__name2(c=>c.actor?.hasPlayerOwner?CONFIG.Canvas.dispositionColors.PARTY:CONFIG.Canvas.dispositionColors.FRIENDLY,"allyColor"),combatantRows=htmlQueryAll(tracker,"li.combatant");for(const row of combatantRows){const combatantId=row.dataset.combatantId??"",combatant=encounter.combatants.get(combatantId,{strict:!0});if(row.dataset.initiative=String(combatant.initiative),combatant?.actor&&this.viewed?.combatant===combatant){const alliance=combatant.actor.alliance,dispositionColor=new foundry.utils.Color(alliance==="party"?allyColor(combatant):alliance==="opposition"?CONFIG.Canvas.dispositionColors.HOSTILE:CONFIG.Canvas.dispositionColors.NEUTRAL);row.style.background=dispositionColor.toRGBA(.1),row.style.borderColor=dispositionColor.toString()}const nameHeader=htmlQuery(row,".token-name h4");if(nameHeader){nameHeader.innerHTML=[createHTMLElement("span",{classes:["name"],children:[nameHeader.innerText]}).outerHTML,createHTMLElement("span",{classes:["users-targeting"]}).outerHTML].join("");for(const control of htmlQueryAll(row,"a.combatant-control")){const controlIcon=htmlQuery(control,"i");if(controlIcon&&(controlIcon.classList.remove("fas"),controlIcon.classList.add("fa-solid","fa-fw"),control.dataset.control==="pingCombatant"&&(controlIcon.classList.remove("fa-bullseye-arrow"),controlIcon.classList.add("fa-signal-stream"),game.scenes.viewed?.tokens.has(combatant.token?.id??"")))){const targetControl=createHTMLElement("a",{classes:["combatant-control"],dataset:{control:"toggleTarget",tooltip:"COMBAT.ToggleTargeting"},children:[fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0})]});control.before(targetControl)}}if(this.refreshTargetDisplay(combatant),tokenSetsNameVisibility){const nameElement=htmlQuery(nameHeader,"span.name");if(nameElement&&!game.user.isGM&&!combatant.playersCanSeeName&&(nameElement.innerText="",row.querySelector("img.token-image")?.removeAttribute("title")),game.user.isGM&&combatant.actor&&combatant.actor.alliance!=="party"){const toggleNameVisibility=document.createElement("a"),isActive=combatant.playersCanSeeName;toggleNameVisibility.classList.add(...["combatant-control",isActive?"active":[]].flat()),toggleNameVisibility.dataset.control="toggleNameVisibility",toggleNameVisibility.dataset.tooltip=game.i18n.localize(isActive?"PF2E.Encounter.HideName":"PF2E.Encounter.RevealName");const icon=fontAwesomeIcon("signature",{fixedWidth:!0});toggleNameVisibility.append(icon),row.querySelector('.combatant-controls a[data-control="toggleHidden"]')?.after(toggleNameVisibility),isActive||row.classList.add("hidden-name")}}}}if(game.user.isGM&&!game.modules.get("combat-enhancements")?.active){Sortable.create(tracker,{animation:200,dataIdAttr:"data-combatant-id",direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",onEnd:event2=>this.adjustFinalOrder(event2),onUpdate:event2=>this.#onDropCombatant(event2)});for(const row of combatantRows)row.classList.add("gm-draggable")}super.activateListeners($html)}refreshTargetDisplay(combatantOrToken){if(!this.viewed||!canvas.ready)return;const{combatant,tokenDoc}=combatantAndTokenDoc(combatantOrToken);if(!(combatant?.encounter!==this.viewed||tokenDoc?.combatant!==combatant))for(const tracker of htmlQueryAll(document,"#combat, #combat-popout")){const combatantRow=htmlQuery(tracker,`li.combatant[data-combatant-id="${combatant?.id??null}"]`);if(!combatantRow)return;const usersTargetting=game.users.filter(u=>Array.from(u.targets).some(t=>t.document===tokenDoc)),userIndicators=usersTargetting.map(user=>{const icon=fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0});return icon.style.color=user.color,icon}),targetingSection=htmlQuery(combatantRow,".users-targeting");targetingSection&&(targetingSection.innerHTML=userIndicators.map(i=>i.outerHTML).join(""),targetingSection.dataset.tooltip=game.i18n.format("COMBAT.TargetedBy",{list:localizeList(usersTargetting.map(u=>u.name),{conjunction:"and"})}));const targetControlIcon=htmlQuery(combatantRow,"a.combatant-control[data-control=toggleTarget]");usersTargetting.includes(game.user)?targetControlIcon?.classList.add("active"):targetControlIcon?.classList.remove("active")}}async _onCombatControl(event2){const control=event2.currentTarget.dataset.control;if((control==="rollNPC"||control==="rollAll")&&this.viewed){event2.stopPropagation();const args=eventToRollParams(event2,{type:"check"});await this.viewed[control]({...args,messageOptions:{rollMode:args.rollMode}})}else await super._onCombatControl(event2)}async _onCombatantControl(event2){if(event2.stopPropagation(),!this.viewed)return;const control=event2.currentTarget.dataset.control,li=event2.currentTarget.closest(".combatant"),combatant=this.viewed.combatants.get(li?.dataset.combatantId??"",{strict:!0});switch(control){case"rollInitiative":{await this.viewed.rollInitiative([combatant.id],eventToRollParams(event2,{type:"check"}));break}case"toggleTarget":return this.#onToggleTarget(combatant.token,event2.originalEvent);case"toggleNameVisibility":return combatant.toggleNameVisibility();default:return super._onCombatantControl(event2)}}_onToggleDefeatedStatus(combatant){return combatant.toggleDefeated()}async#onToggleTarget(tokenDoc,event2){if(!tokenDoc)return;const isTargeted=Array.from(game.user.targets).some(t=>t.document===tokenDoc);if(!tokenDoc.object?.visible){ui.notifications.warn("COMBAT.PingInvisibleToken",{localize:!0});return}tokenDoc.object.setTarget(!isTargeted,{releaseOthers:!event2?.shiftKey})}async#onDropCombatant(event2){this.validateDrop(event2);const encounter=this.viewed;if(!encounter)return;const droppedId=event2.item.getAttribute("data-combatant-id")??"",dropped=encounter.combatants.get(droppedId,{strict:!0});if(typeof dropped.initiative!="number"){ui.notifications.error(game.i18n.format("PF2E.Encounter.HasNoInitiativeScore",{actor:dropped.name}));return}const newOrder=this.getCombatantsFromDOM(),oldOrder=encounter.turns.filter(c=>c.initiative!==null);newOrder.every(c=>newOrder.indexOf(c)===oldOrder.indexOf(c))||(this.setInitiativeFromDrop(newOrder,dropped),await this.saveNewOrder(newOrder))}setInitiativeFromDrop(newOrder,dropped){const aboveDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)-1),belowDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)+1),hasAboveAndBelow=!!aboveDropped&&!!belowDropped,hasAboveAndNoBelow=!!aboveDropped&&!belowDropped,hasBelowAndNoAbove=!aboveDropped&&!!belowDropped,aboveIsHigherThanBelow=hasAboveAndBelow&&belowDropped.initiative<aboveDropped.initiative,belowIsHigherThanAbove=hasAboveAndBelow&&belowDropped.initiative<aboveDropped.initiative,wasDraggedUp=!!belowDropped&&this.viewed?.getCombatantWithHigherInit(dropped,belowDropped)===belowDropped,wasDraggedDown=!!aboveDropped&&!wasDraggedUp;dropped.initiative=hasBelowAndNoAbove||aboveIsHigherThanBelow&&wasDraggedUp?belowDropped.initiative+1:hasAboveAndNoBelow||belowIsHigherThanAbove&&wasDraggedDown?aboveDropped.initiative-1:hasAboveAndBelow?belowDropped.initiative:dropped.initiative;const withSameInitiative=newOrder.filter(c=>c.initiative===dropped.initiative);if(withSameInitiative.length>1)for(let priority=0;priority<withSameInitiative.length;priority++)withSameInitiative[priority].flags.pf2e.overridePriority[dropped.initiative]=priority}async saveNewOrder(newOrder){await this.viewed?.setMultipleInitiatives(newOrder.map(c=>({id:c.id,value:c.initiative,overridePriority:c.overridePriority(c.initiative)})))}adjustFinalOrder(event2){const row=event2.item,tracker=this.element[0].querySelector("#combat-tracker");if(!tracker)throw ErrorPF2e("Unexpected failure to retriever tracker DOM element");const rows=Array.from(tracker.querySelectorAll("li.combatant")),[oldIndex,newIndex]=[event2.oldIndex??0,event2.newIndex??0],firstRowWithNoRoll=rows.find(row2=>Number.isNaN(Number(row2.dataset.initiative)));Number.isNaN(Number(row.dataset.initiative))?newIndex>oldIndex?tracker.insertBefore(row,rows[oldIndex]):tracker.insertBefore(row,rows[oldIndex+1]):firstRowWithNoRoll&&rows.indexOf(firstRowWithNoRoll)<newIndex&&tracker.insertBefore(row,firstRowWithNoRoll)}validateDrop(event2){const{combat}=game;if(!combat)throw ErrorPF2e("Unexpected error retrieving combat");const{oldIndex,newIndex}=event2;if(!(typeof oldIndex=="number"&&typeof newIndex=="number"))throw ErrorPF2e("Unexpected error retrieving new index")}getCombatantsFromDOM(){const{combat}=game;if(!combat)throw ErrorPF2e("Unexpected error retrieving combat");const tracker=this.element[0].querySelector("#combat-tracker");if(!tracker)throw ErrorPF2e("Unexpected failure to retriever tracker DOM element");return Array.from(tracker.querySelectorAll("li.combatant")).map(row=>row.getAttribute("data-combatant-id")??"").map(id=>combat.combatants.get(id,{strict:!0})).filter(c=>typeof c.initiative=="number")}}const darkvision=new VisionMode({id:"darkvision",label:"VISION.ModeDarkvision",canvas:{shader:ColorAdjustmentsSamplerShader,uniforms:{enable:!0,contrast:0,saturation:-1,brightness:0}},lighting:{levels:{},background:{visibility:VisionMode.LIGHTING_VISIBILITY.REQUIRED}},vision:{darkness:{adaptive:!0},defaults:{attenuation:0,contrast:0,saturation:-1,brightness:.75,range:1/0}}});class VisionDetectionMode extends DetectionModeBasicSight{static{__name(this,"VisionDetectionMode")}static{__name2(this,"VisionDetectionMode")}constructor(){super({id:"basicSight",label:"DETECTION.BasicSight",type:DetectionMode.DETECTION_TYPES.SIGHT})}_canDetect(visionSource,target){return target instanceof PlaceableObject&&target.document.hidden||target instanceof TokenPF2e&&target.actor?.hasCondition("hidden","undetected","unnoticed")?!1:super._canDetect(visionSource,target)}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class HearingDetectionMode extends DetectionMode{static{__name(this,"HearingDetectionMode")}static{__name2(this,"HearingDetectionMode")}constructor(){super({id:"hearing",label:"PF2E.Actor.Creature.Sense.Type.Hearing",type:DetectionMode.DETECTION_TYPES.SOUND})}static getDetectionFilter(){const filter2=this._detectionFilter??=OutlineOverlayFilter.create({wave:!0,knockout:!1});return filter2.thickness=1,filter2}_canDetect(visionSource,target){return!(target instanceof TokenPF2e)||target.document.hidden||!target.actor?.emitsSound?!1:game.pf2e.settings.rbv?target.actor?.hasCondition("undetected","unnoticed")?!1:!visionSource.object.actor?.hasCondition("deafened"):!0}_testLOS(visionSource,_mode,_target,test){test.loh??=new Map;const hearingSource=visionSource.object.hearing,hasLOH=test.loh.get(hearingSource)??hearingSource.shape.contains(test.point.x,test.point.y);return test.loh.set(hearingSource,hasLOH),hasLOH}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class DetectionModeTremorPF2e extends DetectionModeTremor{static{__name(this,"DetectionModeTremorPF2e")}static{__name2(this,"DetectionModeTremorPF2e")}constructor(){super({id:"feelTremor",label:"DETECTION.FeelTremor",walls:!1,type:DetectionMode.DETECTION_TYPES.MOVE})}static getDetectionFilter(){const filter2=super.getDetectionFilter();return filter2.thickness=1,filter2}_canDetect(visionSource,target){return super._canDetect(visionSource,target)&&target instanceof TokenPF2e&&!target.document.hidden&&!target.actor?.isOfType("loot")&&!target.actor?.hasCondition("undetected","unnoticed")}}function setPerceptionModes(){CONFIG.Canvas.visionModes.darkvision=darkvision,CONFIG.Canvas.detectionModes.basicSight=new VisionDetectionMode,CONFIG.Canvas.detectionModes.hearing=new HearingDetectionMode,CONFIG.Canvas.detectionModes.feelTremor=new DetectionModeTremorPF2e}__name(setPerceptionModes,"setPerceptionModes"),__name2(setPerceptionModes,"setPerceptionModes");class JournalSheetPF2e extends JournalSheet{static{__name(this,"JournalSheetPF2e")}static{__name2(this,"JournalSheetPF2e")}static get theme(){return null}static get defaultOptions(){const options=super.defaultOptions,{theme}=this;return theme&&options.classes.push(theme),options}}class JournalTextTinyMCESheetPF2e extends JournalTextTinyMCESheet{static{__name(this,"JournalTextTinyMCESheetPF2e")}static{__name2(this,"JournalTextTinyMCESheetPF2e")}async activateEditor(name2,options={},initialContent=""){const editor=await super.activateEditor(name2,options,initialContent),theme=this.object.parent?.sheet.constructor?.theme;return editor.contentDocument.documentElement.classList.add("journal-entry-page","text"),editor.contentDocument.body.classList.add("journal-page-content"),theme&&editor.contentDocument.documentElement.classList.add(theme),editor}}var define_EN_JSON_default={COMBAT:{Begin:"Begin Encounter",CombatantNotInScene:"The participant {name} is not present in your currently viewed scene.",CombatantRemove:"Remove Participant",CombatantStatus:"Participant Status",CombatantUpdate:"Update Participant",End:"End Encounter",EndConfirmation:"End this encounter and empty the turn tracker?",EndTitle:"End Encounter?",NoneActive:"There is no active Encounter in your currently viewed Scene.",NoneRemaining:"There are no participants remaining in this Encounter that are not defeated.",PingCombatant:"Ping Token",PingInvisibleToken:"You can't see this participant's token.",ResourceHint:"Choose an attribute to track for each participant.",Settings:"Encounter Tracker Settings",SidebarTitle:"Encounter Tracker",SkipDefeatedHint:"Automatically bypass participants marked as defeated?",TargetedBy:"Targeted by {list}",ToggleTargeting:"Toggle Targeting",UnknownCombatant:"Unknown Participant"},COMPENDIUM:{MigrationStatus:"Migration Status"},CONTROLS:{AdjustSceneDarkness:"Adjust Scene Darkness",EffectPanel:"Effects Panel",WorldClock:"World Clock"},DOCUMENT:{Combat:"Encounter",Combats:"Encounters"},PF2E:{AbilityBoost:"Attribute Boost",AbilityBoostLevels:"Attribute Boost Levels",AbilityCha:"Charisma",AbilityCheck:{cha:"Charisma Check",con:"Constitution Check",dex:"Dexterity Check",int:"Intelligence Check",str:"Strength Check",wis:"Wisdom Check"},AbilityCon:"Constitution",AbilityDex:"Dexterity",AbilityFlaw:"Flaw",AbilityFree:"Free",AbilityId:{cha:"Cha",con:"Con",dex:"Dex",int:"Int",str:"Str",wis:"Wis"},AbilityInt:"Intelligence",AbilityModifierLabel:"Attribute Modifier",AbilityStr:"Strength",AbilityTitle:"Attribute",AbilityWis:"Wisdom",AccessoryPropertyRuneCalled:"Called",AccessoryPropertyRuneDragonsBreath:"Dragon's Breath",AccessoryPropertyRuneGreaterPaired:"Greater Paired",AccessoryPropertyRuneGreaterWindCatcher:"Greater Wind-Catcher",AccessoryPropertyRuneMajorPaired:"Major Paired",AccessoryPropertyRunePaired:"Paired",AccessoryPropertyRunePresentable:"Presentable",AccessoryPropertyRuneSnagging:"Snagging",AccessoryPropertyRuneSoftLanding:"Soft-Landing",AccessoryPropertyRuneSpellBastion:"Spell-Bastion",AccessoryPropertyRuneWindCatcher:"Wind-Catcher",Action:{RestForTheNight:{Label:"Rest for the Night",Message:{Awakens:"{actor} awakens well-rested.",ConditionReduced:"{condition} reduced by 1.",ConditionRemoved:"No longer {condition}.",FocusPoints:"Focus points restored.",Frequencies:"Action frequencies refreshed.",HitPoints:"{hitPoints} hit points restored.",HitPointsSingle:"{hitPoints} hit point restored.",InfusedReagents:"Infused reagents restored.",Resolve:"Resolve restored.",SpellSlots:"All spell slots restored.",StaminaPoints:"Stamina points restored.",TemporaryItems:"Temporary items removed.",WandsCharges:"Wands recharged."},Prompt:"Rest for the night?"},Strike:{MeleeLabel:"Melee Strike: {weapon}",OutOfRange:"The target is out of range.",RangedLabel:"Ranged Strike: {weapon}"}},ActionActionTypeLabel:"Action Type",ActionActionsLabel:"Actions",ActionBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:<br> source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. <br>Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",ActionDeathNoteLabel:"Death Note",ActionNumber1:"One",ActionNumber2:"Two",ActionNumber3:"Three",ActionSkillRequirementLabel:"Requirement",ActionTypeAction:"Action",ActionTypeFree:"Free Action",ActionTypePassive:"Passive",ActionTypeReaction:"Reaction",ActionTypeSingle:"Single Action",ActionWeaponLabel:"Associated Weapon",ActionsActionsHeader:"Actions",ActionsFreeActionsHeader:"Free Actions",ActionsReactionsHeader:"Reactions",Actor:{ApplyDamage:{AtFullHealth:"<actor>{actor}</actor> is already at full health.",DamagedForN:"<actor>{actor}</actor> takes {hpDamage} damage.",DamagedForNShield:"<actor>{actor}</actor>'s shield absorbs {absorbedDamage} damage, with an additional {hpDamage} making it through.",HealedForN:"<actor>{actor}</actor> is healed for {hpDamage} damage.",InstantDeath:{DeathEffect:"The death effect immediately kills them.",Destroyed:"They are destroyed.",FinePowder:"They are reduced to a fine powder; their gear remains.",MassiveDamage:"The massive damage immediately kills them."},ShieldAbsorbsAll:"<actor>{actor}</actor> is unscathed, their shield completely absorbing {absorbedDamage} damage.",ShieldDamagedForN:"Their shield is also damaged for {shieldDamage}.",ShieldDamagedForNBroken:"Their shield also takes {shieldDamage} damage, breaking it.",ShieldDamagedForNDestroyed:"Their shield also takes {shieldDamage} damage, destroying it.",ShieldNotRaised:"{actor} has not raised their shield.",TakesNoDamage:"<actor>{actor}</actor> takes no damage.",TheTarget:"The target"},Attacks:"Attacks",Character:{Attribute:{Apex:"Apex Attribute",Boosts:"Attribute Boosts",Key:"Key Attribute"},AttributeBuilder:{InputMethod:{Description:"Switching method resets your attribute modifier distribution.",Manual:"Manual Entry",Title:"Input Method"},AncestryMissingHelp:"Choose an ancestry to select boosts.",AlternateBoostsLabel:"Alternate Boosts",BackgroundBoostDescription:"Two boosts: one must be {a} or {b}.",BackgroundMissingHelp:"Choose a background to select boosts.",Boost:"Boost",Boosts:"Boosts",ClassMissingHelp:"Choose a class to select boosts.",Complete:"Complete",Flaw:"Flaw",Flaws:"Flaws",Increase:"Increase",KeyIcon:"Key",LegacyFlaws:"Legacy Flaws",Partial:"Partial",NotSelected:"Not Selected",Title:"Assign your boosts",VoluntaryFlaw:{Description:"You can take one or more additional penalties purely for roleplaying a highly flawed character.",LegacyDescription:"This is the Voluntary Flaws feature that existed until the CRB's 4th printing. It is kept in place for older characters and as a continued option for Pathfinder Society play.",Title:"Voluntary Flaws"}},Active:"Active",ActiveHeader:"Active Activities",Biography:{Anathema:{Add:"Add Anathema",Delete:"Delete Anathema"},ToggleVisibility:"Toggle visibility to other players",Edicts:{Add:"Add Edict",Delete:"Delete Edict"}},Blurb:"Level {level} {ancestry} {class}",ClassDC:{Label:"Class DC",LabelSpecific:"Class DC ({class})",Plural:"Class DCs"},Clear:"Clear",Configure:{ShowBasicUnarmed:{Hint:"A PC always has available an unspecific unarmed attack using any part of their body. The attack may be hidden from view if the player never intends to use it.",Label:"Show Basic Unarmed Attack"},Title:"Configure Character"},Crafting:{Cost:"Cost"},HandsOccupied:"Hands Occupied",Proficiency:{Attack:{Advanced:"Advanced Weapons",Martial:"Martial Weapons",Simple:"Simple Weapons",Title:"Attacks",Unarmed:"Unarmed Attacks"},Defense:{Heavy:"Heavy Armor",HeavyBarding:"Heavy Barding",Light:"Light Armor",LightBarding:"Light Barding",Medium:"Medium Armor",Title:"Defenses",Unarmored:"Unarmored Defense"},HigherUpgrade:"{ability} has upgraded this proficiency's rank to {rank}."},Rest:{Label:"Rest for the Night"}},Creature:{Alliance:{Default:"Ownership Default ({alliance})",Neutral:"Neutral",Opposition:"Opposition",Party:"Party"},AttributeModifiers:"Attribute Modifiers",Configure:{Alliance:{Hint:"A creature can be in opposition to the party, allied with it, or neutral. This impacts some mechanics during an encounter, such as flanking.",Label:"Alliance"}},CriticalSpecialization:"Critical Specialization",Language:{adlet:"Adlet",akitonian:"Akitonian",aklo:"Aklo",alghollthu:"Alghollthu",amurrun:"Amurrun",anadi:"Anadi","ancient-osiriani":"Ancient Osiriani",androffan:"Androffan",anugobu:"Anugobu",arboreal:"Arboreal",arcadian:"Arcadian",azlanti:"Azlanti",boggard:"Boggard",calda:"Calda",caligni:"Caligni",chthonian:"Chthonian",common:"Common",cyclops:"Cyclops",daemonic:"Daemonic",destrachan:"Destrachan",diabolic:"Diabolic",draconic:"Draconic",drooni:"Drooni",dwarven:"Dwarven",dziriak:"D'ziriak",ekujae:"Ekujae shape-script","elder-thing":"Elder Thing",elven:"Elven",empyrean:"Empyrean",erutaki:"Erutaki",fey:"Fey",formian:"Formian",garundi:"Garundi",girtablilu:"Girtablilu",gnomish:"Gnomish",goblin:"Goblin",goloma:"Goloma",grioth:"Grioth",grippli:"Grippli",halfling:"Halfling",hallit:"Hallit",hwan:"Hwan",iblydan:"Iblydan",ikeshti:"Ikeshti",immolis:"Immolis",iruxi:"Iruxi",jistkan:"Jistkan",jotun:"Jotun",jyoti:"Jyoti",kaava:"Kaava",kashrishi:"Kashrishi",kelish:"Kelish",kholo:"Kholo",kibwani:"Kibwani",kitsune:"Kitsune",kovintal:"Kovintal",lirgeni:"Lirgeni",mahwek:"Mahwek",migo:"Mi-Go",minaten:"Minatan",minkaian:"Minkaian",muan:"Muan",munavri:"Munavri",mwangi:"Mwangi",mzunu:"Mzunu",nagaji:"Nagaji",necril:"Necril",ocotan:"Ocotan",okaiyan:"Okaiyan",orcish:"Orcish",orvian:"Orvian",osiriani:"Osiriani",petran:"Petran",protean:"Protean",pyric:"Pyric",rasu:"Rasu",ratajin:"Ratajin",razatlani:"Razatlani",requian:"Requian",russian:"Russian",sakvroth:"Sakvroth",samsaran:"Samsaran",sasquatch:"Sasquatch",senzar:"Senzar",shadowtongue:"Shadowtongue",shae:"Shae",shisk:"Shisk",shoanti:"Shoanti",shobhad:"Shobhad",shoony:"Shoony",shory:"Shory",skald:"Skald",sphinx:"Sphinx",strix:"Strix",sussuran:"Sussuran",taldane:"Taldane",talican:"Talican",tekritanin:"Tekritanin",tengu:"Tengu",thalassic:"Thalassic",thassilonian:"Thassilonian",tien:"Tien",utopian:"Utopian",vanara:"Vanara",varisian:"Varisian",varki:"Varki",vishkanyan:"Vishkanyan",vudrani:"Vudrani",wildsong:"Wildsong",wyrwood:"Wyrwood",xanmba:"Xanmba",yithian:"Yithian",ysoki:"Ysoki"},Sense:{Acuity:{Imprecise:"Imprecise",Label:"Acuity",Precise:"Precise",Vague:"Vague"},Label:"Senses",NoRangeLimit:"No Limit",RangeLabel:"Range",Type:{Darkvision:"Darkvision",Echolocation:"Echolocation",GreaterDarkvision:"Greater Darkvision",Hearing:"Hearing",Heatsight:"Heatsight",Lifesense:"Lifesense",LowLightVision:"Low-Light Vision",Motionsense:"Motionsense",Scent:"Scent",SeeInvisibility:"See Invisibility",Spiritsense:"Spiritsense",Thoughtsense:"Thoughtsense",Tremorsense:"Tremorsense",Wavesense:"Wavesense"},WithAcuity:"{sense} ({acuity})",WithAcuityAndRange:"{sense} ({acuity} {range} Ft)"},Shield:{ACBonus:"Shield AC Bonus (When Raised)",BrokenThreshold:"Shield Broken Threshold",Hardness:{Hint:"Shield Hardness",Label:"H"},HitPoints:{Value:"Shield HP",Max:"Shield Max HP"}},SpellPreparation:{Hint:"To prepare a spell, drag one from this list to a slot on the actor sheet.",HintFlexible:"To prepare a spell, enable it here. To prepare a cantrip, drag one from this list to a slot on the actor sheet.",Search:"Search Spells",Title:"{actor}: Spell Preparation"},Spellcasting:{Cantrips:"Cantrips",DC:"Spell DC",InvalidProficiency:"Invalid",Label:"Spell Attack Modifiers & DCs",MagicItemTypesLabel:"Magic Item Types",Rituals:"Rituals",TraditionSpellcasting:"{tradition} Spellcasting",ValidItemTypes:{All:"All Magic Items",Scroll:"Scrolls Only"}}},Dead:"Dead",Familiar:{Blurb:"Familiar of {master}",Master:{ArmorClass:"Master Armor Class",Perception:"Master Perception"}},Hardness:{ShortLabel:"HRD"},Hazard:{EmitsSound:{Encounter:"During Encounters",False:"Never",Hint:"Whether this hazard emits sound and can be sensed via hearing",Title:"Emits Sound?",True:"Always"},Level:"Hazard {level}",Plural:"Hazards",Simple:"Simple",TitleEdit:"{name} (Edit Mode)"},HitPoints:{Unrecoverable:"{value} hit points are currently unrecoverable."},Inventory:{DistributeCoins:"Distribute Coins",Encumbrance:"Encumbrance",ItemQuantity:{Decrease:{Click:"[Click] Decrease by 1",ShiftClick:"[Shift-Click] Decrease by 5",ControlClick:"[Control-Click] Decrease by 10"},Increase:{Click:"[Click] Increase by 1",ShiftClick:"[Shift-Click] Increase by 5",ControlClick:"[Control-Click] Increase by 10"}},Section:{WeaponsAndShields:"Weapons & Shields"},TotalBulk:"Total Bulk: {bulk}"},IWREditor:{DoubleVs:"Double Vs.",Exceptions:"Exceptions",Title:"{actor}: {category}",Type:"Type"},NPC:{Configure:{Lootable:{DefaultLootable:"Global Default (Lootable)",DefaultNotLootable:"Global Default (Not Lootable)",Hint:"Set whether this NPC becomes lootable by players upon its demise. The global default can be configured in <a>Automation Settings</a>.",Label:"Lootable?",Lootable:"Lootable",NotLootable:"Not Lootable"},Title:"Configure NPC"},GenerateAttack:{Confirm:{Content:"An attack has already been generated for this weapon. Would you like to replace it?",Title:"Regenerate attack"},Label:"Generate Attack",Notification:"Generated NPC attack: {attack}"},Identification:{Skills:{Label:"{skills}: DC {dc} ({adjustment})",Tooltip:`"The skill used to identify a creature usually depends on that creature's trait, as shown on Table 10\u20137, but you have leeway on which skills apply." \u2013 CRB pg. 506`},Lore:{Label:"Applicable Lore: DC {dc1} ({adjustment1}) or DC {dc2} ({adjustment2})",Tooltip:'"Using the applicable Lore usually has an easy or very easy DC (before adjusting for rarity)." \u2013 CRB pg. 506'}},SimpleSheet:"Simple NPC Sheet",SkillsEditor:{LorePlaceholder:"Carpentry Lore",Title:"Skills Editor ({actor})"}},Party:{BlankSlate:"This party doesn't have any members. Drag a creature from the actor sidebar to get started.",CheckPrompt:{AdjustDifficulty:"Adjust Difficulty",ChooseLores:"Choose Lores",ChooseSaves:"Choose Saves",ChooseSkills:"Choose Skills/Perception",LevelDC:"Level-Based DC",Post:"Generate Prompt",PromptTitle:"Prompt Title",SecretCheck:"Secret Check",SetDC:"Set DC",SimpleDC:"Simple DC",SkillsPerception:"Skills/Perception",Title:"Generate Check Prompt",TitleShort:"Check Prompt"},Coin:"Coin",ClearActivities:{Label:"Clear",Complete:"Party exploration activities have been cleared"},ClownCar:{Deposit:"Deposit PC Tokens",Retrieve:"Retrieve PC Tokens"},DefaultName:"The Party",InvalidCampaign:{Hint:"The campaign data is invalid",Title:"Invalid Campaign ({party})",Message:{mismatch:"This party has campaign data of type {current}, but the configured type is {campaignType}. Do you want to delete existing campaign data?",error:"This party's campaign data ({current}) is corrupt and failed data preparation. Do you want to delete existing campaign data?"}},Languages:"Party Languages",MembersLabel:"Members: ",NoMembers:"No Members",NoSpecialSenses:"No Special Senses",RemoveMember:{Title:"Remove Member",Content:"Remove member from party?"},Rest:"Rest",Sidebar:{ActivateParty:"Activate Party",CreateMember:"Create New Member",CreateParty:"Create New Party",RemoveMember:"Remove Member",OpenSheet:"Open Sheet",OtherParties:"Other Parties"},Skills:"Party Skills",SlotAvailable:"Slot Available",Tabs:{Overview:"Overview",Exploration:"Exploration",Orphaned:"Orphaned Items",Stash:"Stash"},Total:"Party Total",TravelHeader:"Party Travel and Hexploration",Visibility:{Restricted:"Restricted",Unrestricted:"Unrestricted"},Wealth:"Wealth"},Plural:"Actors"},ActorSizeGargantuan:"Gargantuan",ActorSizeHuge:"Huge",ActorSizeLarge:"Large",ActorSizeMedium:"Medium",ActorSizeSmall:"Small",ActorSizeTiny:"Tiny",AddCoinsCombineStacksLabel:"Combine Stacks",AddCoinsTitle:"Add Coins",AddCombatProficiency:{Message:"Select a weapon group or base weapon",Title:"Add Combat Proficiency"},AddModifierTitle:"Add Modifier",AddShortLabel:"Add",AddSpellTitle:"Add Spell",AddSpellcastingEntryTitle:"Add Spellcasting Entry",AdditionalLanguagePlusInt:"(plus Intelligence)",AdditionalSkills:"Additional Skills",Age:"Age",AllSavesLabel:"All Saves",AncestryFeatLevels:"Ancestry Feat Levels",AncestryFeatures:"Ancestry Features",AncestryHP:"Ancestry HP",AreaLabel:"Area",AreaSize10:"10 Foot",AreaSize100:"100 Foot",AreaSize1000:"1000 Foot",AreaSize120:"120 Foot",AreaSize15:"15 Foot",AreaSize1Mile:"1 Mile",AreaSize20:"20 Foot",AreaSize25:"25 Foot",AreaSize30:"30 Foot",AreaSize360:"360 Foot",AreaSize40:"40 Foot",AreaSize45:"45 Foot",AreaSize5:"5 Foot",AreaSize50:"50 Foot",AreaSize500:"500 Foot",AreaSize60:"60 Foot",AreaSize65:"65 Foot",AreaSize75:"75 Foot",AreaSize80:"80 Foot",AreaSize90:"90 Foot",AreaSizeQuarterMile:"Quarter Mile",AreaTypeBurst:"Burst",AreaTypeCone:"Cone",AreaTypeCube:"Cube",AreaTypeEmanation:"Emanation",AreaTypeLine:"Line",AreaTypeSquare:"Square",ArmorArmorLabel:"AC Bonus",ArmorCheckLabel:"Check Penalty",ArmorCheckPenalty:"Armor Check Penalty",ArmorClassBase:"Base Armor Class 10",ArmorClassLabel:"Armor Class",ArmorClassShortLabel:"AC",ArmorDexLabel:"Dex Modifier Cap",ArmorGreaterResilientRune:"Greater Resilient",ArmorGroupChain:"Chain",ArmorGroupCloth:"Cloth",ArmorGroupComposite:"Composite",ArmorGroupLabel:"Group",ArmorGroupLeather:"Leather",ArmorGroupPlate:"Plate",ArmorGroupSkeletal:"Skeletal",ArmorGroupWood:"Wood",ArmorMajorResilientRune:"Major Resilient",ArmorPotencyRune1:"Armor Potency (+1)",ArmorPotencyRune2:"Armor Potency (+2)",ArmorPotencyRune3:"Armor Potency (+3)",ArmorPotencyRune4:"Armor Potency (+4)",ArmorPropertyRuneAcidResistant:"Acid-Resistant",ArmorPropertyRuneAdvancing:"Advancing",ArmorPropertyRuneAimAiding:"Aim-Aiding",ArmorPropertyRuneAntimagic:"Antimagic",ArmorPropertyRuneAssisting:"Assisting",ArmorPropertyRuneBitter:"Bitter",ArmorPropertyRuneColdResistant:"Cold-Resistant",ArmorPropertyRuneDeathless:"Deathless",ArmorPropertyRuneElectricityResistant:"Electricity-Resistant",ArmorPropertyRuneEnergyAdaptive:"Energy Adaptive",ArmorPropertyRuneEthereal:"Ethereal",ArmorPropertyRuneFireResistant:"Fire-Resistant",ArmorPropertyRuneFortification:"Fortification",ArmorPropertyRuneGlamered:"Glamered",ArmorPropertyRuneGliding:"Gliding",ArmorPropertyRuneGreaterAcidResistant:"Greater Acid-Resistant",ArmorPropertyRuneGreaterAdvancing:"Greater Advancing",ArmorPropertyRuneGreaterColdResistant:"Greater Cold-Resistant",ArmorPropertyRuneGreaterDread:"Greater Dread",ArmorPropertyRuneGreaterElectricityResistant:"Greater Electricity-Resistant",ArmorPropertyRuneGreaterFireResistant:"Greater Fire-Resistant",ArmorPropertyRuneGreaterFortification:"Greater Fortification",ArmorPropertyRuneGreaterInvisibility:"Greater Invisibility",ArmorPropertyRuneGreaterQuenching:"Greater Quenching",ArmorPropertyRuneGreaterReady:"Greater Ready",ArmorPropertyRuneGreaterShadow:"Greater Shadow",ArmorPropertyRuneGreaterSlick:"Greater Slick",ArmorPropertyRuneGreaterStanching:"Greater Stanching",ArmorPropertyRuneGreaterSwallowSpike:"Greater Swallow-Spike",ArmorPropertyRuneGreaterWinged:"Greater Winged",ArmorPropertyRuneImmovable:"Immovable",ArmorPropertyRuneImplacable:"Implacable",ArmorPropertyRuneInvisibility:"Invisibility",ArmorPropertyRuneLesserDread:"Lesser Dread",ArmorPropertyRuneMagnetizing:"Magnetizing",ArmorPropertyRuneMajorQuenching:"Major Quenching",ArmorPropertyRuneMajorShadow:"Major Shadow",ArmorPropertyRuneMajorSlick:"Major Slick",ArmorPropertyRuneMajorStanching:"Major Stanching",ArmorPropertyRuneMajorSwallowSpike:"Major Swallow-Spike",ArmorPropertyRuneMalleable:"Malleable",ArmorPropertyRuneMisleading:"Misleading",ArmorPropertyRuneModerateDread:"Moderate Dread",ArmorPropertyRunePortable:"Portable",ArmorPropertyRuneQuenching:"Quenching",ArmorPropertyRuneRaiment:"Raiment",ArmorPropertyRuneReady:"Ready",ArmorPropertyRuneRockBraced:"Rock-Braced",ArmorPropertyRuneShadow:"Shadow",ArmorPropertyRuneSinisterKnight:"Sinister Knight",ArmorPropertyRuneSlick:"Slick",ArmorPropertyRuneSoaring:"Soaring",ArmorPropertyRuneStanching:"Stanching",ArmorPropertyRuneSwallowSpike:"Swallow-Spike",ArmorPropertyRuneTrueQuenching:"True Quenching",ArmorPropertyRuneTrueStanching:"True Stanching",ArmorPropertyRuneWinged:"Winged",ArmorResilientRune:"Resilient",ArmorSpeedLabel:"Speed Penalty",ArmorStrengthLabel:"Strength Requirement",ArmorTypeHeavy:"Heavy Armor",ArmorTypeLight:"Light Armor",ArmorTypeMedium:"Medium Armor",ArmorTypeUnarmored:"Unarmored",AttackEffectConstrict:"Constrict",AttackEffectGrab:"Grab",AttackEffectGreaterConstrict:"Improved Constrict",AttackEffectImprovedGrab:"Improved Grab",AttackEffectImprovedKnockdown:"Improved Knockdown",AttackEffectImprovedPush:"Improved Push",AttackEffectKnockdown:"Knockdown",AttackEffectPush:"Push",AttackEffectTrip:"Trip",AttackLabel:"Attack",AttitudeLabel:"Attitude",Attitudes:{Friendly:"Friendly",Helpful:"Helpful",Hostile:"Hostile",Indifferent:"Indifferent",Unfriendly:"Unfriendly"},AutomaticBonusProgression:{attackPotency:"Attack Potency",defensePotency:"Defense Potency",devastatingAttacks:"Devastating Attacks",perceptionPotency:"Perception Potency",savePotency:"Save Potency"},Background:"Background",BackgroundSkillFeats:"Skill Feats",BaseModifier:"Base Modifier",BaseWeapons:"Base Weapons",BestiaryBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:<br> source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. <br>Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",Biography:"Biography",BiographyAllies:"Allies",BiographyAppearance:"Appearance",BiographyAnathema:"Anathema",BiographyAttitude:"Attitude",BiographyBackStory:"Backstory",BiographyBeliefs:"Beliefs",BiographyBirthPlace:"Birth Place",BiographyCampaignNotes:"Notes",BiographyCampaignNotesHeader:"Campaign",BiographyCatchphrases:"Catchphrases",BiographyDislikes:"Dislikes",BiographyEdicts:"Edicts",BiographyEnemies:"Enemies",BiographyLikes:"Likes",BiographyOrganizations:"Organizations",BiographyPersonalityHeader:"Personality",Bonus:"Bonus",BonusLabel:{ability:"Attribute Bonus",circumstance:"Circumstance Bonus",item:"Item Bonus",proficiency:"Proficiency Bonus",status:"Status Bonus",untyped:"Untyped Bonus"},BonusSPLabel:"Bonus SP",BonusSPperLevel:"Bonus SP per Level",BrowseLabel:"Browse",BrowserClearFilter:"Clear Filter",BrowserClearFilters:"Clear All Filters",BrowserFilterAlignments:"Alignments",BrowserFilterAncestries:"Ancestries",BrowserFilterArmorFilters:"Armor Filters",BrowserFilterCastingTime:"Casting time",BrowserFilterCategory:"Categories",BrowserFilterClass:"Classes",BrowserFilterComplexity:"Hazard Complexities",BrowserFilterConjunction:{AndLabel:"All of above",OrLabel:"Any of above"},BrowserFilterInventoryTypes:"Inventory Types",BrowserFilterLevels:"Levels",BrowserFilterProficiencyRequirements:"Proficiency Requirements",BrowserFilterRarities:"Rarities",BrowserFilterSizes:"Sizes",BrowserFilterSkills:"Skills",BrowserFilterSource:"Source",BrowserFilterSpellCategories:"Categories",BrowserFilterTraditions:"Traditions",BrowserFilterTraits:"Traits",BrowserFilterWeaponFilters:"Weapon Filters",BrowserSearchPlaceholder:"Search Text",BrowserSearchTitle:"Right click for guide",BrowserSettingsSaved:"Settings have been saved",BrowserSortyByLabel:"Sort by",BrowserWarnPackNotLoaded:'Compendium "{pack}" could not be loaded.',BulkMaxLabel:"Max Bulk",CapacityBarLabel:"Capacity",CarryType:{dropped:"Dropped",held1:"Held 1H",held2:"Held 2H",stowed:"Stowed",worn:"Worn","worn-in-slot":"Worn (In Slot)"},CastLabel:"Cast",CastingItemCreateDialog:{"10thLevelWand":"10th level wands don't exist",cantripDeck5:"Cantrip Deck (5-pack)",itemTypeLabel:"Item type: ",label:"Create a spellcasting item from the dropped spell",scroll:"Scroll",spellLevelLabel:"Heightened Rank: ",submit:"Create item",title:"Create a spellcasting item",wand:"Wand"},Category:"Category",CharacterDetails:"Character Details",CharacterLevelLabel:"Level",CharacterNamePlaceholder:"Character Name",CharacterTraits:"Character Traits",CharacterTraitsHeader:"Traits & Other Details",ChatRollDetails:{FlatCheckNoModifiers:"Flat checks never include any modifiers, bonuses, or penalties.",ModifiersAndDice:"Modifiers and Dice",RollOptions:"Roll Options",Select:"Inspect Roll",Title:"Roll Inspector"},Check:{DC:{Label:{AdjustedTarget:"<target>Target: {target}</target> <dc>({dcType} <preadjusted>{preadjusted}</preadjusted> <adjusted>{adjusted}</adjusted>)</dc>",NoChangeTarget:"<target>Target: {target}</target> <dc>({dcType} <adjusted>{adjusted}</adjusted>)</dc>",NoTarget:"<dc>{dcType} {dc}</dc>",WithTarget:"<target>Target: {target}</target> <dc>({dcType} {dc})</dc>"},Specific:{armor:"AC",athletics:"Athletics DC",deception:"Deception DC",fortitude:"Fortitude DC",perception:"Perception DC",reflex:"Reflex DC",stealth:"Stealth DC",will:"Will DC"},Unspecific:"DC"},Label:"Check",Result:{AdjustedLabel:"Result: <unadjusted>{unadjusted}</unadjusted> <adjusted>{adjusted}</adjusted> <offset>by {offset}</offset>",Degree:{Attack:{criticalFailure:"Critical Miss",criticalSuccess:"Critical Hit",failure:"Miss",success:"Hit"},Check:{criticalFailure:"Critical Failure",criticalSuccess:"Critical Success",failure:"Failure",success:"Success"}},Label:"Result: <unadjusted>{unadjusted}</unadjusted> <offset>by {offset}</offset>"},SetAsInitiative:"Set as {actor}'s initiative",Specific:{Counteract:"Counteract Check",Perception:{Label:"Perception Check",Secret:"Perception Check (Secret)"},Recovery:"Recovery Check"}},CircumstanceBonusShortLabel:"Circumstance",CircumstanceBonusTitle:"Circumstance Bonus",ClassFeatLevels:"Class Feat Levels",ClassFeatures:"Class Features",ClassHP:"Class HP",ClipboardNotification:'Copied "{clipText}" to the clipboard.',CompendiumBrowser:{AddedItem:"Added {item} to the selected actor(s).",AddedItemToCharacter:"Added {item} to {character}.",BestiaryBrowser:"Bestiary Browser",BoughtItemWithAllCharacters:"Purchased {item} with all selected actor(s).",BoughtItemWithCharacter:"Purchased {item} with {character}.",BuyLabel:"Buy Item",FailedToBuyItemWithCharacter:"Could not purchase {item} with {character}.",FailedToBuyItemWithSomeCharacters:"Could not purchase {item} with some of the selected actor(s).",Hint:"Use the tabs above to select a compendium",RollTable:{AddDialogText:"Add {count} result(s) to Roll Table?",AddLabel:"Add to Roll Table",CreateDialogText:"Create Roll Table with {count} result(s)?",CreateLabel:"Create Roll Table",SelectTableTitle:"Select Roll Table",WeightLabel:"Weight"},Settings:{PacksLabel:"Packs",SourcesLabel:"Sources"},TabAction:"Actions",TabBestiary:"Bestiaries",TabCampaign:"Campaign",TabFeat:"Feats/Features",TakeLabel:"Take Item",Title:"Compendium Browser"},CompendiumMigrationStatus:{Document:"Document",Foundry:"Foundry",FoundryOld:"0.7 or older",Invalid:"Invalid",LockedTooltip:"Unable to migrate - compendium is locked",MigrateCompendium:"Migrate Compendium",Schema:"Schema",Size:"Size",Title:"Migration Status",UpToDate:"Up to Date"},Condition:{ActiveLabel:"Active",DurationNumberLabel:"Rounds",DurationTextLabel:"Duration",HasValueLabel:"Has Value",ImmutableLabel:"Immutable",ImmutableTitle:"Value cannot be reduced.",PerpetualLabel:"Perpetual Condition",RemovableLabel:"Removable",ValueLabel:"Value"},ConditionTypeBlinded:"Blinded",ConditionTypeBroken:"Broken",ConditionTypeClumsy:"Clumsy",ConditionTypeConcealed:"Concealed",ConditionTypeConfused:"Confused",ConditionTypeControlled:"Controlled",ConditionTypeDazzled:"Dazzled",ConditionTypeDeafened:"Deafened",ConditionTypeDoomed:"Doomed",ConditionTypeDrained:"Drained",ConditionTypeDying:"Dying",ConditionTypeEncumbered:"Encumbered",ConditionTypeEnfeebled:"Enfeebled",ConditionTypeFascinated:"Fascinated",ConditionTypeFatigued:"Fatigued",ConditionTypeFlatFooted:"Off-Guard",ConditionTypeFleeing:"Fleeing",ConditionTypeFriendly:"Friendly",ConditionTypeFrightened:"Frightened",ConditionTypeGrabbed:"Grabbed",ConditionTypeHelpful:"Helpful",ConditionTypeHidden:"Hidden",ConditionTypeHostile:"Hostile",ConditionTypeImmobilized:"Immobilized",ConditionTypeIndifferent:"Indifferent",ConditionTypeInvisible:"Invisible",ConditionTypeMalevolence:"Malevolence",ConditionTypeObserved:"Observed",ConditionTypeOffGuard:"Off-Guard",ConditionTypeParalyzed:"Paralyzed",ConditionTypePersistent:"Persistent Damage",ConditionTypePersistentShort:"Persistent",ConditionTypePetrified:"Petrified",ConditionTypeProne:"Prone",ConditionTypeQuickened:"Quickened",ConditionTypeRestrained:"Restrained",ConditionTypeSickened:"Sickened",ConditionTypeSlowed:"Slowed",ConditionTypeStunned:"Stunned",ConditionTypeStupefied:"Stupefied",ConditionTypeUnconscious:"Unconscious",ConditionTypeUndetected:"Undetected",ConditionTypeUnfriendly:"Unfriendly",ConditionTypeUnnoticed:"Unnoticed",ConditionTypeWounded:"Wounded",ConditionsLabel:"Conditions",ConsumableMessage:{UseExhausted:"Exhausted {name}",UseMulti:"Uses {name}, {current} remain",UseSingle:"Uses {name}"},CoreSkillsHeader:"Core Skills",Counteractable:"Counteractable",CraftDCTitle:"DC",CraftItemTitle:"Craft",CraftingTab:{Alchemical:{AdvancedAlchemy:"Advanced Alchemy",AdvancedAlchemyLevel:"Advanced Alchemy Level",InfusedReagents:"Infused Reagents",ReagentCost:"Reagent Cost",ToggleSignatureItem:"Toggle Signature Item",TotalCost:"Total Cost"},Alerts:{CharacterLevel:"Item level exceeds character level.",FormulaExpended:"Prepared formula has already been crafted.",ItemMissingTraits:"Item is not compatible with crafting entry item requirements.",MaxItemLevel:"Item level exceeds maximum item level for entry.",MaxSlots:"Crafting entry's allowed slots are full.",MissingReagents:"Insufficient infused reagents to complete crafting."},CraftQuantityTitle:"Quantity",ExpendFormula:"Expend Formula",NoEligibleEntry:"No eligible crafting entry was found.",QuickAddTitle:"Add this formula to one or more crafting entries",RemoveFormulaDialogQuestion:"Are you sure you want to remove the formula for {name}?",RemoveFormulaDialogTitle:"Remove Formula",ToggleFreeCrafting:"Toggle Free Crafting",ToggleQuickAlchemy:"Quick Alchemy",UndeletableTooltip:"This crafting formula is part of another item and cannot be individually deleted.",UnprepareFormulaDialogQuestion:"Are you sure you want to unprepare the formula for {name}?",UnprepareFormulaDialogTitle:"Unprepare Formula"},CreateActionTitle:"Create Action",CreateAttackTitle:"Create Attack",CreateFeatTitle:"Create Feat",CreateFormulaTitle:"Create Formula",CreateItemTitle:"Create Item",CreateLabelUniversal:"Create",CreateSkillTitle:"Create Skill",CreateSpellTitle:"Create Spell",CritFailure:"<strong>Critical Failure</strong>",CritSuccess:"<strong>Critical Success</strong>",CriticalDamageLabel:"Critical",CriticalFumbleCardButtonTitle:"Draw a Critical Fumble Card",CriticalHitCardButtonTitle:"Draw a Critical Hit Card",CurrencyAbbreviations:{cp:"cp",gp:"gp",pp:"pp",sp:"sp"},CurrencyCP:"Copper",CurrencyGP:"Gold",CurrencyPP:"Platinum",CurrencySP:"Silver",CurrentHitPointsShortLabel:"Current HP",CurrentStaminaPointsShortLabel:"Current SP",DCAdjustmentEasy:"easy",DCAdjustmentHard:"hard",DCAdjustmentIncrediblyEasy:"incredibly easy",DCAdjustmentIncrediblyHard:"incredibly hard",DCAdjustmentNormal:"baseline",DCAdjustmentVeryEasy:"very easy",DCAdjustmentVeryHard:"very hard",DCBase:"Base DC 10",DCWithValue:"DC {dc} {text}",DCWithValueAndVisibility:'<span data-visibility="{role}">DC {dc}</span> {text}',Damage:{Base:"Base",IWR:{ActorIsImmune:"{actor} is immune to {effect}.",ActorIsUnaffected:"{actor} is unaffected by {effect}.",ApplicationBreakdown:{ignored:"Resistance to {type} ignored!",immunity:"Immune to {type}: {adjustment}",resistance:"Resistant to {type}: {adjustment}",unaffected:"Unaffected by {type}: {adjustment}",weakness:"Weak to {type}: {adjustment}",reduction:"Reduced by {type}: {adjustment}"},CompositeLabel:{Exceptions0DoubleVs0:"{type} {value}",Exceptions0DoubleVs1:"{type} {value} (double resistance vs. {doubleVs1})",Exceptions0DoubleVs2:"{type} {value} (double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions0DoubleVs3:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions0DoubleVs4:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions1DoubleVs0:"{type} {value} (except {exception1})",Exceptions1DoubleVs1:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1})",Exceptions1DoubleVs2:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions1DoubleVs3:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions1DoubleVs4:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions2DoubleVs0:"{type} {value} (except {exception1} or {exception2})",Exceptions2DoubleVs1:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1})",Exceptions2DoubleVs2:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions2DoubleVs3:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions2DoubleVs4:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions3DoubleVs0:"{type} {value} (except {exception1}, {exception2}, or {exception3})",Exceptions3DoubleVs1:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1})",Exceptions3DoubleVs2:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions3DoubleVs3:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions3DoubleVs4:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions4DoubleVs0:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4})",Exceptions4DoubleVs1:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1})",Exceptions4DoubleVs2:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions4DoubleVs3:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions4DoubleVs4:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})"},Type:{abysium:"abysium",adamantine:"adamantine","all-damage":"all damage","area-damage":"area damage","arrow-vulnerability":"arrow vulnerability",auditory:"auditory","axe-vulnerability":"axe vulnerability",blinded:"blinded",broken:"broken",clumsy:"clumsy","cold-iron":"cold iron",confused:"confused",controlled:"controlled","critical-hits":"critical hits",curse:"curse","damage-from-spells":"damage from spells",dawnsilver:"dawnsilver",dazzled:"dazzled",deafened:"deafened","death-effects":"death effects",disease:"disease",djezet:"djezet",doomed:"doomed",drained:"drained",duskwood:"duskwood",emotion:"emotion",energy:"energy",enfeebled:"enfeebled",fascinated:"fascinated",fatigued:"fatigued","fear-effects":"fear effects",fleeing:"fleeing",frightened:"frightened","ghost-touch":"ghost touch",glass:"glass",grabbed:"grabbed",healing:"healing",hidden:"hidden",holy:"holy",illusion:"illusion",immobilized:"immobilized",inhaled:"inhaled",inubrix:"inubrix",light:"light",magic:"magic",magical:"magical",metal:"metal","misfortune-effects":"misfortune effects","non-magical":"non-magical",nonlethal:"nonlethal","nonlethal-attacks":"nonlethal attacks",noqual:"noqual","object-immunities":"object immunities","off-guard":"off-guard",olfactory:"olfactory",orichalcum:"orichalcum",paralyzed:"paralyzed","persistent-damage":"persistent damage",petrified:"petrified",physical:"physical",plant:"plant",polymorph:"polymorph",possession:"possession",prone:"prone","protean-anatomy":"protean anatomy",radiation:"radiation",restrained:"restrained",salt:"salt","salt-water":"salt water",scrying:"scrying",siccatite:"siccatite",sickened:"sickened",silver:"silver",sleep:"sleep",slowed:"slowed","spell-deflection":"spell deflection",spells:"spells","splash-damage":"splash damage",stunned:"stunned",stupefied:"stupefied","swarm-attacks":"swarm attacks","swarm-mind":"swarm mind",trip:"trip","unarmed-attacks":"unarmed attacks",unconscious:"unconscious",unholy:"unholy","vampire-weaknesses":"vampire weaknesses",visual:"visual",vorpal:"vorpal","vorpal-adamantine":"vorpal adamantine","vorpal-fear":"vorpal fear","vulnerable-to-sunlight":"vulnerable to sunlight",water:"water",weapons:"weapons","weapons-shedding-bright-light":"weapons shedding bright light",wood:"wood",wounded:"wounded"}},Hardness:{Full:"hardness",Half:"half hardness"},IncreasedFrom:"Increased from {original} to minimum of 1",Kind:{Both:{Label:"Both",Roll:{Noun:"Damage/Healing Roll",Verb:"Roll Damage/Healing"}},Damage:{Roll:{Noun:"Damage Roll",Verb:"Roll Damage"}},Healing:{Apply:{Label:"Apply Healing"},Roll:{Noun:"Healing Roll",Verb:"Roll Healing"}}},NoDamageFormulaLabel:"No damage",PersistentTooltip:"Persistent {damageType}",Precision:"Precision",RollFlavor:{acid:"acid",air:"air",bleed:"bleed",bludgeoning:"bludgeoning",cold:"cold",earth:"earth",electricity:"electricity",fire:"fire",force:"force",mental:"mental",metal:"metal",persistent:"persistent {damageType}",piercing:"piercing",poison:"poison",precision:"precision",slashing:"slashing",sonic:"sonic",spirit:"spirit",splash:"splash",vitality:"vitality",void:"void",untyped:"untyped"},Scatter:"Scatter Damage"},DamageButton:{Adjust:"[Shift-Click] Adjust value before applying.",Double:"[Click] Apply double damage to selected tokens.",DoubleContext:"Double Damage",DoubleShort:"Double",Full:"[Click] Apply full damage to selected tokens.",FullContext:"Apply Damage",FullShort:"Damage",Half:"[Click] Apply half damage to selected tokens.",HalfContext:"Half Damage",HalfShort:"Half",Healing:"[Click] Apply full healing to selected tokens.",HealingContext:"Apply Healing",HealingShort:"Heal",ShieldBlock:"[Click] Toggle the shield block status of the selected tokens before applying damage.",ShieldBlockContext:"Shield Block",ShieldBlockShort:"Block",Triple:"[Click] Apply triple damage to selected tokens.",TripleContext:"Apply Triple Damage",TripleShort:"Triple"},DamageCategoriesLabel:"Damage Categories",DamageDieD10:"d10",DamageDieD12:"d12",DamageDieD4:"d4",DamageDieD6:"d6",DamageDieD8:"d8",DamageLabel:"Damage",DamageRoll:"Damage Roll",DecrementEffectTitle:"Decrease Effect Level",DefensesLabel:"Defenses",Deity:"Deity",DeleteQuestion:"Are you sure you want to delete {name}?",DeleteConditionTitle:"Delete Condition",DeleteItemTitle:"Delete Item",DeleteShortLabel:"Delete",DeleteSpellcastEntryQuestion:"Are you sure you want to delete this spellcasting entry?",DeleteSpellcastEntryTitle:"Delete Spellcasting",DeleteSpellcastEntryWarning:"WARNING: All spells in this spellcasting entry will also be deleted.",DenominationLabel:"Denomination",DetailsHeading:"Details",DragDropFeats:"Drag & Drop feats to add",Duration:{P1M:"month",P1W:"week",P1Y:"year",PT10M:"10 minutes",PT1H:"hour",PT1M:"minute",PT24H:"24 hours",day:"day",round:"round",turn:"turn"},Edit:"Edit",EditHazardLabel:"Edit Hazard",EditItemTitle:"Edit Item",EditLabel:"Edit?",EffectPanel:{AppliedBy:"Applied by: {condition-list}",DecrementToolTip:"[Right Click] Decrease value",Expired:"Expired",IncrementToolTip:"[Left Click] Increase value",RemainingDuration:{MultipleDays:"{days} days remaining",MultipleHours:"{hours} hours remaining",MultipleMinutes:"{minutes} minutes remaining",MultipleRounds:"{rounds} rounds remaining",MultipleSeconds:"{seconds} seconds remaining",MultipleWeeks:"{weeks} weeks remaining",MultipleYears:"{years} years remaining",SingleRound:"1 round remaining",SingleSecond:"1 second remaining",SingleWeek:"1 week remaining",SingleYear:"1 year remaining",ZeroRoundsExpireTurnEnd:"0 rounds remaining, expires end of initiative {initiative}",ZeroRoundsExpireTurnStart:"0 rounds remaining, expires start of initiative {initiative}"},RemoveToolTip:"[Right Click] Remove effect",RollDamageToolTip:"[Left Click] Roll damage",Sustained:"Sustained?",Unidentified:"Unidentified",UnlimitedDuration:"Unlimited duration",UntilEncounterEnds:"Until encounter ends"},EffectsLabel:"Effects",EmptySlot:"Empty Slot",Encounter:{AlreadyRolled:"{actor} has already rolled initiative.",Broadcast:{FastHealing:{DeactivatedBy:"Deactivated by {types}","fast-healing":{Name:"Fast Healing",ReceivedMessage:"Received fast healing"},regeneration:{Name:"Regeneration",ReceivedMessage:"Received regeneration"}},TempHP:{PluralNew:"{actor} now has {newQuantity} temporary hit points{wasAt} from {item}.",SingleNew:"{actor} now has {newQuantity} temporary hit point{wasAt} from {item}.",WasAt:" (was at {oldQuantity})"}},Budget:{EncounterBudget:"Encounter Budget",PartyLevel:"Party Level",PartySize:"Party Size",Reward:"Reward",Threat:"Threat",Threats:{extreme:"Extreme",low:"Low",moderate:"Moderate",severe:"Severe",trivial:"Trivial"},XPBudget:"XP Budget",XPNeeded:"XP Needed"},CreatureXPAndRole:{CreatureLevel:"Creature Level",CreatureLevels:{0:"Any standard creature or low-threat boss",1:"Low- or moderate-threat boss",2:"Moderate- or severe-threat boss",3:"Severe- or extreme-threat boss",4:"Extreme-threat solo boss","-1":"Any standard creature","-2":"Any lackey or standard creature","-3":"Low- or moderate-threat lackey","-4":"Low-threat lackey"},CreatureXPAndRole:"Creature XP and Role",SuggestedRole:"Suggested Role"},ExcludingFromInitiative:"Excluding {type} {actor} from initiative.",HasNoInitiativeScore:"{actor} has no initiative score.",HideName:"Hide Name",InitiativeSet:"Initiative of {actor} was set to {initiative}.",Metrics:{Award:{Label:"Award: {xp} XP",Tooltip:{Four:"4 Party Members",Plural:"{xpPerFour} \xD7 4 / {recipients} Party Members",Singular:"1 Party Member"}},Budget:"Budget: {spent}/{max} XP (Party Level {partyLevel})",Threat:"Threat: <threat>{threat}</threat>"},NoActiveEncounter:"There is no active encounter.",NoTokenInScene:"{actor} has no token in the scene.",RevealName:"Reveal Name",XP:"XP"},ErrorMessage:{CantCreateEffectMacro:"An effect for a toggle macro must come from a compendium or world item.",CantImportTooHighVersion:"Unable to import {sourceName}: its schema version ({sourceSchemaVersion}) is higher than this world's ({worldSchemaVersion}).",CantMoveItemDestination:"You are not allowed to move items to this character.",CantMoveItemSource:"You are not allowed to move items from this character.",ItemNotFoundByUUID:'Item with UUID of "{uuid}" not found.',MinimumProfLevelSetByFeatures:"The selected proficiency is below proficiency set by features.",NoCreatureTokenSelected:"Select at least one token associated with a creature.",NoPCTokenSelected:"Select at least one token associated with a PC.",NoTokenSelected:"Select at least one token.",NoUpdatePermission:"You lack permission to update this actor.",NotEnoughAmmo:"You don't have enough ammo to make this strike.",NotEnoughCoins:"Insufficient Coins",RuleElementSyntax:"Syntax error in rule element definition: {message}",SubV9Module:"{module} is unmaintained and may introduce stability issues to your game.",WeaponNoDamage:"This weapon deals no damage.",WeaponQuantityZero:"You have no more of these weapons equipped."},Ethnicity:"Ethnicity",ExpendSpellTitle:"Expend Spell",Failure:"<strong>Failure</strong>",Familiar:{AbilitiesLabel:"Abilities",ArmorClass:"Armor Class",AttackRoll:"Attack Roll",Creature:"Creature",CreatureType:"Creature Type",Defenses:"Defense",Familiar:"Familiar",Master:"Master",MasterActor:"Master Actor",MasterLevel:"Master Level",MasterSpellcastingAbility:"Master Attribute",Offenses:"Offenses",Perception:"Perception",SelectMaster:"Select a master...",Skills:"Skills",TotalNumberFamiliarAbilities:"Total # of Familiar Abilities"},FeatActionTypeLabel:"Action Type",FeatActionsLabel:"Number of Actions",FeatAncestryHeader:"Ancestry Feats",FeatArchetypeHeader:"Archetype Feats",FeatBackgroundShort:"BG",FeatBonusHeader:"Bonus Feats",FeatBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:<br> source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. <br>Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",FeatCampaignHeader:"Campaign Feats",FeatClassHeader:"Class Feats",FeatDeityBoonCursesHeader:"Divine Intercessions",FeatGeneralHeader:"General Feats",FeatLevelLabel:"Level",FeatPFSBoonHeader:"Society Boons",FeatPrereqLabel:"Prerequisites",FeatSkillHeader:"Skill Feats",FeatTypeAncestry:"Ancestry Feat",FeatTypeAncestryfeature:"Ancestry Feature",FeatTypeBonus:"Bonus Feat",FeatTypeClass:"Class Feat",FeatTypeClassfeature:"Class Feature",FeatTypeCurse:"Deity Curse",FeatTypeDeityboon:"Deity Boon",FeatTypeGeneral:"General Feat",FeatTypePfsboon:"Society Boon",FeatTypeSkill:"Skill Feat",FeaturesAncestryHeader:"Ancestry Features",FeaturesClassHeader:"Class Features",Feet:"feet",FlatCheck:"Flat Check",Focus:{NotEnoughFocusPointsError:"You do not have enough focus points to cast this spell.",Outdated:"Old value of the focus pool as a reminder. Click to delete.",Pool:"Focus Pool",Previous:"Previous",Spells:"Focus Spells",label:"Focus Points",pointLabel:"Points"},Foot:"Foot",FormulaKnownTitle:"Known Formulas",FormulaListEmpty:"Empty (drag formula/item here)",Formula:"Formula",FormulaSheet:{DescriptionUnknown:"This formula is completely filled with drawings of small stick men, stains from some unknown liquid, nonsensical rhymes written in children's letters, and other seemingly random markings. It must have been made by goblins, and makes no sense to you.<hr><strong>Note</strong> This formula is referencing a missing or invalid item.",NameEmpty:"Empty Formula",NamePrefix:"Formula of {name}",NameUnknown:"Unknown Formula"},Frequency:{AtWill:"At-Will",Label:"Frequency",per:"per"},GenderPronoun:"Gender/Pronouns",GeneralFeatLevels:"General Feat Levels",GreaterWeaponSpecialization:"Greater Weapon Specialization",HardnessLabel:"Hardness",HazardDescriptionLabel:"Description",HazardDisableLabel:"Disable",HazardResetLabel:"Reset",HazardRoutineLabel:"Routine",HealingTypeTemporaryHealing:"Healing (Temporary)",Height:"Height",Heritage:"Heritage",HeroPointRatio:{Many:"{value}/{max} Hero Points",One:"1/{max} Hero Point"},HeroPointsLabel:"Hero Points",HitPointsDetailsLabel:"HP Details",HitPointsDetailsTitle:"Additional information related to Hit Points such as Fast Healing or Regeneration",HitPointsHeader:"Hit Points",HitPointsShortLabel:"HP",ImageLabel:"Image",ImmunitiesLabel:"Immunities",IncrementEffectTitle:"Increase Effect Level",InitiativeIsNow:"{name}'s Initiative is now {value}!",InitiativeHeader:"Initiative bonus",InitiativeLabel:"Initiative",InitiativeWithSkill:"Initiative: {skillName}",InlineCheck:{BasicWithSave:"Basic {save}",DCWithName:"{name} DC",Invalid:"Invalid @Check expression: {message}",Errors:{AdjustmentLengthMismatch:"mismatch between number of type and adjustment parameters",DCAndDefense:"cannot have both dc and defense arguments",NonIntegerAdjustment:"adjustments must be integers",TypeMissing:"type argument is mandatory",InvalidDomains:"{type} domains must be sluggified and end with -damage"}},InlineDamage:{Base:"Base: {formula}"},InlineTemplateErrors:{DistanceMissing:"Error in @Template: distance parameter is mandatory",DistanceNoNumber:"Error in @Template: dimension {distance} is not a number",TypeMissing:"Error in @Template: type parameter is mandatory",TypeUnsupported:"Error in @Template: type {type} is not supported",WidthNoNumber:"Error in @Template: width {width} is not a number"},InventroyBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:<br> source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. <br>Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",InvestedLabel:"Invested",Item:{ABC:{InvalidDrop:"{badType} cannot be dropped here (must be {goodType})"},Action:{Category:{None:"None",Defensive:"Defensive",Interaction:"Interaction",Offensive:"Offensive",Familiar:"Familiar Ability"},Plural:"Abilities",SelfAppliedEffect:{Applied:"{effect} was applied.",Delete:"Delete Reference",Drop:"Drop Effect",Label:"Self-Applied Effect",Hint:"A single effect item to be applied to the actor that uses this action"},Type:{Activity:"Activity",Free:"Free Action",Single:"Single Action",Reaction:"Reaction"}},Activation:{Add:"Add Activation",Cast:"Cast a Spell",Command:"command",CommandSheetLabel:"Command",Envision:"envision",EnvisionSheetLabel:"Envision",Interact:"Interact",Label:"Activation"},Affliction:{AddStage:"Add Stage",Error:{RestrictedStageItem:"Only effect items can be directly added to afflictions"},Linked:{Title:"If set, prevents the condition from being removed while the affliction lasts"},OnsetLabel:"Onset",OnsetActive:"Onset Active",SaveLabel:"Save DC",Stage:"Stage {stage}",StageLabel:"Stage"},Ancestry:{Vision:{Label:"Vision",Normal:"Normal Vision"}},Armor:{Base:{"armored-cloak":"Armored Cloak","armored-coat":"Armored Coat","bastion-plate":"Bastion Plate",breastplate:"Breastplate","buckle-armor":"Buckle Armor","ceramic-plate":"Ceramic Plate","chain-mail":"Chain Mail","chain-shirt":"Chain Shirt","coral-armor":"Coral Armor","explorers-clothing":"Explorer's Clothing","fortress-plate":"Fortress Plate","full-plate":"Full Plate",gi:"Gi","half-plate":"Half Plate","hellknight-breastplate":"Hellknight Breastplate","hellknight-half-plate":"Hellknight Half Plate","hellknight-plate":"Hellknight Plate","hide-armor":"Hide Armor","lamellar-breastplate":"Lamellar Breastplate","lattice-armor":"Lattice Armor","leaf-weave":"Leaf Weave","leather-armor":"Leather Armor","leather-lamellar":"Leather Lamellar","mantis-shell":"Mantis Shell",niyahaat:"Niyah\xE1at","o-yoroi":"O-Yoroi","padded-armor":"Padded Armor","power-suit":"Power Suit","quilted-armor":"Quilted Armor",sankeit:"Sankeit","scale-mail":"Scale Mail","scroll-robes":"Scroll Robes","splint-mail":"Splint Mail","studded-leather-armor":"Studded Leather Armor","subterfuge-suit":"Subterfuge Suit","wooden-breastplate":"Wooden Breastplate"},Category:{"heavy-barding":"Heavy Barding","light-barding":"Light Barding"},Rune:{Resilient:{Label:"Resilient Rune"}},Specific:{Hint:"Marking this armor as <i>specific magic armor</i> indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Armor"},UnequippedHint:"This armor is bulkier due to not being equipped."},CampaignFeature:{CampaignLabel:"Campaign"},CannotAddType:"{type} items cannot be added to this actor.",Condition:{Flanked:"Off-Guard (Flanked)",PersistentDamage:{AssistedRecovery:"Roll Assisted Recovery",Chat:{Recover:"Roll Recovery Check",RecoverLabel:"Recovery: {name}"},Dialog:{Add:"Add Persistent Damage",Invalid:"Formula is invalid.",Remove:"Remove Persistent Damage",Title:"Persistent Damage ({actor})"},Error:{DoesNotExist:"No persistent {damageType} damage exists on the actor"},Name:"Persistent Damage ({formula} {damageType})",NameWithDC:"Persistent Damage ({formula} DC{dc})",RollDamage:"Roll Damage"}},Consumable:{Damage:{Add:"Add Damage/Healing",Label:"Damage/Healing",Remove:"Remove Damage/Healing"},Category:{ammo:"Ammunition",catalyst:"Catalyst",drug:"Drug",elixir:"Elixir",fulu:"Fulu",gadget:"Gadget",mutagen:"Mutagen",oil:"Oil",other:"Other",poison:"Poison",potion:"Potion",scroll:"Scroll",snare:"Snare",talisman:"Talisman",toolkit:"Toolkit",wand:"Wand"},Plural:"Consumables",Uses:{AutoDestroy:"Destroy on Use",Label:"Uses",None:"No Uses Remain",Use:"Use"}},Container:{Bulk:{Capacity:"Bulk Capacity",Ignored:"Bulk Ignored"},Plural:"Containers",Stowing:"Is Stowing Container?"},CreationDialog:{Categories:{Character:"Character Building",Other:"Other",Physical:"Physical Items"}},Deity:{Alignment:"Alignment",Category:{Hint:"Pantheons of deities and philosophies not associated with any deity can be followed instead of a particular deity. Clerics and Champions must follow a deity or pantheon.",Pantheon:"Pantheon",Philosophy:"Philosophy"},ClericSpells:{DropError:"A deity's cleric spells may not include cantrips, focus spells, or rituals.",Hint:"To add a spell, drag and drop one onto this sheet.",Label:"Cleric Spells"},DivineAttribute:{Hint:"If choosing the Raised by Belief background, its attribute boost options come from a deity.",Label:"Divine Attribute"},DivineFont:{Harm:"Harm",Heal:"Heal",Label:"Divine Font"},DivineSkill:"Divine Skill",Domain:{Abomination:{Description:"You seek to instill abhorrence and horror in those around you.",Label:"Abomination"},Air:{Description:"You can control winds and the weather.",Label:"Air"},AirApocryphal:{Description:"You can control winds and the weather. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Air (apocryphal)"},Ambition:{Description:"You strive to keep up with and outpace the competition.",Label:"Ambition"},AmbitionApocryphal:{Description:"You strive to keep up with and outpace the competition. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Ambition (apocryphal)"},Change:{Description:"You can restructure the physical and metaphysical.",Label:"Change"},Cities:{Description:"You have powers over urban environments and denizens.",Label:"Cities"},Cold:{Description:"You control ice, snow, and freezing temperatures.",Label:"Cold"},Confidence:{Description:"You overcome your fear and project pride.",Label:"Confidence"},ConfidenceApocryphal:{Description:"You overcome your fear and project pride. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Confidence (apocryphal)"},Creation:{Description:"You have divine abilities related to crafting and art.",Label:"Creation"},Darkness:{Description:"You operate in the darkness and take away the light.",Label:"Darkness"},DarknessApocryphal:{Description:"You operate in the darkness and take away the light. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Darkness (apocryphal)"},Death:{Description:"You have the power to end lives and destroy undead.",Label:"Death"},DeathApocryphal:{Description:"You have the power to end lives and destroy undead. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Death (apocryphal)"},Decay:{Description:"You have the power to spoil and deteriorate matter.",Label:"Decay"},Delirium:{Description:"You can bring about hallucinations and restlessness.",Label:"Delirium"},Destruction:{Description:"You are a conduit for divine devastation.",Label:"Destruction"},Dreams:{Description:"You have the power to enter and manipulate dreams.",Label:"Dreams"},Dust:{Description:"You have the power to dry and crumble what opposes you.",Label:"Dust"},Duty:{Description:"You defend oaths and carry out your divine missions with great dedication.",Label:"Duty"},Earth:{Description:"You control soil and stone.",Label:"Earth"},Family:{Description:"You aid and protect your family and community more effectively.",Label:"Family"},Fate:{Description:"You see and understand hidden inevitabilities.",Label:"Fate"},FateApocryphal:{Description:"You see and understand hidden inevitabilities. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fate (apocryphal)"},Fire:{Description:"You control flame.",Label:"Fire"},FireApocryphal:{Description:"You control flame. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fire (apocryphal)"},Freedom:{Description:"You liberate yourself and others from shackles and constraints.",Label:"Freedom"},Glyph:{Description:"You wield power over written words and symbols.",Label:"Glyph"},Healing:{Description:"Your healing magic is particularly potent.",Label:"Healing"},Indulgence:{Description:"You feast mightily and can shake off the effects of overindulging.",Label:"Indulgence"},IndulgenceApocryphal:{Description:"You feast mightily and can shake off the effects of overindulging. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Indulgence (apocryphal)"},Introspection:{Description:"You guide others in examining their lives, emotions, and motivations to ultimately become a truer version of themselves\u2014a difficult and often painful process.",Label:"Introspection"},Knowledge:{Description:"You receive divine insights.",Label:"Knowledge"},KnowledgeApocryphal:{Description:"You receive divine insights. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Knowledge (apocryphal)"},Lightning:{Description:"You control electricity, thunder, and storms.",Label:"Lightning"},Luck:{Description:"You're unnaturally lucky and keep out of harm's way.",Label:"Luck"},Magic:{Description:"You perform the unexpected and inexplicable.",Label:"Magic"},Metal:{Description:"You manipulate flexible, mutable metal.",Label:"Metal"},Might:{Description:"Your physical power is bolstered by divine strength.",Label:"Might"},MightApocryphal:{Description:"Your physical power is bolstered by divine strength. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Might (apocryphal)"},Moon:{Description:"You command powers associated with the moon.",Label:"Moon"},Naga:{Description:"Like the serpentine nagas, you're in tune with cosmic forces that Ravithra once controlled.",Label:"Naga"},Nature:{Description:"You hold power over animals and plants.",Label:"Nature"},Nightmares:{Description:"You fill minds with horror and dread.",Label:"Nightmares"},Pain:{Description:"You punish those who displease you with the sharp sting of pain.",Label:"Pain"},Passion:{Description:"You evoke passion, whether as love or lust.",Label:"Passion"},Perfection:{Description:"You strive to perfect your mind, body, and spirit.",Label:"Perfection"},Plague:{Description:"You wield disease and pestilence like a weapon.",Label:"Plague"},Protection:{Description:"You ward yourself and others.",Label:"Protection"},Repose:{Description:"You ease mental burdens.",Label:"Repose"},Secrecy:{Description:"You protect secrets and keep them hidden.",Label:"Secrecy"},SecrecyApocryphal:{Description:"You protect secrets and keep them hidden. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Secrecy (apocryphal)"},Sorrow:{Description:"You have a painful connection to melancholy and sadness.",Label:"Sorrow"},Soul:{Description:"You wield power over the spiritual.",Label:"Soul"},Star:{Description:"You command the power of the stars.",Label:"Star"},Sun:{Description:"You harness the power of the sun and other light sources, and punish undead.",Label:"Sun"},Swarm:{Description:"You exert control over masses of creatures.",Label:"Swarm"},Time:{Description:"You reign over the flow of time.",Label:"Time"},Toil:{Description:"You work constantly and refuse to let anything stand in your way.",Label:"Toil"},Travel:{Description:"You have power over movement and journeys.",Label:"Travel"},TravelApocryphal:{Description:"You have power over movement and journeys. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Travel (apocryphal)"},Trickery:{Description:"You deceive others and cause mischief.",Label:"Trickery"},Truth:{Description:"You pierce lies and discover the truth.",Label:"Truth"},Tyranny:{Description:"You wield power to rule and enslave others.",Label:"Tyranny"},Undeath:{Description:"Your magic carries close ties to the undead.",Label:"Undeath"},Vigil:{Description:"You watch over those long passed and guard their secrets.",Label:"Vigil"},Void:{Description:"You draw power from emptiness.",Label:"Void"},Water:{Description:"You control water and bodies of water.",Label:"Water"},WaterApocryphal:{Description:"You control water and bodies of water. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Water (apocryphal)"},Wealth:{Description:"You hold power over wealth, trade, and treasure.",Label:"Wealth"},Wood:{Description:"You command the indomitable power of wood.",Label:"Wood"},Wyrmkin:{Description:"You draw on the power of dragons, linnorms, and other powerful reptilian creatures.",Label:"Wyrmkin"},Zeal:{Description:"Your inner fire increases your combat prowess.",Label:"Zeal"}},Domains:{Alternate:{Hint:"A cleric can take the Expanded Domain Initiate feat to gain access to one of their deity's alternate domains.",Label:"Alternate Domains"},Primary:"Primary Domains"},FavoredWeapons:{Hint:"Almost all deities have a single favored weapon, but a few have both a favored weapon and unarmed attack.",Label:"Favored Weapon(s)"},Sanctification:{Can:{Holy:"can choose holy",HolyUnholy:"can choose holy or unholy",Unholy:"can choose unholy"},Label:"Divine Sanctification",Must:{Holy:"must choose holy",Unholy:"must choose unholy"},None:"none"},Spellcasting:"Spellcasting"},Effect:{Expiry:{EndOfRound:"End of Round",EndOfTurn:"End of Turn",ExpiresOn:"Expires On",StartOfTurn:"Start of Turn"},Badge:{Add:"Add Badge",Labels:{Add:"Add Label",Label:"Labels",Hint:"The values of a badge can be given descriptive labels. They should be short enough to fit in the effects panel. Labels also serve as a natural maximum value for a badge.",Placeholder:"New Label"},Range:"Range",ReevaluateFormula:{Label:"Reevaluate?",Never:"Never",TurnEnd:"On Turn End",TurnStart:"On Turn Start"},Type:{counter:"Counter",formula:"Formula",value:"Fixed Value"}},Disintegrated:{Description:"Maybe it's a treatable condition.",Name:"Disintegrated"},Plural:"Effects",ShowTokenIcon:"Show token icon?",Sustained:"Sustained",Unidentified:"Unidentified?"},Feat:{Info:{Added:"{item} was added to {category}."},KeyAbilityOptions:{Label:"Key Attribute Options",Hint:"Key attribute options in addition to this provided by a class"},LevelLabel:"Feat",LevelN:"Feat {level}",OnlyLevel1:"Must be taken at level 1",Plural:"Feats",TakeMultiple:{Five:"Up to 5\xD7",Four:"Up to 4\xD7",Label:"Can be taken multiple times",NoLimit:"No limit",Three:"Up to 3\xD7",Two:"Up to 2\xD7"},Warning:{InvalidCategory:'Cannot add feat "{item}" to {category}: feat type is invalid.',TakenAfterLevel1:"{item} must be taken at level 1, but {actor} is at level {actorLevel}.",TakenMoreThanMax:"{item} may only be taken {maxTakable} times, but {actor} has selected it {timesTaken} times.",TakenMoreThanOnce:"{item} may only be taken once, but {actor} has selected it an additional time."}},GMNotes:{Add:"Add GM Notes",Title:"GM Notes"},Heritage:{AncestryNotFound:"The referenced ancestry item was not found.",DragAncestryHere:"Drag an ancestry item here to set this heritage's prerequisite ancestry.",NoneVersatile:"None (Versatile)",RemoveAncestry:"Remove prerequisite ancestry"},IconLabel:"Icon",MaterialEffects:{Hint:"Precious-material damage effects that can trigger or bypass some creatures' immunities, weaknesses, and resistances (applied to inline damage rolls)",Label:"Material Damage Effects"},NameLabel:"Name",OtherTags:{Label:"Other Tags",Hint:"Additional tags beyond traits to help classify an item"},Physical:{Base:"Base",Broken:"Broken",BrokenThreshold:{Label:"Broken Threshold",ShortLabel:"BT"},Bulk:{HeldOrStowed:"Bulk (held/stowed)",Label:"Bulk",Light:{Label:"Light",ShortLabel:"L"},Negligible:{Label:"Negligible",ShortLabel:"\u2014"},NLight:"{light}L",WithLight:"{bulk}, {light}L"},Destroyed:"Destroyed",FromSpell:{CantripDeck5:"Cantrip Deck of {name} (5-pack)",Scroll:"Scroll of {name} (Rank {level})",Wand:"Wand of {name} (Rank {level})"},GeneratedName:{FourProperties:"{property1} {property2} {property3} {property4} {base}",FourPropertiesMaterial:"{property1} {property2} {property3} {property4} {material} {base}",Fundamental2:"{fundamental2} {base}",Fundamental2Material:"{fundamental2} {material} {base}",Hint:'This is the name of the base weapon. For most weapons, the base is used to generate a fuller name, taking into account the material composition and/or runes. Giving this weapon a custom name or marking it as "specific" will prevent the generated name from appearing.',Material:"{material} {base}",OneProperty:"{property1} {base}",OnePropertyMaterial:"{property1} {material} {base}",Potency:"+{potency} {base}",PotencyFourProperties:"+{potency} {property1} {property2} {property3} {property4} {base}",PotencyFourPropertiesMaterial:"+{potency} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2:"+{potency} {fundamental2} {base}",PotencyFundamental2FourProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {base}",PotencyFundamental2FourPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2Material:"+{potency} {fundamental2} {material} {base}",PotencyFundamental2OneProperty:"+{potency} {fundamental2} {property1} {base}",PotencyFundamental2OnePropertyMaterial:"+{potency} {fundamental2} {property1} {material} {base}",PotencyFundamental2ThreeProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {base}",PotencyFundamental2ThreePropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {material} {base}",PotencyFundamental2TwoProperties:"+{potency} {fundamental2} {property1} {property2} {base}",PotencyFundamental2TwoPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {material} {base}",PotencyMaterial:"+{potency} {material} {base}",PotencyOneProperty:"+{potency} {property1} {base}",PotencyOnePropertyMaterial:"+{potency} {property1} {material} {base}",PotencyThreeProperties:"+{potency} {property1} {property2} {property3} {base}",PotencyThreePropertiesMaterial:"+{potency} {property1} {property2} {property3} {material} {base}",PotencyTwoProperties:"+{potency} {property1} {property2} {base}",PotencyTwoPropertiesMaterial:"+{potency} {property1} {property2} {material} {base}",Reinforcing:"{reinforcing} {base}",ReinforcingMaterial:"{reinforcing} {material} {base}",ThreeProperties:"{property1} {property2} {property3} {base}",ThreePropertiesMaterial:"{property1} {property2} {property3} {material} {base}",TwoProperties:"{property1} {property2} {base}",TwoPropertiesMaterial:"{property1} {property2} {material} {base}"},LevelLabel:"Item {level}",OtherTag:{Herbal:"Herbal",Improvised:"Improvised",Shoddy:"Shoddy"},OtherTags:{Hint:"These are tags indicating classifications in Second Edition rules that lack explicit status/definition but are still yet heavily relied upon. Some may be automatically added when other properties are present.",Label:"Other Tags"},MaterialRunes:{Label:"Precious Material and Runes"},PriceLabel:"Price: {price}",Usage:{WornParenthetical:"Worn ({where})",WornSlot:{amulet:"Amulet",anklets:"Anklets",armbands:"Armbands",armor:"Armor",backpack:"Backpack",barding:"Barding",belt:"Belt",beltpouch:"Belt Pouch",bracelet:"Bracelet",bracers:"Bracers",circlet:"Circlet",cloak:"Cloak",clothing:"Clothing",collar:"Collar",crown:"Crown",epaulet:"Epaulet",eyepiece:"Eyepiece",footwear:"Footwear",garment:"Garment",gloves:"Gloves",headwear:"Headwear",horseshoes:"Horseshoes",mask:"Mask",necklace:"Necklace",onbelt:"On Belt",ring:"Ring",saddle:"Saddle",shoes:"Shoes",wrist:"On Wrists"}}},Plural:"Items",RefreshFromCompendium:{Label:"Refresh",SourceNotFound:'The compendium source for "{item}" (source ID: {sourceId}) was not found.',Tooltip:{Disabled:"Item cannot be refreshed: contains data stored at time of adding to actor",Enabled:"Refresh this item's data with the latest from its originating compendium."}},RemovalPrevented:"Removal of {item} is prevented by {preventer}.",Rules:{Apply:"Apply",Close:"Close",Edit:"Edit JSON",Hint:{Slug:"A stable, human-readable identifier: if set, it will remain in place even if the item is renamed.",SourceId:"The UUID of the original compendium item",UUID:"A universally unique identifier for this item"},New:"New Rule Element",RegenerateSlug:"(Re)generate Slug",Remove:"Remove Rule Element",Tab:"Rules"},Shield:{Base:{buckler:"Buckler","casters-targe":"Caster's Targe","dart-shield":"Dart Shield","fortress-shield":"Fortress Shield","gauntlet-buckler":"Gauntlet Buckler","harnessed-shield":"Harnessed Shield","heavy-rondache":"Heavy Rondache","hide-shield":"Hide Shield",klar:"Klar","meteor-shield":"Meteor Shield","razor-disc":"Razor Disc","salvo-shield":"Salvo Shield","steel-shield":"Steel Shield","swordstealer-shield":"Swordstealer Shield","tower-shield":"Tower Shield","wooden-shield":"Wooden Shield"},Rune:{Reinforcing:{Greater:"Greater Reinforcing",Label:"Reinforcing Rune",Lesser:"Lesser Reinforcing",Major:"Major Reinforcing",Minor:"Minor Reinforcing",Moderate:"Moderate Reinforcing",Supreme:"Supreme Reinforcing"}},Specific:{Hint:"Marking this shield as a <i>specific magic shield</i> indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Shield"}},SidebarSummary:"{type} Summary",Spell:{Area:"{size}-{unit} {shape}",Cast:"Cast",Cost:"Cost",Counteract:{Hint:"If you're counteracting an affliction, the DC is in the affliction's stat block. If it's a spell, use the caster's DC. The GM can also calculate a DC based on the target effect's level.",Label:"Counteract",criticalFailure:"You fail to counteract the target.",criticalSuccess:"Counteract the target if its counteract rank is {rank} or less.",failure:"Counteract the target if its counteract rank is less than {rank}.",success:"Counteract the target if its counteract rank is {rank} or less."},Defense:{BasicSave:"Basic",Label:"Defense"},LevelN:"Spell {level}",MeasuredTemplate:{Clear:"Clear Placed Templates",Place:"Place {area}"},Plural:"Spells",Rank:{Label:"Rank",Ordinal:"{rank} Rank",Plural:"Ranks"},Ritual:{Label:"Ritual",PrimaryCheck:"Primary Check",SecondaryChecks:"Secondary Checks",SecondaryCasters:"Secondary Casters"},Variants:{DeleteDialogText:"Are you sure you want to delete '{variantName}'?",DeleteDialogTitle:"Delete Spell Variant",LabelPlural:"Spell Variants",SelectOtherVariantLabel:"Select Other Variant",SelectVariantLabel:"Select Variant",SheetTitle:"{originalName} (Variant)"},Warning:{InvalidLevel:"Attempted to add spell {name} at {targetLevel}, but spell is {baseLevel}.",WrongSpellType:"Cannot add {spellType} spell to this casting entry."}},Weapon:{CanBeAmmo:{Label:"Usable as Ammo",Hint:"Indicate that this weapon can be loaded into another weapon as ammunition."},CriticalSpecialization:{axe:"Choose one creature adjacent to the initial target and within reach. If its AC is lower than your attack roll result for the critical hit, you deal damage to that creature equal to the result of the weapon damage die you rolled (including extra dice for its potency rune, if any). This amount isn't doubled, and no bonuses or other additional dice apply to this damage.",bomb:"Increase the radius of the bomb's splash damage (if any) to 10 feet.",bow:"If the target of the critical hit is adjacent to a surface, it gets stuck to that surface by the missile. The target is @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} and must spend an Interact action to attempt a @Check[type:athletics|dc:10|name:Pull the Missile Free|showDC:all] check to pull the missile free; it can't move from its space until it succeeds. The creature doesn't become stuck if it is incorporeal, is liquid (like a water elemental or some oozes), or could otherwise escape without effort",brawling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Brawling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn.",club:"You knock the target away from you up to 10 feet (you choose the distance). This is forced movement.",firearm:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Firearm Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",flail:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they success at a @Check[type:reflex|dc:resolve(@actor.attributes.classDC.value)|name:Flail Critical Specialization] save against your class DC.",hammer:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Hammer Critical Specialization] save against your class DC.",polearm:"The target is moved 5 feet in a direction of your choice. This is forced movement.",shield:"You knock the target back from you 5 feet. This is forced movement.",sling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Sling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",spear:"The weapon pierces the target, weakening its attacks. The target is @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} until the start of your next turn.",sword:"The target is made off-balance by your attack, becoming @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} until the start of your next turn."},Damage:{DiceNumber:"Dice Number"},FromABP:"Automatic bonus progression has adjusted this weapon's {property} to {value}.",FromMaterialAndRunes:"Precious materials and runes on this item have adjusted its {property} to {value}.",HandsLabel:"Hands",MandatoryMelee:"This weapon has a trait that can only be used with melee weapons.",MaterialAndRunes:{MaterialOption:"{type} ({grade})",Title:"Material Composition and Runes"},MeleeUsage:{Hint:"A combination weapon has a firearm form or usage and a melee weapon form or usage. Switching between the melee weapon usage and the firearm usage requires an Interact action. However, if your last action was a successful melee Strike against a foe using a combination weapon, you can make a firearm Strike with the combination weapon against that foe without fully switching to the firearm usage, firing the firearm just as you hit with the melee attack. In this case, the combination weapon returns to its melee usage after the firearm Strike.",Label:"Melee Usage"},NoRangeMelee:"None (Melee)",RangeIncrementN:{Hint:"Ranged and thrown weapons have a range increment. Attacks with these weapons work normally up to that distance. Attack rolls beyond a weapon's range increment take a -2 penalty for each additional multiple of that increment between you and the target. Attacks beyond the sixth range increment are impossible.",Label:"Range Increment {range} ft."},Reload:{LabelN:"Reload {value}",OneMinute:"1 min"},Rune:{Potency:"Weapon Potency",Striking:{Greater:"Greater Striking",Major:"Major Striking",Striking:"Striking"}},SpecificMagicWeapon:{Hint:"Marking this weapon as a <i>specific magic weapon</i> indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Weapon"},ThrownUsage:{Label:"Thrown Usage"}},WorldItemWarning:"This is a World Item and will not work if saved in a compendium"},ItemBonus0:"0",ItemBonus1:"+1 Weapon Potency",ItemBonus2:"+2 Weapon Potency",ItemBonus3:"+3 Weapon Potency",ItemBonusLabel:"Item Bonus",ItemBonusMinus2:"Shoddy (-2)",ItemBonusShortLabel:"Item",ItemDescription:"Description",ItemDescriptionHeader:"Description",ItemDetails:"Details",ItemLevel:"{type} {level}",ItemMystification:"Mystification",ItemMystified:"Mystified",ItemNamePlaceholder:"Name",ItemNewSkillVariant:"New Skill Variant",ItemNotSupportedOnActor:"Item not supported on actor",ItemRemoveRuleElement:"Remove Rule Element",ItemTitle:"Item",ItemsLabel:"Items",Keybinding:{CycleTokenStack:{Hint:"Cycle the Z indices of a mouse-hovered stack of tokens, pushing the top to the bottom.",Label:"Cycle Token Stack"},GMVision:{Hint:"Brighten dark scenes for easier viewing.",Label:"GM Vision"},TogglePartySheet:{Hint:"Open or close the sheet of the active or (if a player) assigned party.",Label:"Toggle Party Sheet"}},KitItems:"Items",KitWorldItem:"This item is not found in a Compendium and will not work in other worlds",LackCastConsumableCapability:"{actor} lacks the proficiency to use {spell} and does not have the Trick Magic Item feat.",Languages:"Languages",LanguagesAdditional:"Additional Languages",Level1:"Level 1",Level10:"Level 10",Level11:"Level 11",Level12:"Level 12",Level13:"Level 13",Level14:"Level 14",Level15:"Level 15",Level16:"Level 16",Level17:"Level 17",Level18:"Level 18",Level19:"Level 19",Level2:"Level 2",Level20:"Level 20",Level3:"Level 3",Level4:"Level 4",Level5:"Level 5",Level6:"Level 6",Level7:"Level 7",Level8:"Level 8",Level9:"Level 9",LevelLabel:"Level",LevelN:"Level {level}",LevelRange:"Levels {minLevel} - {level}",LicenseViewer:{Label:"Legal Notice",LandingPageText:"Use the tabs above to read the legal information"},ListPartsAnd:{end:"{first}, and {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} and {second}"},ListPartsOr:{end:"{first}, or {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} or {second}"},Lore:"Lore",LoreProficiencyDisclaimer:"Informational only. Will not change the skill modifier.",LoreSkillsHeader:"Lore Skills",MAPAbbreviationLabel:"MAP {penalty}",MAPAbbreviationValueLabel:"{value} (MAP {penalty})",Macro:{OptionToggle:{Notification:"{toggle} has been toggled {state}.",Off:"OFF",On:"ON"},Plural:"Macros",NoCompendiumItem:"A macro cannot be created from a compendium item that isn't an effect or condition."},MacroActionNoActionError:"This action no longer exists!",MacroActionNoActorError:"This actor no longer exists!",MagicTraditionLabel:"Magic Tradition",MagicTraditionUseSpellLabel:"Use Spell Tradition",MasterAbility:{cha:"Master Charisma",con:"Master Constitution",dex:"Master Dexterity",int:"Master Intelligence",str:"Master Strength",wis:"Master Wisdom"},MasterArmorClass:"Master Armor Class {base}",MasterLevel:"Master Level",MasterSavingThrow:{fortitude:"Master Fortitude",reflex:"Master Reflex",will:"Master Will"},MaxHitPointsBaseLabel:"Base Max HP {base}",MaxHitPointsShortLabel:"Max HP",MaxStaminaPointsShortLabel:"Max SP",Migrations:{Finished:"PF2E System Migration to version {version} completed!",OnlyGMCanUse:"Only a gamemaster can use this tool.",OutsideSchemaRange:"The specified range is outside the system's schema version range (between {minimum} and {maximum}).",Running:"Running system migration ...",Starting:"Applying PF2E System Migration to version {version}. Please be patient and do not close your game or shut down your server.",Summary:{Documents:"Documents",HelpResources:'An unexpected error was encountered while migrating some actors or items. If you would like further assistance, feel free to report an issue at the <a href="https://github.com/foundryvtt/pf2e/issues">system repository</a> or visit us on <a href="https://discord.gg/SajryVzCyf">Discord</a> for community support.',Migrated:"Migrated",Remigrate:"Remigrate",Title:"Migration Summary",Total:"Total",Troubleshoot:{Hint:"Here you can run a remigration, which will attempt to automatically fix issues with actors and items.",Title:"System Troubleshooting"}},Troubleshooting:"Troubleshooting",WorldNotReady:"Game world not ready: try again in a few seconds."},ModifierNamePlaceholder:"Name",ModifierTitle:"Modifier",ModifierType:{ability:"Attribute",circumstance:"Circumstance",item:"Item",potency:"Potency",proficiency:"Proficiency",status:"Status",untyped:"Untyped"},ModifierTypeTitle:"[Type]",ModifiersTitle:"Modifiers",MultipleAttackPenalty:"Multiple Attack Penalty",MysticStrikes:"Mystical Strikes",NPC:{Abilities:{Glossary:{AllAroundVision:"<p>This monster can see in all directions simultaneously, and therefore can't be flanked.</p>",AquaticAmbush:`<p><strong>Requirements</strong> The monster is hiding in water and a creature that hasn't detected it is within the listed number of feet.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster moves up to its swim Speed + 10 feet toward the triggering creature, traveling on water and on land. Once the creature is in reach, the monster makes a Strike against it. The creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against this Strike.</p>`,AtWillSpells:"<p>The monster can cast its at-will spells any number of times without using up spell slots.</p>",AttackOfOpportunity:`<p><strong>Trigger</strong> A creature within the monster's reach uses a manipulate action or a move action, makes a ranged attack, or leaves a square during a move action it's using.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster attempts a melee Strike against the triggering creature. If the attack is a critical hit and the trigger was a manipulate action, the monster disrupts that action. This Strike doesn't count toward the monster's multiple attack penalty, and its multiple attack penalty doesn't apply to this Strike.</p>`,Aura:`<p>A monster's aura automatically affects everything within a specified emanation around that monster. The monster doesn't need to spend actions on the aura; rather, the aura's effects are applied at specific times, such as when a creature ends its turn in the aura or when creatures enter the aura.</p>
|
|
<p>If an aura does nothing but deal damage, its entry lists only the radius, damage, and saving throw. Such auras deal this damage to a creature when the creature enters the aura and when a creature starts its turn in the aura. A creature can take damage from the aura only once per round.</p>
|
|
<p>The GM might determine that a monster's aura doesn't affect its own allies. For example, a creature might be immune to a monster's frightful presence if they have been around each other for a long time.</p>`,Buck:`<hr />
|
|
<p>Most monsters that serve as mounts can attempt to buck off unwanted or annoying riders, but most mounts will not use this reaction against a trusted creature unless the mounts are spooked or mistreated.</p>
|
|
<p><strong>Trigger</strong> A creature @UUID[Compendium.pf2e.actionspf2e.Item.PM5jvValFkbFH3TV]{Mounts} or uses the @UUID[Compendium.pf2e.actionspf2e.Item.q9nbyIF0PEBqMtYe]{Command an Animal} action while riding the monster.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The triggering creature must succeed at a Reflex saving throw against the listed DC or fall off the creature and land @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone}. If the save is a critical failure, the triggering creature also takes [[/roll 1d6[bludgeoning]]]{1d6 bludgeoning damage} in addition to the normal damage for the fall.</p>`,CatchRock:`<p><strong>Requirements</strong> The monster must have a free hand but can @UUID[Compendium.pf2e.actionspf2e.Item.wQYmDStjdjn0I26t]{Release} anything it's holding as part of this reaction.</p>
|
|
<p><strong>Trigger</strong> The monster is targeted with a thrown rock Strike or a rock would fall on the monster.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster gains a +4 circumstance bonus to its AC against the triggering attack or to any defense against the falling rock. If the attack misses or the monster successfully defends against the falling rock, the monster catches the rock, takes no damage, and is now holding the rock.</p>`,ChangeShape:"<p>The monster changes its shape indefinitely. It can use this action again to return to its natural shape or adopt a new shape. Unless otherwise noted, a monster cannot use Change Shape to appear as a specific individual. Using Change Shape counts as creating a disguise for the @UUID[Compendium.pf2e.actionspf2e.Item.AJstokjdG6iDjVjE]{Impersonate} use of Deception. The monster's transformation automatically defeats Perception DCs to determine whether the creature is a member of the ancestry or creature type into which it transformed, and it gains a +4 status bonus to its Deception DC to prevent others from seeing through its disguise. Change Shape abilities specify what shapes the monster can adopt. The monster doesn't gain any special abilities of the new shape, only its physical form. For example, in each shape, it replaces its normal Speeds and Strikes, and might potentially change its senses or size. Any changes are listed in its stat block.</p>",ConstantSpells:"<p>A constant spell affects the monster without the monster needing to cast it, and its duration is unlimited. If a constant spell gets counteracted, the monster can reactivate it by spending the normal spellcasting actions the spell requires.</p>",Constrict:"<p>The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC.</p>",Coven:`<p>This monster can form a coven with two or more other creatures who also have the coven ability. This involves performing an 8-hour ceremony with all prospective coven members. After the coven is formed, each of its members gains elite adjustments, adjusting their levels accordingly. Coven members can sense other members' locations and conditions by spending a single action, which has the concentrate trait, and can sense what another coven member is sensing as a two-action activity, which has the concentrate trait as well.</p>
|
|
<p>Covens also grant spells and rituals to their members, but these can be cast only in cooperation between three coven members who are all within 30 feet of one another. A coven member can contribute to a coven spell with a single-action spellcasting activity that has a single verbal component. If two coven members have contributed these actions within the last round, a third member can cast a coven spell on her turn by spending the normal spellcasting actions. A coven can cast its coven spells an unlimited number of times but can cast only one coven spell each round. All covens grant the 8th-rank <em>@UUID[Compendium.pf2e.spells-srd.Item.dN8QBNuTiaBHCKUe]{Baleful Polymorph}</em> spell and all the following spells, which the coven can cast at any rank up to 5th: <em>@UUID[Compendium.pf2e.spells-srd.Item.41TZEjhO6D1nWw2X]{Augury}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.vLA0q0WOK2YPuJs6]{Charm}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.HXhWYJviWalN5tQ2]{Clairaudience}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.zvKWclOZ7A53DObE]{Clairvoyance}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.yM3KTTSAIHhyuP14]{Dream Message}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.i35dpZFI7jZcRoBo]{Illusory Disguise}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.Ucf8eynbZMfUucjE]{Illusory Scene}</em>, <em>@UUID[Compendium.pf2e.spells-srd.Item.Ek5XI0aEdZhBgm21]{Prying Eye}</em>, and <em>@UUID[Compendium.pf2e.spells-srd.Item.FM3SmEW8N1FCRjqt]{Talking Corpse}</em>. Individual creatures with the coven ability also grant additional spells to any coven they join. A coven can also cast the <em>@UUID[Compendium.pf2e.spells-srd.Item.XkDCzMIyc0YOjw05]{Control Weather}</em> ritual, with a DC of 23 instead of the standard DC.</p>
|
|
<p>If a coven member leaving the coven or the death of a coven member brings the coven below three members, the remaining members keep their elite adjustments for 24 hours, but without enough members to contribute the necessary actions, they can't cast coven spells.</p>`,Darkvision:"<p>A monster with darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank <em>@UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness}</em> spell, block normal darkvision. A monster with @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.4Ho2xMPEC05aSxzr]{Greater Darkvision}, however, can see through even these forms of magical darkness.</p>",Disease:"<p>When a creature is exposed to a monster's disease, it attempts a Fortitude save or succumbs to the disease. The level of a disease is the level of the monster inflicting the disease. The disease follows the rules for afflictions.</p>",Engulf:`<p>The monster Strides up to double its Speed and can move through the spaces of any creatures in its path. Any creature of the monster's size or smaller whose space the monster moves through can attempt a Reflex save with the listed DC to avoid being engulfed. A creature unable to act automatically critically fails this save. If a creature succeeds at its save, it can choose to be either pushed aside (out of the monster's path) or pushed in front of the monster to the end of the monster's movement. The monster can attempt to Engulf the same creature only once in a single use of Engulf. The monster can contain as many creatures as can fit in its space.</p>
|
|
<p>A creature that fails its save is pulled into the monster's body. It is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The creature takes the listed amount of damage when first engulfed and at the end of each of its turns while it's engulfed. An engulfed creature can get free by @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escaping} against the listed escape DC. An engulfed creature can attack the monster engulfing it, but only with unarmed attacks or with weapons of light Bulk or less. The engulfing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the engulfed creature cuts itself free. A creature that gets free by either method can immediately breathe and exits the swallowing monster's space.</p>
|
|
<p>If the monster dies, all creatures it has engulfed are automatically released as the monster's form loses cohesion.</p>`,FastHealing:"<p>A monster with this ability regains the given number of Hit Points each round at the beginning of its turn.</p>",Ferocity:`<p><strong>Trigger</strong> The monster is reduced to 0 HP.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster avoids being knocked out and remains at 1 HP, but its @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded} value increases by 1. When it is Wounded 3, it can no longer use this ability</p>`,FormUp:"<p>The troop chooses one of the squares it currently occupies and redistributes its squares to any configuration in which all squares are contiguous and within 15 feet of the chosen square. The troop can't share its space with other creatures.</p>",FrightfulPresence:`<p>A creature that first enters the area must attempt a Will save.</p>
|
|
<p>Regardless of the result of the saving throw, the creature is temporarily immune to this monster's Frightful Presence for 1 minute.</p>
|
|
<hr />
|
|
<p><strong>Critical Success</strong> The creature is unaffected by the presence.</p>
|
|
<p><strong>Success</strong> The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}.</p>
|
|
<p><strong>Failure</strong> The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}.</p>
|
|
<p><strong>Critical Failure</strong> The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 4}.</p>`,Grab:"<p><strong>Requirements</strong> The monster's last action was a successful Strike that lists Grab in its damage entry, or the monster has a creature @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained}</p><hr /><p><strong>Effect</strong> If used after a Strike, the monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.PMbdMWc2QroouFGD]{Grapple} the creature using the body part it attacked with. This attempt neither applies nor counts toward the creature's multiple attack penalty.</p><p>The monster can instead use Grab and choose one creature it's grabbing or restraining with an appendage that has Grab to automatically extend that condition to the end of the monster's next turn.</p>",GreaterConstrict:"<p>The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC. A creature that fails this save falls @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}, and a creature that succeeds is then temporarily immune to falling unconscious from Greater Constrict for 1 minute.</p>",GreaterDarkvision:"<p>A creature with greater darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank <em>@UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness}</em> spell, block normal @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.qCCLZhnp2HhP3Ex6]{Darkvision}. A creature with greater darkvision, however, can see through even these forms of magical darkness.</p>",ImprovedGrab:"<p>The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.Tkd8sH4pwFIPzqTr]{Grab} as a free action triggered by a hit with its initial attack. A monster with Improved Grab still needs to spend an action to extend the duration for creatures it already has @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.</p>",ImprovedKnockdown:"<p>The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.BCLvAx4Pz4MLa2pu]{Knockdown} as a free action triggered by a hit with its initial attack.</p>",ImprovedPush:"<p>The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.t6cx9FOODmeZQNYl]{Push} as a free action triggered by a hit with its initial attack.</p>",Knockdown:"<p><strong>Requirements</strong> The monster's last action was a successful Strike that lists Knockdown in its damage entry</p><hr /><p><strong>Effect</strong> The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.ge56Lu1xXVFYUnLP]{Trip} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty.</p>",Lifesense:"<p>Lifesense allows a monster to sense the vital essence of living and undead creatures within the listed range. The sense can distinguish between the vitality energy animating living creatures and the void energy animating undead creatures, much as sight distinguishes colors.</p>",LightBlindness:"<p>When first exposed to bright light, the monster is @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} until the end of its next turn. After this exposure, light doesn't blind the monster again until after it spends 1 hour in darkness. However, as long as the monster is in an area of bright light, it's @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.</p>",LowLightVision:"<p>The monster can see in dim light as though it were bright light, so it ignores the @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} condition due to dim light.</p>",NegativeHealing:"<p>A creature with void healing draws health from void energy rather than vitality energy. It is damaged by vitality damage and is not healed by vitality healing effects. It does not take void damage, and it is healed by void effects that heal undead.</p>",Poison:"<p>When a creature is exposed to a monster's poison, it attempts a Fortitude save to avoid becoming poisoned. The level of a poison is the level of the monster inflicting the poison. The poison follows the rules for afflictions.</p>",PowerAttack:`<p><strong>Frequency</strong> once per round</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster makes a melee Strike. This counts as two attacks when calculating the monster's multiple attack penalty. If this Strike hits, the monster deals an extra die of weapon damage.</p>`,Push:"<p><strong>Requirements</strong> The monster's last action was a successful Strike that lists Push in its damage entry</p><hr /><p><strong>Effect</strong> The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.7blmbDrQFNfdT731]{Shove} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty. If Push lists a distance, change the distance the creature is pushed on a success to that distance.</p>",Regeneration:"<p>This monster regains the listed number of Hit Points each round at the beginning of its turn. Its @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition never increases beyond Dying 3 as long as its regeneration is active. However, if it takes damage of a type listed in the regeneration entry, its regeneration deactivates until the end of its next turn. Deactivate the regeneration before applying any damage of a listed type, since that damage might kill the monster by bringing it to Dying 4.</p>",Rend:`<p>A Rend entry lists a Strike the monster has.</p>
|
|
<p><strong>Requirements</strong> The monster hit the same enemy with two consecutive Strikes of the listed type in the same round.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster automatically deals that Strike's damage again to the enemy.</p>`,RetributiveStrike:`<p><strong>Trigger</strong> An enemy damages the monster's ally, and both are within 15 feet of the monster.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The ally gains resistance to all damage against the triggering damage equal to 2 + the monster's level. If the foe is within reach, the monster makes a melee Strike against it.</p>`,Scent:`<p>Scent involves sensing creatures or objects by smell, and is usually a vague sense. The range is listed in the ability, and it functions only if the creature or object being detected emits an aroma (for instance, incorporeal creatures usually do not exude an aroma).</p>
|
|
<p>If a creature emits a heavy aroma or is upwind, the GM can double or even triple the range of scent abilities used to detect that creature, and the GM can reduce the range if a creature is downwind.</p>`,ShieldBlock:`<p><strong>Trigger</strong> The monster has its shield raised and takes damage from a physical attack.</p>
|
|
<hr />
|
|
<p><strong>Effect</strong> The monster snaps its shield into place to deflect a blow. The shield prevents the monster from taking an amount of damage up to the shield's Hardness. The monster and the shield each take any remaining damage, possibly breaking or destroying the shield.</p>`,SneakAttack:"<p>When the monster Strikes a creature that has the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition with an agile or finesse melee weapon, an agile or finesse unarmed attack, or a ranged weapon attack, it also deals the listed precision damage. For a ranged attack with a thrown weapon, that weapon must also be an agile or finesse weapon.</p>",SwallowWhole:`<p>The monster attempts to swallow a creature of the listed size or smaller that it has grabbed in its jaws or mouth. If a swallowed creature is of the maximum size listed, the monster can't use Swallow Whole again. If the creature is smaller than the maximum, the monster can usually swallow more creatures; the GM determines the maximum. The monster attempts an @Check[type:athletics|defense:reflex] check opposed by the grabbed creature's Reflex DC. If it succeeds, it swallows the creature. The monster's mouth or jaws no longer grab a creature it has swallowed, so the monster is free to use them to Strike or Grab once again. The monster can't attack creatures it has swallowed.</p>
|
|
<p>A swallowed creature is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The swallowed creature takes the listed amount of damage when first swallowed and at the end of each of its turns while it's swallowed. If the victim @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escapes} this ability's grabbed condition, it exits through the monster's mouth. This frees any other creature grabbed in the monster's mouth or jaws. A swallowed creature can attack the monster that has swallowed it, but only with unarmed attacks or with weapons of light Bulk or less. The swallowing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the swallowed creature cuts itself free. A creature that gets free by either Escaping or cutting itself free can immediately breathe and exits the swallowing monster's space.</p>
|
|
<p>If the monster dies, a swallowed creature can be freed by creatures adjacent to the corpse if they spend a combined total of 3 actions cutting the monster open with a weapon or unarmed attack that deals piercing or slashing damage.</p>`,SwarmMind:"<p>This monster doesn't have a single mind (typically because it's a swarm of smaller creatures), and is immune to mental effects that target only a specific number of creatures. It is still subject to mental effects that affect all creatures in an area.</p>",Telepathy:"<p>A monster with telepathy can communicate mentally with any creatures within the listed radius, as long as they share a language. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.</p>",Thoughtsense:"<p>Thoughtsense allows a monster to sense all non-mindless creatures at the listed range.</p>",ThrowRock:"<p>The monster picks up a rock within reach or retrieves a stowed rock and throws it, making a ranged Strike.</p>",Trample:"<p>The monster Strides up to double its Speed and can move through the spaces of creatures of the listed size, Trampling each creature whose space it enters. The monster can attempt to Trample the same creature only once in a single use of Trample. The monster deals the damage of the listed Strike, but trampled creatures can attempt a basic Reflex save at the listed DC (no damage on a critical success, half damage on a success, double damage on a critical failure).</p>",Tremorsense:"<p>Tremorsense allows a monster to feel the vibrations through a solid surface caused by movement. It is an imprecise sense with a limited range (listed in the ability). Tremorsense functions only if the monster is on the same surface as the subject, and only if the subject is moving along (or burrowing through) the surface.</p>",TroopDefenses:`<p>Troops are composed of many individuals, and over the course of enough attacks and downed comrades, troops shrink in size. Most troops start with 16 squares (4 by 4), and their Hit Points have two listed thresholds, typically the first is at 2/3 their maximum Hit Points and the second is at 1/3 their maximum Hit Points. Once the troop drops below the first threshold, it loses 4 squares, leaving 12 squares remaining, and the first threshold becomes the troop's new maximum Hit Points. Once the troop falls below the second threshold, it loses another 4 squares, leaving 8 squares remaining, and the second threshold becomes the troop's new maximum Hit Points. In order to restore its size and maximum Hit Points, a troop needs to spend downtime to use long-term treatment on casualties or recruit new members to replace the fallen. At 0 Hit Points, the troop is reduced down to 4 squares, which is too few to sustain the troop, so it disperses entirely, with the few remaining members surrendering, fleeing, or easily dispatched, depending on their nature.</p>
|
|
<p>A damaging single-target effect, such as a Strike, can't force a troop to pass through more than one threshold at once. For instance, if a troop had 60 Hit Points, with thresholds at 40 and 20, a Strike for 50 damage would leave the troop at 21 Hit Points, just above the second threshold. A damaging area effect or multi-target effect can cross multiple thresholds at once and could potentially destroy the entire troop in one shot.</p>
|
|
<p>Non-damaging effects with an area or that target all creatures in a certain proximity affect a troop normally if they affect the entire area occupied by the troop. If an effect has a smaller area or numbers of targets, it typically has no effect on the troop. However, if the effect can target at least four creatures or cover at least four squares in the troop, and if it would prevent its targets from acting, cause them to flee, or otherwise make them unable to function as part of the troop for a round or more, the troop loses loses a number of Hit Points equal to the amount required to bring it to the next threshold, removing 4 squares. If an effect would both deal damage and automatically cross a threshold due to incapacitating some of the creatures in the troop, apply the damage first. If the damage wasn't enough to cross a threshold on its own, then reduce the Hit Points to cross the threshold for the incapacitating effect.</p>`,Wavesense:"<p>This sense allows a monster to feel vibrations caused by movement through a liquid. It's an imprecise sense with a limited range (listed in the ability). Wavesense functions only if monster and the subject are in the same body of liquid, and only if the subject is moving through the liquid.</p>"}},ActionsList:{ActionName:"Name",Cost:"Cost",Traits:"Traits",Type:"Type"},AddAction:"Add Action",AddArmor:"Armor",AddConsumable:"Consumable",AddEquipment:"Equipment",AddItem:"Add Item",AddPassive:"Add Passive",AddSkill:"Add Skill",AddTrait:"Add Trait",AddTreasure:"Treasure",AddWeapon:"Weapon",Adjustment:{EliteLabel:"Elite",EliteNameFormat:"Elite {name}",NormalLabel:"Normal",WeakLabel:"Weak",WeakNameFormat:"Weak {name}"},ArmorExtraInfoLabelPlaceholder:"AC details...",AttackType:{Melee:"NPC Melee Attack",Ranged:"NPC Ranged Attack",Weapon:"Compendium Weapon"},Attacks:"Attacks",Creature:"Creature",Dead:"Dead",Edit:"Edit",EditImmunities:"Edit Immunities",EditLanguages:"Edit Languages",EditResistances:"Edit Resistances",EditSenses:"Edit Senses",EditSkills:"Edit Skills",EditSpeed:"Edit Speed",EditTraits:"Edit Traits",EditWeaknesses:"Edit Weaknesses",EffectsTab:"Effects",HPExtraInfoLabelPlaceholder:"HP details...",Inventory:{Header:{NameLabel:"Name",QuantityLabel:"Quantity",ValueLabel:"Value"}},InventoryTab:"Inventory",MainTab:"Main",NotesTab:"Notes",PassivesLabel:"Passives",PrivateNotes:"Private Notes",PublicNotes:"Description",Remove:"Remove",SavesExtraInfoLabelPlaceholder:"Bonus to all saves...",SendToChat:"Send to chat",SensesLabel:"Senses",SkillRollFlavor:"{skillName} Skill Check ({rank})",SpeedExtraInfoLabelPlaceholder:"Speed details...",SpeedLabel:"Speed",Spells:{AttackLabel:"Attack",DCLabel:"DC",PreparedLabel:"Prepared",PreparedShortLabel:"Prep."},SpellsTab:"Spells"},NPCAttackMelee:"Melee",NPCAttackRanged:"Ranged",NPCNotesLabel:"Notes/Conditions",NPCNotesTitle:"Write any notes for this NPC here.",NPCWeaponAddDamage:"Add Damage Partial",NPCWeaponAttackEffect:"Additional Attack Effects",NPCWeaponAttackLabel:"Attack Modifier",NPCWeaponDamageLabel:"Damage Formula",Nationality:"Nationality",NewLabel:"New",NewLoreSkill:"New skill",NewPlaceholders:{Action:"New Action",Ancestry:"New Ancestry",Armor:"New Armor",Background:"New Background",Backpack:"New Container",Condition:"New Condition",Consumable:"New Consumable",Equipment:"New Equipment",Feat:"New Feat",Kit:"New Kit",Lore:"New Lore",Melee:"New Attack",Skill:"New Skill",Spell:"New Spell",SpellcastingEntry:"New Spellcasting Entry",Treasure:"New Treasure",Weapon:"New Weapon"},NoAmmoLabel:"No Ammo",NoneOption:"None",OK:"OK",OpenActionBrowserTitle:"Open Action Browser",OpenInventoryBrowser:"Open Inventory Browser",OpenItemTitle:"Toggle Container Contents",OpenSpellBrowserTitle:"Open Spell Browser",OrdinalNumber:"{value}{suffix}",OrdinalSuffixes:{few:"rd",many:"th",one:"st",other:"th",two:"nd",zero:"th"},OrphanedSpellsHeader:"Orphaned Spells (move to spellcasting entry above)",OverridesTitle:"Overrides",Pathfinder:"Pathfinder",PFS:{CharacterNumber:"Character #",CurrentFaction:"Current Faction",Factions:{EA:"Envoy's Alliance",GA:"Grand Archive",HH:"Horizon Hunters",RO:"Radiant Oath",VS:"Vigilant Seal",VW:"Verdant Wheel"},LevelBump:"Level Bump",OrganizedPlayNumber:"Organized Play #",Reputation:"Reputation",School:{None:"Field-Commissioned Agent",Scrolls:"Scrolls",Spells:"Spells",Swords:"Swords"}},PenaltyLabel:{ability:"Attribute Penalty",circumstance:"Circumstance Penalty",item:"Item Penalty",proficiency:"Proficiency Penalty",status:"Status Penalty",untyped:"Untyped Penalty"},PerceptionCheck:"Perception Check",PerceptionHeader:"Perception",PerceptionLabel:"Perception",PotencyRuneLabel:"Potency Rune",PreciousMaterialAbysium:"Abysium",PreciousMaterialAbysiumDescription:"A blue-green metal with an eerie green luminescence, abysium radiates power that's inimical to life. Careless exposure to the material can lead to long-term damage to the immune system; as such, mining abysium is hazardous, as large quantities of the metal in an area cause all nearby creatures to become sick. A creature carrying an abysium object is sickened 1 for a standard-grade object of light Bulk, sickened 2 for a standard-grade object of 1 Bulk or more or a high-grade object of light Bulk, or sickened 3 for a high-grade object of 1 Bulk or more. This and all other sickening effects of abysium are poison effects. Crafters can use 1 abysium chunk to create up to 6 doses of poisonous abysium powder. Unscrupulous smiths have harnessed abysium's toxic properties to create noxious weapons and deadly substances. All objects crafted from abysium shed dim light in a 10-foot radius.",PreciousMaterialAdamantine:"Adamantine",PreciousMaterialAdamantineDescription:"Mined from rocks that fell from the heavens, adamantine is one of the hardest metals known. It has a shiny, black appearance, and it is prized for its amazing resiliency and ability to hold an incredibly sharp edge.",PreciousMaterialColdIron:"Cold Iron",PreciousMaterialColdIronDescription:"Weapons made from cold iron are deadly to demons and fey alike. Cold iron looks like normal iron but is mined from particularly pure sources and shaped with little or no heat. This process is extremely difficult, especially for high-grade cold iron items.",PreciousMaterialDawnsilver:"Dawnsilver",PreciousMaterialDawnsilverDescription:"Dawnsilver is renowned for its lightness, durability, and effectiveness against a range of creatures including devils and lycanthropes. It has the same sheen as silver but a slightly lighter hue. Dawnsilver weapons and armor are treated as if they were silver for the purpose of damaging creatures with weakness to silver. A metal item made of dawnsilver is lighter than one made of iron or steel: the item's Bulk is reduced by 1 (reduced to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of this material is based on the item's normal Bulk, not its reduced Bulk for being made of dawnsilver, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialDjezet:"Djezet",PreciousMaterialDjezetDescription:'This rust red metal is liquid at room temperature, making it challenging for all but the most skilled metallurgists to craft with and earning it the name "quickiron" in some places. Djezet is also extremely reactive to magic, even in its solid, workable alloyed form. It glows when targeted by magic, and objects crafted with djezet alloys glow with scarlet striations, which lead some smiths to nickname it "tiger iron." When targeted by spells, objects crafted from djezet alloys exhibit these glowing red markings that last for 1 round or the duration of the spell, whichever is longer. A djezet mass contains enough djezet to refine into up to two djezet doses.',PreciousMaterialDragonhide:"Dragonhide",PreciousMaterialDragonhideDescription:"The hide and scales of a dragon can be used to Craft any item normally made of ordinary leather or hide. Dragonhide varies in color from blue to glittering gold, depending on the dragon it came from. Due to the scales' resiliency, it can also be used to Craft armor usually made out of metal plates (such as a breastplate, half plate, and full plate), allowing such armor to be made without metal. Dragonhide objects are immune to one damage type, depending on the type of dragon.",PreciousMaterialDuskwood:"Duskwood",PreciousMaterialDuskwoodDescription:"Duskwood is a very lightweight wood found primarily in old- growth forests in south-central Avistan; it is dark as ebony but has a slight purple tint. A duskwood item's Bulk is reduced by 1 (or to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of duskwood is based on the item's normal Bulk, not its reduced Bulk for being made of duskwood, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialGradeLabel:"Precious Material Grade",PreciousMaterialGrisantianPelt:"Grisantian Pelt",PreciousMaterialGrisantianPeltDescription:"This supernaturally tough animal skin is gold and shines in sunlight. It can be used to make any item usually made of cloth, leather, or hide. This material is immune to fire, and its Hardness is doubled against piercing or slashing damage. Up to 4 Bulk of grisantian pelt can be harvested from a single creature (this is usually more than enough for 4 suits of standard grade armor or 2 suit of high-grade armor).",PreciousMaterialHighGrade:"High-Grade",PreciousMaterialInubrix:"Inubrix",PreciousMaterialInubrixDescription:"This pale, malleable metal's unusual molecular structure allows it to partially pass through iron and steel without touching them. While this property is useful for making weapons that bypass metal armor, inubrix is barely sturdier than lead. Even in an alloyed state, this skymetal is so fragile that it's difficult to use in crafting reliable shields and less than ideal for crafting armor.",PreciousMaterialLabel:"Precious Material",PreciousMaterialLowGrade:"Low-Grade",PreciousMaterialKeepStone:"Keep Stone",PreciousMaterialKeepStoneDescription:"The crowning achievement of Highhelm's millennia of metallurgical advancements and engineering is the beautiful alloy called keep stone. Despite its name, no stone is used in the production of keep stone. Through the use of a highly guarded process that smelts together adamantine and lead, Highhelm's greatest crafters were able to develop a material with an appearance that more closely resembles marble than metal. Keep stone is only slightly weaker than adamantine alone, but with the incredible ability to disrupt magic. Any spell or magical effect targeting raw keep stone must succeed at a DC 5 flat check or the effect is lost.",PreciousMaterialNoqual:"Noqual",PreciousMaterialNoqualDescription:"Light and strong, noqual also demonstrates a powerful resistance to magic. A side effect of this resistance is that making magical weapons out of noqual requires complex and expensive alchemical treatments. Kevoth-Kul, the Black Sovereign of Numeria, has developed an alloy of noqual and cold iron known as sovereign steel to help mitigate this property. The metal's crystalline appearance might suggest that it's fragile, but the pale-green material can be worked similarly to iron. Objects made of noqual have a +4 circumstance bonus on saves against magic that the item attempts and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialOrichalcum:"Orichalcum",PreciousMaterialOrichalcumDescription:"The most rare and valuable skymetal, orichalcum is coveted for its incredible time-related magical properties. This dull, coppery metal isn't as physically sturdy as adamantine, but orichalcum's time-bending properties protect it, granting it greater Hardness and Hit Points. If an orichalcum item takes damage but isn't destroyed, it repairs itself completely 24 hours later.",PreciousMaterialPeachwood:"Peachwood",PreciousMaterialPeachwoodDescription:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",PreciousMaterialSiccatite:"Siccatite",PreciousMaterialSiccatiteDescription:"In its raw state, this silvery ore is either scalding hot or freezing cold. Metallurgists disagree over whether siccatite is two related substances or one substance that determines its temperature output via some unknown process. Whatever the reason, the extreme temperature of the material means it must be handled carefully. Hot siccatite can easily ignite flammables such as paper and dry brush, and cold siccatite left in moist areas quickly surrounds itself with a thick layer of ice. A creature that comes into physical contact with a significant amount of siccatite takes 1 energy Damage for each round of continued contact (either fire or cold damage, for hot and cold siccatite respectively).",PreciousMaterialSilver:"Silver",PreciousMaterialSilverDescription:"Silver weapons are a bane to creatures ranging from devils to werewolves. Silver items are less durable than steel items, and low-grade silver items are usually merely silver-plated.",PreciousMaterialSisterstone:"Sisterstone",PreciousMaterialSisterstoneDescription:"Sisterstone is a term used for two closely related ores infused by the spiritual runoff in the Field of Maidens, dusk sisterstone and scarlet sisterstone. They have the same physical properties except for color-dusk sisterstone is a pale orange while scarlet sisterstone is orange-red. When near an object made of the other type of sisterstone, they both begin exuding spiritual energy that repels undead.",PreciousMaterialSisterstoneDusk:"Sisterstone (Dusk)",PreciousMaterialSisterstoneScarlet:"Sisterstone (Scarlet)",PreciousMaterialSovereignSteel:"Sovereign Steel",PreciousMaterialSovereignSteelDescription:"Created by Black Sovereign Kevoth-Kul, this unique alloy of cold iron and the skymetal noqual can provide protection from magical assault. The process of cold-forging the two materials together is quite complicated and precise. Characters in search of sovereign steel weapons and armor will almost assuredly have to travel to Starfall to procure gear made from this rare alloy. While some believe it possible to craft shields of sovereign steel as well, in one of his fits, Kevoth-Kul yelled that he had no use for them and banned anyone from making such a thing. So far, his smiths have been too afraid to confirm whether or not it was a joke. All sovereign steel items (including weapon and armor below) have a +4 circumstance bonus on saves against magic that the item makes, and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialStandardGrade:"Standard-Grade",PreciousMaterialWarpglass:"Warpglass",PreciousMaterialWarpglassDescription:"This bizarre substance is fashioned from the raw, chaotic quintessence of the Maelstrom. It can be fashioned into weapons and items, but is too unstable to make into useful armor or shields. Raw warpglass is an opalescent glassy material with surprising strength. When worked, it changes its appearance-though not its properties-to appear as random striations of other metals and types of stone.",PreparationTypeInnate:"Innate",PreparationTypeItems:"Items Only",PreparationTypePrepared:"Prepared",PreparationTypeSpontaneous:"Spontaneous",Prerequisite1:"Prerequisite 1",Prerequisite2:"Prerequisite 2",Prerequisite3:"Prerequisite 3",Prerequisite4:"Prerequisite 4",Prerequisite5:"Prerequisite 5",PriceLabel:"Price",ProficiencyLabel:"Proficiency",ProficiencyLevel0:"Untrained",ProficiencyLevel1:"Trained",ProficiencyLevel2:"Expert",ProficiencyLevel3:"Master",ProficiencyLevel4:"Legendary",ProficiencyRankLabel:"Prof",ProgressBar:{LoadingComplete:"Loading complete",LoadingPack:"Loading {pack}"},PropertyRuneLabel1:"Property Rune (1st)",PropertyRuneLabel2:"Property Rune (2nd)",PropertyRuneLabel3:"Property Rune (3rd)",PropertyRuneLabel4:"Property Rune (4th)",Publication:{Authors:"Author(s)",Label:"Publication",License:{Label:"License",OGL:"OGL",ORC:"ORC"},Remaster:"Remaster?",Title:"Title"},QuantityLabel:"Quantity",QuantityShortLabel:"Qty.",RangePenalty:"Range Penalty",Rarity:"Rarity",Reach:"Reach (feet)",RecallKnowledge:{Breakdown:"Attempts",BreakdownTitle:"Identify Creature Attempts",FifthAttempt:"5th DC",FirstAttempt:"1st DC",FourthAttempt:"4th DC",Help:"You can attempt repeated Recall Knowledge actions to recall more information about a creature. These checks increase in difficulty as shown in the chart below. However, if you fail, or if no DC is listed, you can not attempt further Recall Knowledge checks against this creature.",Label:"Recall Knowledge",LoreEasy:"Applicable Lore (Easy)",LoreVeryEasy:"Applicable Lore (Very Easy)",SecondAttempt:"2nd DC",SixthAttempt:"6th DC",Skill:"Skill",ThirdAttempt:"3rd DC"},Recovery:{critFailure:"Increase your dying value by 2.",critSuccess:"Reduce your dying value by 2.",failure:"Increase your dying value by 1.",rollingDescription:"DC {dc} (Dying {dying})",success:"Reduce your dying value by 1."},RemoveCoinsByValueLabel:"Remove value, not specific type",RemoveCoinsTitle:"Remove Coins",RemoveCombatProficiency:{Message:"Remove {proficiency} proficiency?",Title:"Remove Combat Proficiency"},RemoveModifierTitle:"Remove Modifier",RemoveSpellcastingEntryTitle:"Remove Spellcasting Entry",RepairItemTitle:"Attempt to Repair Item",Repost:"Post prompt to chat",RerollMenu:{ErrorCantDelete:"You are unable to delete the original roll.",ErrorNoActor:"No actor is associated to the roll",HeroPoint:"Reroll using a Hero Point",KeepHigher:"Reroll and keep the higher result",KeepNew:"Reroll and keep the new result",KeepLower:"Reroll and keep the lower result",MessageHeroPoint:"Rerolled using a Hero Point",MessageKeep:{higher:"Rerolled and kept the higher result",new:"Rerolled and kept the new result",lower:"Rerolled and kept the lower result"},WarnNoHeroPoint:"{name} has no Hero Points"},ResistancesLabel:"Resistances",ResolvePointsShortLabel:"Resolve",RestoreSpellTitle:"Restore Spell",RevertDamage:{ButtonTooltip:"Undo",DamageMessage:"Damage applied to {actor} was reverted.",HealingMessage:"Healing applied to {actor} was reverted."},Roll:{Add:"Add",CriticalHit:"Critical Hit",Dialog:{Check:{Substitution:"Substitution",Utilize:"Utilize?"},Damage:{BaseDamage:"Base Damage",Dice:"{dice} Dice",DiceHeader:"Dice",DieSizeUpgrade:"Upgrade Die Size",ExtraDice:"Extra {dice}",Label:"Label",None:"None",Override:"Override {value}",Splash:"{damageType} Splash",TitleCritical:"Critical Damage Roll",Title:"Damage Roll"},ShowDefault:"Always Show Dialog",ShowDefaultHint:"If enabled, this dialog is always shown unless you hold Shift. If disabled, you can open this dialog by holding Shift."},Fortune:"Fortune",FortuneTitle:"{title} Fortune",KeepHigher:"Keep Higher",KeepLower:"Keep Lower",Misfortune:"Misfortune",MisfortuneTitle:"{title} Misfortune",Modifier:"Modifier",None:"None",Normal:"Normal",Roll:"Roll",Type:"Type",UntypedPenalty:"Untyped (penalty)"},RollBonusPlaceholder:"e.g. +3 or +1d4",RollModeLabel:"Roll Mode",RollTable:{Plural:"Rollable Tables"},SETTINGS:{Automation:{ActorsDeadAtZero:{Both:"Yes",Hint:"Upon reaching zero hit points, actors are marked as dead. For PCs, this only applies to damage that would immediately kill them.",NPCsOnly:"NPCS only",Name:"Actors Dead at 0 HP",Neither:"No"},Encumbrance:{Hint:"Automatically apply the Encumbered condition to creatures carrying more than their respective limits.",Name:"Encumbrance"},EffectExpiration:{Hint:"Effects automatically disable attached rule elements when the duration expires.",Name:"Effects Auto-Expire"},FlankingDetection:{Hint:"Flanking arrangements and abilities that predicate on it are managed by the system.",Name:"Flanking Detection"},Hint:"Decide how much and what kinds of automation should apply to your game world.",IWR:{Hint:"When applying damage to an actor, adjust its value according to the actor's immunities, weaknesses, and resistances.",Name:"Immunities, Weaknesses, & Resistances"},Label:"Manage Automation",LootableNPCs:{Hint:"Upon their demise, NPCs become lootable by players.",Name:"Lootable NPCs"},Name:"Automation",RemoveExpiredEffects:{Hint:"Expired effects are automatically removed from actors (requires a GM to be logged in).",Name:"Remove Expired Effects"},RulesBasedVision:{Hint:"Apply vision mechanics that are a best-effort attempt to capture Pathfinder Second Edition rules. Enabling this setting will remove the ability to configure Unrestricted Global Vision as well as Token Sight radii.",ManagedBy:"Managed by <rbv>rules-based vision</rbv>.",Name:"Rules-Based Vision",ViewWorldSetting:"View World Setting"}},CampaignFeats:{Hint:"Adds a section to all player sheets for campaign specific feats.",Name:"Campaign Feats"},CampaignType:{Hint:"Extended campaign rule type for parties",Name:"Campaign Type",Choices:{none:"None",kingmaker:"Kingmaker"}},CompendiumBrowserPacks:{Hint:"Settings to exclude packs from loading",Name:"Compendium Browser Packs"},CompendiumBrowserSources:{DeleteAllInfo:"All compendium documents will become browseable, including those with empty sources.",DeleteAllQuestion:"Are you sure you want to reset all settings for included sources?",DeleteAllTitle:"Reset Settings",Hint:"Settings to display only entries with specified sources in the compendium browser.",IgnoreAsGM:"Let GMs ignore filtering and see all entries.",Name:"Included Sources",ShowEmptySources:"Do not filter entries with empty sources.",ShowUnknownSources:"Do not filter entries with unknown sources.",SourcesListHeader:"Specified Sources"},CritRule:{Choices:{Doubledamage:"Double the damage",Doubledice:"Double the number of dice"},Hint:"Use a different rule for doubling damage on a critical hit",Name:"Critical Damage Rule"},DeathIcon:{Hint:"Set the overlay icon used to mark dead actors.",Name:"Death Icon"},EnabledDisabled:{Enabled:"Enabled",Default:"World Default ({worldDefault})",Disabled:"Disabled"},EnabledRulesUI:{Hint:"When enabled, players are able to see and utilize the rule elements panel on item sheets.",Name:"Player Rule Elements Access"},Homebrew:{BaseWeapons:{Hint:"The bottom level of Pathfinder 2e weapon taxonomy (e.g, Heavy Crossbow, Longsword)",Name:"Base Weapons"},ConfirmDelete:{Message:"Delete Homebrew element <strong>{element}</strong>?",Title:"Delete Homebrew Element?"},CreatureTraits:{Hint:"Traits that can be applied to any creature and some item types (e.g., Dragon, Gnome)",Name:"Creature Traits"},DamageTypes:{Add:"Add Damage Type",Hint:"Additional damage types for the system to recognize",Icon:"Icon (Font Awesome)",Name:"Custom Damage Types",Label:"Label"},EquipmentTraits:{Hint:"Traits applicable to equipment other than weapons",Name:"Equipment Traits"},FeatTraits:{Hint:"Traits that can be applied to feats (e.g., Lineage, Monk) and actions",Name:"Feat Traits"},Hint:"Add custom traits, languages, and other elements of a homebrew world.",Instructions:"These settings allow GMs to add traits, languages, and other elements to a homebrew world. To add such elements, simply type the desired terms in the appropriate fields, separated by commas or tab keystrokes. They will then appear in the appropriate places on actor and item sheets. To update a term, click it to make the desired changes.",Label:"Manage Homebrew Elements",Languages:{Hint:"Languages for characters to know or learn (e.g., Draconic, Gnomish)",Name:"Languages"},Name:"Homebrew Elements",ReservedTerm:'"{term}" is a reserved term.',SpellTraits:{Hint:"Traits that can be applied to any spell (e.g., Cursebound, Healing)",Name:"Spell Traits"},Tabs:{Damage:"Damage Types",Traits:"Traits and Categories"},WeaponCategories:{Hint:"The top level of Pathfinder 2e weapon taxonomy (e.g., Simple, Martial)",Name:"Weapon Categories"},WeaponGroups:{Hint:"The mid level of Pathfinder 2e weapon taxonomy (e.g, Crossbow, Sword)",Name:"Weapon Groups"},WeaponTraits:{Hint:"Traits applicable to weapons and NPC attacks",Name:"Weapon Traits"}},IdentifyMagicNotMatchingTraditionModifier:{Choices:{0:"0",2:"+2",5:"+5",10:"+10"},Hint:"Modifier to add to Identify Magic Skill DCs if the skill does not match the item's magic tradition",Name:"Identify Magic Skill Modifier"},Metagame:{Hint:"Limit what kinds of metagame information your players have access to.",Label:"Limit Metagame Information",Name:"Metagame Information",PartyVision:{Hint:"If enabled, all players will mutually share token vision, regardless of permissions or token selection.",Name:"Shared Party Vision"},SecretCondition:{Hint:"If enabled, only the GM will see the condition update and reminder messages that are generated for tokens not owned by a player.",Name:"Hide Condition Update Message"},SecretDamage:{Hint:"If enabled, only the GM will see the damage/healing taken messages that are generated by the damage chat cards for tokens not owned by a player.",Name:"Hide Damage-Taken Message"},ShowDC:{Hint:"If enabled, players will see DCs of checks made against NPCs and other non-player-owned sources.",Name:"Show DCs on Attacks and Saves"},ShowResults:{Hint:"If enabled, players will see the degree of success of checks made against NPCs and other non-player-owned sources.",Name:"Show Results on Attacks and Saves"},ShowPartyStats:{Hint:"If enabled, players will see stats for their fellow party members in the party actor sheet",Name:"Show Party-Member Stats"},TokenSetsNameVisibility:{Hint:"If enabled, then for any NPC token whose nameplate isn't visible to players, its name will also be hidden from them in the encounter tracker and chat messages.",Name:"Tokens Determine NPC Name Visibility"}},NathMode:{Hint:"Use better default token icons",Name:"Nath Mode"},ResetChanges:"Reset Changes",Settings:"Settings",Sidebar:{Changelog:"Changelog",Discord:"Discord",Remaster:"Remaster Changes",Wiki:"Wiki"},TOTMToggles:{Hint:"Include additional toggles on actor sheets to facilitate Theater of the Mind play. Such toggles will allow for enabling certain abilities without targeting in Foundry.",Name:"Theater of the Mind Toggles"},Tokens:{Autoscale:{Hint:"If enabled, tokens will be scaled to 1.0 or (if belonging to a small creature) 0.8",Name:"Scale Tokens According to Size"}},User:{EffectPanel:{Hint:"Show the Effects Panel when a token is selected.",Name:"Show Effects Panel"},MonochromeDarkvision:{Hint:"If rules-based vision is enabled, depict areas of darkness in monochrome for tokens with darkvision. Note that some creatures, such as fetchlings, possess full-color darkvision and will not be affected.",Name:"Monochrome Darkvision"}},Variant:{GradualBoosts:{Hint:"Spread out attribute boosts across multiple levels. Players gain a boost every level except 6, 11, and 16.",Name:"Gradual Attribute Boosts"},AutomaticBonus:{Choices:{ABPFundamentalPotency:"ABP: Allow Property Runes",ABPRulesAsWritten:"ABP: Disallow Property Runes",noABP:"Do not use ABP"},Hint:"Enable the Automatic Bonus Progression variant rule. Skill potency must currently be managed manually.",Name:"Automatic Bonus Progression"},FreeArchetype:{Hint:"Grant additional feat slots for the free archetype variant from Gamemastery Guide pg 194",Name:"Free Archetype"},Hint:"Enable and configure variant rules like Proficiency Without Level or the Stamina system.",Label:"Toggle Variant Rules",Name:"Variant Rules",Proficiency:{Hint:"Play with the proficiency without level variant from Gamemastery Guide pg 198.",ModifiersHint:"Set the modifier value for each proficiency rank.",Name:"Proficiency without Level"},Stamina:{Hint:"Play with the stamina variant from Gamemastery Guide pg 200.",Name:"Stamina"},Title:"Variant Rules"},WorldClock:{DateTheme:{AD:"Earth (Gregorian Calendar)",AR:"Golarion (Absalom Reckoning)",CE:"Unthemed (Gregorian Calendar)",Hint:"Set the theme of the World Clock application.",IC:"Golarion (Imperial Calendar)",Name:"Date Theme"},Hint:"Configure the appearance of the World Clock application.",Label:"Configure World Clock",Name:"World Clock",PlayersCanView:{Hint:"Set whether players can view the World Clock.",Name:"Player Access"},ResetWorldTime:{Button:"Reset",Confirm:{Question:"Are you sure you want to reset this world's elapsed time?",Warning1:"Time-dependent game effects may be impacted.",Warning2:"This action cannot be undone."},Hint:"Reset this world's time elapsed time to zero.",Name:"Reset World Date/Time"},ShowClockButton:{Hint:"Set whether to show the clock button at all (requires refresh).",Name:"Show Clock Button"},SyncDarkness:{Hint:"Set whether any scene's Darkness Level will reflect the time of day.",Name:"Synchronize Darkness (World Default)"},SyncDarknessScene:{Hint:"Set whether this scene's Darkness Level will reflect the time of day.",ManagedBy:"Synchronized with <wt>world time</wt>.",Name:"Synchronize Darkness (Current Scene)"},TimeConvention:{Hint:"Display either a 24-hour or 12-hour clock.",Name:"Time Convention",Twelve:"12-Hour",TwentyFour:"24-Hour"}},WorldSchemaVersion:{Hint:"Records the schema version for documents in the PF2e system (don't modify this unless you know what you are doing).",Name:"World Schema Version"},critFumbleCardButtons:{hint:"Show critical hit and fumble card draw buttons on attack rolls.",name:"Critical Hit & Fumble Card Buttons"},critFumbleCards:{hint:"Automatically draw a critical hit or fumble card on appropriate rolls.",name:"Critical Hit & Fumble Cards"},statusEffectShowCombatMessage:{hint:"Each turn of an encounter, send a chat message containing the conditions of the turn's participant.",name:"Show Conditions during Encounters"},statusEffectType:{blackWhite:"Black & white",default:"Full color",hint:"Determines which icon set is used for condition token effects.",legacy:"Legacy",name:"Condition Icon Set"}},SaveDCLabel:"Save <dc>DC {dc}</dc> {type}",SaveDCLabelBasic:"Save <dc>DC {dc}</dc> basic {type}",SavesFortitude:"Fortitude",SavesFortitudeShort:"Fort",SavesHeader:"Saves",SavesReflex:"Reflex",SavesReflexShort:"Ref",SavesWill:"Will",SavesWillShort:"Will",SavingThrow:"Saving Throw",SavingThrowWithName:"{saveName} Saving Throw",Scene:{HearingRange:{Caveat:"*For performance reasons, the radius is a real measurement rather than a grid-based one.",Hint:'Limit the range* creatures can hear in this scene as a representation of "an environment that distorts the sense, such as a noisy room" (CRB pg. 464). Requires rules-based vision to be enabled.',Name:"Hearing Range (ft.)",Unlimited:"Unlimited"}},ScoreTitle:"Score",SelectLabel:"Select",SellAllTreasureQuestion:"Convert all treasure items into coins",SellAllTreasureTitle:"Sell All Treasure",SellItemConfirmHeader:"Sell Confirmation",SellItemQuestion:"Are you sure you want to sell {item}?",Senses:"Senses",SettingsQuickChecksLabel:"Preview D20 Rolls",SettingsQuickChecksNotes:"If disabled, dialogs to preview D20 rolls will appear only when a roll button is shift-clicked.",SettingsQuickDamageLabel:"Preview Damage Rolls",SettingsQuickDamageNotes:"If disabled, dialogs to preview Damage rolls will appear only when a roll button is shift-clicked.",SheetLabel:"{type} Sheet",ShieldLabel:"Shield",SidebarAppearanceLabel:"Appearance",Size:"Size",SizeLabel:"Size",SkillAcr:"Acrobatics",SkillAcrobatics:"Acrobatics",SkillArc:"Arcana",SkillArcana:"Arcana",SkillAth:"Athletics",SkillAthletics:"Athletics",SkillCheckWithName:"Skill Check: {skillName}",SkillCra:"Crafting",SkillCrafting:"Crafting",SkillDec:"Deception",SkillDeception:"Deception",SkillDip:"Diplomacy",SkillDiplomacy:"Diplomacy",SkillFeatLevels:"Skill Feat Levels",SkillIncreaseLevels:"Skill Increase Levels",SkillIntimidation:"Intimidation",SkillItm:"Intimidation",SkillLabel:"Skill",SkillLore:"Lore",SkillMed:"Medicine",SkillMedicine:"Medicine",SkillNat:"Nature",SkillNature:"Nature",SkillOcc:"Occultism",SkillOccultism:"Occultism",SkillPerformance:"Performance",SkillPotencyHeader:"Skill Potencies",SkillPrf:"Performance",SkillRel:"Religion",SkillReligion:"Religion",SkillSoc:"Society",SkillSociety:"Society",SkillSte:"Stealth",SkillStealth:"Stealth",SkillSur:"Survival",SkillSurvival:"Survival",SkillThi:"Thievery",SkillThievery:"Thievery",SkillsLabel:"Skills",Slug:"Slug",SpecialLabel:"Special",SpecialSensesLabel:"Special Senses",Speed:"Speed",SpeedBaseLabel:"Base {type} Speed",SpeedFeet:"Speed (feet)",SpeedLabel:"{type} Speed",SpeedTypes:"Speed Types",SpeedTypesBurrow:"Burrow",SpeedTypesClimb:"Climb",SpeedTypesFly:"Fly",SpeedTypesLand:"Land",SpeedTypesSwim:"Swim",SpellAbilityModLabel:"+ Mod",SpellArea:"Area: {area}",SpellAttackLabel:"Spell Attack",SpellAttackWithTradition:"{tradition} Spell Attack",SpellBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:<br> source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. <br>Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",SpellCastingFormat:"{traditionSpells} {preparationType} Spells",SpellCollectionAdd:"Add to Spell Collection",SpellCollectionRemove:"Remove from Spell Collection",SpellDurationLabel:"Duration",SpellFlexibleAvailable:"Flexible: {value} / {max}",SpellFlexibleLabel:"Flexible",SpellFocusLabel:"Focus",SpellLevelBase:"Base: {level}",SpellLevelHeightened:"Heightened: +{heightened}",SpellLevelLabel:"Spell Rank",SpellPreparedLabel:"Prepared",SpellRangeLabel:"Range",SpellRequirementsLabel:"Requirements",SpellScalingInterval:{Add:"Add Heightening (Interval)",Header:"Scaling (Interval)",Label:"Interval",Selection:"Heightened (+{interval})"},SpellScalingLabel:"Scaling",SpellScalingOverlay:{Add:"Add Heightening (Fixed)",Selection:"Heightened ({level})"},SpellSlotEmpty:"Empty Slot (drag spell here)",SpellSlotExpendedError:"Cannot cast {name}: spell is already expended",SpellSlotNotEnoughError:"Cannot cast {name} at the {level}: not enough spell slots",SpellTargetLabel:"Targets",SpellTraditionsLabel:"Traditions",SpellUnlimitedLabel:"Unlimited",SpellUsesLabel:"Uses",SpellcastingSettings:{AutoHeightenDefault:"Default (Use Actor Level)",AutoHeightenLabel:"Auto Heighten Rank",Title:"Spellcasting Settings"},SpellcastingTypeLabel:"Spellcasting Type",SpellsActionHeader:"Action",StackGroupArrows:"Arrows",StackGroupBlowgunDarts:"Blowgun Darts",StackGroupBolts:"Bolts",StackGroupCoins:"Coins",StackGroupGems:"Gems",StackGroupLabel:"Stack Group",StackGroupRounds10:"Rounds (10)",StackGroupRounds5:"Rounds (5)",StackGroupSlingBullets:"Sling Bullets",StackGroupSprayPellets:"Spray Pellets",StackGroupWoodenTaws:"Wooden Taws",StaminaPointsHeader:"Stamina Points",StaminaPointsShortLabel:"Stamina",StatusBonusShortLabel:"Status",StatusBonusTitle:"Status Bonus",StatusEffects:"{name}'s conditions",StealthLabel:"Stealth",Strike:{Combined:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Default:{CriticalSuccess:"As success, but you deal double damage.",Description:"You attack with a weapon you're wielding or with an unarmed attack, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon or unarmed attack, including any modifiers, bonuses, and penalties you have to damage."},Fist:{Label:"Fist"},Melee:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Ranged:{Description:"You attack with a weapon you're wielding, targeting one creature within range. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",NoAmmo:"No ammunition is assigned to {weapon}. Check the Actions tab of {actor}'s sheet.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Unarmed:{Description:"You attack with an unarmed attack, targeting one creature within your reach. Roll the attack roll for the unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the unarmed attack, including any modifiers, bonuses, and penalties you have to damage."}},StrikesLabel:"Strikes",StrikingRuneLabel:"Striking Rune",Success:"<strong>Success</strong>",TabActionsDowntimeLabel:"Downtime",TabActionsEncounterLabel:"Encounter",TabActionsExplorationLabel:"Exploration",TabActionsLabel:"Actions",TabCharacterLabel:"Character",TabCraftingLabel:"Crafting",TabDescriptionLabel:"Description",TabDetailsLabel:"Details",TabInventoryLabel:"Inventory",TabManageTabsLabel:"Manage Tabs",TabPathfinderSociety:"Pathfinder Society",TabSkillsLabel:"Proficiencies",TabSpellbookLabel:"Spellcasting",TempHitPointsShortLabel:"Temp HP",TemplateLabel:"{size}-{unit} {shape}",TemporaryItemToolTip:"This item is temporary and will expire after a duration or during daily preparations. It has no value and cannot be sold.",Time:{Duration:"Duration",Unit:{Days:"Days",Hours:"Hours",Minutes:"Minutes",Rounds:"Rounds",Seconds:"Seconds",Unlimited:"Unlimited",UntilEncounterEnds:"Until encounter ends",Weeks:"Weeks"}},ToggleEffectUnidentified:"Toggle Whether Effect Is Unidentified",ToggleSignatureSpellTitle:"Toggle Signature Spell",ToggleSlotlessSpellLevelsTitle:"Toggle visibility of spell ranks without slots",ToggleSpellVisibilityTitle:"Spell Preparation",ToggleUnreadyStrikes:"Toggle unequipped weapons",ToggleWithName:"Toggle: {property}",TogglesLabel:"Toggles",Token:{Appearance:"Appearance",Flanking:"Flanking",SecretDisposition:{Label:"Secret Disposition",Hint:'Activate the "secret" disposition, which displays a purple border for owners and no border or cursor change for all others.'},Size:{Dimensions:"Dimensions",Label:"Size",LinkToActorSize:{Link:"Link to Actor Size",Unlink:"Unlink from Actor Size"}}},TotalCoinage:"Total Coinage",TotalTreasure:"Total Treasure",TotalWealth:"Total Wealth",TrainedSkillsLabel:"Trained Skills",TraitAberration:"Aberration",TraitAcid:"Acid",TraitAdditive0:"Additive 0",TraitAdditive1:"Additive 1",TraitAdditive2:"Additive 2",TraitAdditive3:"Additive 3",TraitAdjusted:"Adjusted",TraitAdjustment:"Adjustment",TraitAeon:"Aeon",TraitAesir:"Aesir",TraitAffixedToAMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToARangedWeapon:"Affixed to a Ranged Weapon",TraitAffixedToAShield:"Affixed to a Shield",TraitAffixedToAShieldOrWeapon:"Affixed to a Shield or Weapon",TraitAffixedToATwoHandedFirearmOrCrossbow:"Affixed to a Two-Handed Firearm or Crossbow",TraitAffixedToArmor:"Affixed to Armor",TraitAffixedToArmorOrAWeapon:"Affixed to Armor or a Weapon",TraitAffixedToArmorOrTravelersClothing:"Affixed to Armor or Travelers Clothing",TraitAffixedToCreature:"Affixed to a Creature",TraitAffixedToCrossbowOrFirearm:"Affixed to Crossbow or Firearm",TraitAffixedToFirearm:"Affixed to Firearm",TraitAffixedToFirearmWithAReloadOf1:"Affixed to a Firearm With a Reload of 1",TraitAffixedToFirearmWithTheKickbackTrait:"Affixed to a Firearm With the Kickback Trait",TraitAffixedToGround:"Affixed to the Ground",TraitAffixedToGroundIn10FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 10-foot Radius",TraitAffixedToGroundIn20FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 20-foot Radius",TraitAffixedToHarness:"Affixed to Harness",TraitAffixedToHeadgear:"Affixed to Headgear",TraitAffixedToInnovation:"Affixed to an Innovation",TraitAffixedToInstrument:"Affixed to Instrument",TraitAffixedToLoadBearingWallOrPillar:"Affixed to a Load-Bearing Wall or Pillar",TraitAffixedToMagicalStaff:"Affixed to a Magical Staff",TraitAffixedToMediumHeavyArmor:"Affixed to Medium or Heavy Armor",TraitAffixedToMediumHeavyMetalArmor:"Affixed to Medium or Heavy Metal Armor",TraitAffixedToMeleeWeapon:"Affixed to a Melee Weapon",TraitAffixedToMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToObjectOrStructure:"Affixed to an Object or Structure",TraitAffixedToStructureObjectOrCreature:"Affixed to Structure, Object, or Creature",TraitAffixedToThrownWeapon:"Affixed to a Thrown Weapon",TraitAffixedToUnarmoredItem:"Affixed to Unarmored Defense Item",TraitAffixedToWeapon:"Affixed to a Weapon",TraitAftermath:"Aftermath",TraitAgathion:"Agathion",TraitAgile:"Agile",TraitAir:"Air",TraitAiuvarin:"Aiuvarin",TraitAlchemical:"Alchemical",TraitAlchemist:"Alchemist",TraitAmp:"Amp",TraitAmphibious:"Amphibious",TraitAnadi:"Anadi",TraitAndroid:"Android",TraitAngel:"Angel",TraitAnimal:"Animal",TraitAnugobu:"Anugobu",TraitApex:"Apex",TraitAphorite:"Aphorite",TraitAppliedToANoninjectionMeleePiercingWeapon:"Applied to a non-injection melee weapon that deals piercing damage",TraitAppliedToAWindPoweredVehicle:"Applied to a wind-powered vehicle",TraitAppliedToAWeapon:"Applied to a weapon",TraitAppliedToAnyItemOfLightOrNegligibleBulk:"Applied to any item of light or negligible Bulk",TraitAppliedToAnyVisibleArticleOfClothing:"Applied to any visible article of clothing",TraitAppliedToArmor:"Applied to armor",TraitAppliedToArmorOrUnarmored:"Applied to armor or unarmored defense clothing",TraitAppliedToBasketBagOrContainer:"Applied to a Basket, Bag, or Other Container",TraitAppliedToBeltCapeCloakOrScarf:"Applied to belt, cape, cloak, or scarf",TraitAppliedToBootsCapeCloakOrUmbrella:"Applied to boots, cape, cloak, or umbrella",TraitAppliedToBucklerShield:"Applied to a buckler or a shield",TraitAppliedToDuelingCapeOrShield:"Applied to dueling cape or shield",TraitAppliedToFootwear:"Applied to Footwear",TraitAppliedToMediumHeavyArmor:"Applied to Medium or Heavy Armor",TraitAppliedToShield:"Applied to shield",TraitAquadynamic:"Aquadynamic",TraitAquatic:"Aquatic",TraitArcane:"Arcane",TraitArchetype:"Archetype",TraitArchon:"Archon",TraitArdande:"Ardande",TraitAreaDamage:"Area Damage",TraitArtifact:"Artifact",TraitAstral:"Astral",TraitAsura:"Asura",TraitAttached:"Attached",TraitAttachedToAThrownWeapon:"Attached to a Thrown Weapon",TraitAttachedToCrossbowOrFirearm:"Attached to Crossbow or Firearm",TraitAttachedToCrossbowOrFirearmFiringMechanism:"Attached to Crossbow or Firearm (Firing Mechanism)",TraitAttachedToCrossbowOrFirearmScope:"Attached to Crossbow or Firearm (Scope)",TraitAttachedToFirearm:"Attached To Firearm",TraitAttachedToFirearmFiringMechanism:"Attached To Firearm (Firing Mechanism)",TraitAttachedToFirearmScope:"Attached To Firearm (Scope)",TraitAttachedToShield:"Attached to Shield",TraitAttachedToShipsBow:"Attached to a Ship's Bow",TraitAttack:"Attack",TraitAuditory:"Auditory",TraitAura:"Aura",TraitAutomaton:"Automaton",TraitAzarketi:"Azarketi",TraitAzata:"Azata",TraitBackstabber:"Backstabber",TraitBackswing:"Backswing",TraitBarbarian:"Barbarian",TraitBard:"Bard",TraitBarding:"Barding",TraitBeast:"Beast",TraitBeastkin:"Beastkin",TraitBleed:"Bleed",TraitBludgeoning:"Bludgeoning",TraitBoggard:"Boggard",TraitBomb:"Bomb",TraitBonded:"Bonded",TraitBottledBreath:"Bottled Breath",TraitBrace:"Brace",TraitBrutal:"Brutal",TraitBulwark:"Bulwark",TraitCaligni:"Caligni",TraitCantrip:"Cantrip",TraitCapacity:"Capacity",TraitCapacity2:"Capacity 2",TraitCapacity3:"Capacity 3",TraitCapacity4:"Capacity 4",TraitCapacity5:"Capacity 5",TraitCarried:"Carried",TraitCatalyst:"Catalyst",TraitCatfolk:"Catfolk",TraitCelestial:"Celestial",TraitChampion:"Champion",TraitChangeling:"Changeling",TraitCharauKa:"Charau-ka",TraitCircus:"Circus",TraitCleric:"Cleric",TraitClimbing:"Climbing",TraitClockwork:"Clockwork",TraitCobbled:"Cobbled",TraitCoda:"Coda",TraitCold:"Cold",TraitColdiron:"Cold Iron",TraitCombination:"Combination",TraitComfort:"Comfort",TraitCommon:"Common",TraitCompanion:"Companion",TraitComplex:"Complex",TraitComposite:"Composite",TraitComposition:"Composition",TraitConcealable:"Concealable",TraitConcentrate:"Concentrate",TraitConcussive:"Concussive",TraitConfusion:"Confusion",TraitConrasu:"Conrasu",TraitConsecration:"Consecration",TraitConstruct:"Construct",TraitConsumable:"Consumable",TraitContact:"Contact",TraitContingency:"Contingency",TraitContract:"Contract",TraitCouatl:"Couatl",TraitCriticalFusion:"Critical Fusion",TraitCurse:"Curse",TraitCursebound:"Cursebound",TraitCursed:"Cursed",TraitDaemon:"Daemon",TraitDarkness:"Darkness",TraitDarvakka:"Darvakka",TraitDeadly:"Deadly",TraitDeadly2D10:"Deadly 2d10",TraitDeadly2D12:"Deadly 2d12",TraitDeadly2D8:"Deadly 2d8",TraitDeadly3D10:"Deadly 3d10",TraitDeadly3D12:"Deadly 3d12",TraitDeadly3D8:"Deadly 3d8",TraitDeadly4D10:"Deadly 4d10",TraitDeadly4D12:"Deadly 4d12",TraitDeadly4D8:"Deadly 4d8",TraitDeadlyD10:"Deadly d10",TraitDeadlyD12:"Deadly d12",TraitDeadlyD4:"Deadly d4",TraitDeadlyD6:"Deadly d6",TraitDeadlyD8:"Deadly d8",TraitDeath:"Death",TraitDedication:"Dedication",TraitDeflectingBludgeoning:"Deflecting Bludgeoning",TraitDeflectingPhysicalRanged:"Deflecting Physical Ranged",TraitDeflectingPiercing:"Deflecting Piercing",TraitDeflectingSlashing:"Deflecting Slashing",TraitDemon:"Demon",TraitDero:"Dero",TraitDescriptionAcid:"Effects with this trait deal acid damage. Creatures with this trait have a magical connection to acid.",TraitDescriptionAdditive:"Feats with the additive trait allow you to spend actions to add special substances to bombs or elixirs. You can add only one additive to a single alchemical item, and attempting to add another spoils the item. You can typically use actions with the additive trait only when you're creating an infused alchemical item, and some can be used only with the Quick Alchemy action. The additive trait is always followed by a level, such as additive 2. An additive adds its level to the level of the alchemical item you're modifying; the result is the new level of the mixture. The mixture's item level must be no higher than your advanced alchemy level",TraitDescriptionAdjusted:"The equipment comes with an adjustment described in its entry. This adjustment is built into the equipment permanently, meaning the equipment can't have another adjustment added, nor can it be swapped out for a different adjustment. If the adjustment alters the item's base statistics, such as adding the noisy trait, that's reflected in the equipment's table entry.",TraitDescriptionAdjustment:"Items with this trait are intended to alter existing pieces of equipment, typically armors, shields, and weapons. The given item will note which type of equipment it modifies. A piece of equipment can only be affected by a single adjustment at a time. Unless otherwise noted, adding or removing an adjustment requires using a 10-minute activity and a repair kit.",TraitDescriptionAeon:"These monitors are the self-styled defenders of reality. Traditional aeons have dualistic natures and forms, and they hold a dichotomy of interests, though axiomites and inevitables do not. Aeons other than axiomites and inevitables communicate via a strange telepathic hodgepodge of sensory sending called envisioning.",TraitDescriptionAesir:"Aesir are often-bellicose monitors of the chaotic planes, honing their skill in battle and preparing for a final confrontation at the end of the multiverse.",TraitDescriptionAftermath:"This trait describes feats that represent special abilities gained after exposure to the weird and deadly.",TraitDescriptionAgathion:"This family of animal-featured celestials is native to the plane of Nirvana. Most agathions are neutral good, have darkvision, and have a weakness to evil damage.",TraitDescriptionAgile:"The multiple attack penalty you take with this weapon on the second attack on your turn is -4 instead of -5, and -8 instead of -10 on the third and subsequent attacks in the turn.",TraitDescriptionAir:"Effects with the air trait either manipulate or conjure air. Those that manipulate air have no effect in a vacuum or an area without air. Creatures with this trait consist primarily of air or have a magical connection to that element.",TraitDescriptionAiuvarin:"A creature with this trait has the aiuvarin versatile heritage. Aiuvarins are of mixed ancestry, including elves or other aiuvarins. An ability with this trait can be used or selected only by aiuvarins.",TraitDescriptionAlchemical:"Alchemical items are powered by reactions of alchemical reagents. Alchemical items aren't magical and don't radiate a magical aura.",TraitDescriptionAlchemist:"This indicates abilities from the alchemist class.",TraitDescriptionAmp:"An amp is a special thoughtform that modifies the properties of your psi cantrips. Psi cantrips each have their own amp, and feats with the amp trait provide different amps you can apply to psi cantrips in place of their normal amps.",TraitDescriptionAmphibious:"An amphibious creature can breathe in water and in air, even outside of its preferred environment, usually indefinitely but at least for hours. These creatures often have a swim Speed. Their bludgeoning and slashing unarmed Strikes don't take the usual -2 penalty for being underwater.",TraitDescriptionAnadi:"A reclusive people from Garund who resemble spiders and can assume human forms.",TraitDescriptionAndroid:"A synthetic humanoid ancestry created by artificial means. Most common in Numeria.",TraitDescriptionApex:"When you Invest an Item that has the apex trait, it improves one of your attribute modifiers, either increasing it by 1 or to a total of +4, whichever grants the higher modifier. This gives you all the benefits of the new attribute modifier until the investiture ends. An apex item grants this benefit only the first time it's invested within a 24-hour period, and you can benefit from only one apex item at a time. If you attempt to invest an apex item when you already have one invested, you don't gain the attribute modifier increase, though you do gain any other effects of Investing the Item.",TraitDescriptionAphorite:"A type of planar scion descended from a being from Axis, the Plane of Law.",TraitDescriptionAquadynamic:"This armor is designed for use underwater, with streamlined design and buoyant materials used in strategic places. You don't apply the armor's check penalty to Acrobatics or Athletics checks in water or similar liquids.",TraitDescriptionArcane:"This magic comes from the arcane tradition, which is built on logic and rationality. Anything with this trait is magical.",TraitDescriptionArdande:"Ardandes are planar scions descended from kizidhars and other beings of elemental wood.",TraitDescriptionArchetype:"This feat belongs to an archetype.",TraitDescriptionArtifact:"Items with this trait are artifacts. These magic items can't be crafted by normal means, and they can't be damaged by normal means. Artifacts are always rare or unique.",TraitDescriptionAttached:"An attached weapon must be combined with another piece of gear to be used. The trait lists what type of item the weapon must be attached to. You must be wielding or wearing the item the weapon is attached to in order to attack with it. For example, shield spikes are attached to a shield, allowing you to attack with the spikes instead of a shield bash, but only if you're wielding the shield. An attached weapon is usually bolted onto or built into the item it's attached to, and typically an item can have only one weapon attached to it. An attached weapon can be affixed to an item with 10 minutes of work and a successful @Check[type:crafting|dc:10] check; this includes the time needed to remove the weapon from a previous item, if necessary. If an item is destroyed, its attached weapon can usually be salvaged.",TraitDescriptionAttack:"An ability with this trait involves an attack. For each attack you make beyond the first on your turn, you take a multiple attack penalty.",TraitDescriptionAuditory:"Auditory actions and effects rely on sound. An action with the auditory trait can be successfully performed only if the creature using the action can speak or otherwise produce the required sounds. A spell or effect with the auditory trait has its effect only if the target can hear it. This applies only to sound-based parts of the effect, as determined by the GM. This is different from a sonic effect, which still affects targets who can't hear it (such as deaf targets) as long as the effect itself makes sound.",TraitDescriptionAura:"An aura is an emanation that continually ebbs out from you, affecting creatures within a certain radius. Aura can also refer to the magical signature of an item or a creature with a strong alignment.",TraitDescriptionAutomaton:"A creature with this trait is a member of the automaton ancestry.",TraitDescriptionAzarketi:"Amphibious humanoids who live among the seas of the Inner Sea region, said to have descended from the people of Azlant. Sometimes known as gillmen or Low Azlanti.",TraitDescriptionBackstabber:"When you hit an off-guard creature, this weapon deals 1 precision damage in addition to its normal damage. The precision damage increases to 2 if the weapon is a +3 weapon.",TraitDescriptionBackswing:"You can use the momentum from a missed attack with this weapon to lead into your next attack. After missing with this weapon on your turn, you gain a +1 circumstance bonus to your next attack with this weapon before the end of your turn.",TraitDescriptionBarbarian:"This indicates abilities from the barbarian class.",TraitDescriptionBard:"This indicates abilities from the bard class.",TraitDescriptionBarding:"You can purchase special armor for animals, called barding. All animals have a trained proficiency rank in light barding, and combat-trained animals are trained in heavy barding. Barding uses the same rules as armor except for the following. The Price and Bulk of barding depend on the animal's size. Unlike for a suit of armor, barding's Strength entry is listed as a modifier, not a score. Barding can't be etched with magic runes, though special magical barding might be available.",TraitDescriptionBeastkin:"Humanoids that can partially or fully transform into animal forms.",TraitDescriptionBomb:"An alchemical bomb combines volatile alchemical components that explode when the bomb hits a creature or object. Most alchemical bombs deal damage, though some produce other effects.",TraitDescriptionBottledBreath:"Bottles of breath are enchanted bottles of cloud and mist, first developed by the denizens of the Plane of Air. You can Activate an item with the bottled breath trait as you inhale it or cause another creature to inhale it.",TraitDescriptionBrace:"A brace weapon is effective at damaging moving opponents. When you Ready to Strike an opponent that moves within your reach, until the start of your next turn Strikes with the brace weapon deal an additional 2 precision damage for each weapon damage die it has.",TraitDescriptionBrutal:"A ranged attack with this trait uses its Strength modifier instead of Dexterity on the attack roll.",TraitDescriptionBulwark:"The armor covers you so completely that it provides benefits against some damaging effects. On Reflex saves to avoid a damaging effect, such as a fireball, you add a +3 modifier instead of your Dexterity modifier.",TraitDescriptionCantrip:"A spell you can cast at will that is automatically heightened to half your level rounded up.",TraitDescriptionCapacity:"Weapons that have the capacity trait typically have multiple barrels or chambers capable of containing a round of ammunition. Capacity is always accompanied by a number indicating the number of barrels or chambers. After a capacity weapon is fired, you can select the next loaded barrel or chamber as an Interact action that doesn't require a free hand. Each barrel or chamber can be reloaded after it's fired as a separate Interact action.",TraitDescriptionCatalyst:"Items with the catalyst trait are consumable material spell components that alter or magnify specific spells. Activating a catalyst is part of Casting the Spell. The catalyst might increase the number of actions required to Cast the Spell, as indicated in the catalyst's Activate entry. Additionally, the spell gains material components if it didn't have them already or adds the catalyst to its existing components. Because the catalyst becomes part of the material components, you can draw the catalyst as part of Casting the Spell.",TraitDescriptionCatfolk:"A creature with this trait is a member of the catfolk ancestry.",TraitDescriptionCenser:"Censers are decorative containers, often metal or ceramic, in which incense is burned. An item with the censer trait must be filled with incense to Activate it, which ignites the incense and causes the censer to exude a cloud of smoke.",TraitDescriptionChampion:"This indicates abilities from the champion class.",TraitDescriptionChangeling:"A creature with this trait is a member of the changeling ancestry.",TraitDescriptionClass:"Archetypes with the class trait fundamentally diverge from your class's specialties but still fit within the theme of your class. You can select a class archetype only if your class meets the criteria listed in the archetype's prerequisites. Class archetypes always alter or replace some of a class's static class features in addition to any new feats they offer. It might be possible to take a class archetype at 1st level if it alters or replaces some of the class's initial class features. The 1st-level ability is presented much like a class feature and includes the class archetype's prerequisites and rules on how it changes your class. If you select this ability, you must take that archetype's dedication feat at 2nd level, and you proceed normally afterward. You can never have more than one class archetype.",TraitDescriptionCleric:"This indicates abilities from the cleric class.",TraitDescriptionClimbing:"The hand wielding the weapon is available to Climb.",TraitDescriptionClockwork:"Clockworks are intricate, complex constructs that can be programmed to perform specific functions.",TraitDescriptionCobbled:"This firearm is cobbled together and likely to misfire. No matter how well you upkeep it, on a failed attack roll, the attack misses and you must roll a @Check[type:flat|dc:5]. If you fail this check, the weapon misfires.",TraitDescriptionCoda:"<p>Instruments with the coda trait work mostly like staves and have the staff trait. There are two differences: Coda instruments are in the form of musical instruments, and they can be prepared only by bards. Because they're not physically staves, you can't attack with a coda instrument, nor can you etch it with weapon runes.</p><p>The process of preparing a coda instrument involves playing significant portions of songs related to the spells within the instrument\u2014either old standards or ones of your own creation. This leaves magical reverberations within the instrument that allow you to complete the songs by playing their coda later in the day.</p>",TraitDescriptionCold:"Effects with this trait deal cold damage. Creatures with this trait have a connection to magical cold.",TraitDescriptionCombination:"This is a trait for weapons that combine the functionality of melee weapons and firearms in unique or unusual ways. A combination weapon has both a firearm form or usage and a melee weapon form or usage.",TraitDescriptionComfort:"The armor is so comfortable that you can rest normally while wearing it.",TraitDescriptionCommon:"Anything that doesn't list another rarity trait (uncommon, rare, or unique) automatically has the common trait. This rarity indicates that an ability, item, or spell is available to all players who meet the prerequisites for it. A creature of this rarity is generally known and can be summoned with the appropriate summon spell.",TraitDescriptionCompanion:"An item with this trait can be worn by an animal companion or similar creature. A companion can have up to two items invested.",TraitDescriptionComplex:"A hazard with this trait takes turns in an encounter.",TraitDescriptionComposite:"A composite impulse combines multiple elements. You can gain an impulse with the composite trait only if your kinetic elements include all the elements listed in the impulse's traits.",TraitDescriptionComposition:"To cast a composition cantrip or focus spell, you usually use a type of Performance. If the spell includes a verbal component, you must use an auditory performance, and if it includes a somatic component, you must use a visual one. The spell gains all the traits of the performance you used. You can cast only one composition spell each turn, and you can have only one active at a time. If you cast a new composition spell, any ongoing effects from your previous composition spell end immediately.",TraitDescriptionConcealable:"This weapon is designed to be inconspicuous or easily concealed. You gain a +2 circumstance bonus to Stealth checks and DCs to hide or conceal a weapon with this trait.",TraitDescriptionConcentrate:"An action with this trait requires a degree of mental concentration and discipline.",TraitDescriptionConcussive:"These weapons smash as much as puncture. When determining a creature's resistance or immunity to damage from this weapon, use the weaker of the target's resistance or immunity to piercing or to bludgeoning. For instance, if the creature were immune to piercing and had no resistance or immunity to bludgeoning damage, it would take full damage from a concussive weapon. Resistance or immunity to all physical damage, or all damage, applies as normal.",TraitDescriptionConrasu:"A people that are made of cosmic force given consciousness and housed within unique exoskeletons.",TraitDescriptionConsecration:"A consecration spell enhances an area for an extended period of time. A given area can have only a single consecration effect at a time. The new effect attempts to counteract any existing one in areas of overlap.",TraitDescriptionConstruct:"A construct is an artificial creature empowered by a force other than necromancy. Constructs are often mindless; they are immune to bleed damage, death effects, disease, healing, necromancy, nonlethal attacks, poison, and the doomed, drained, fatigued, paralyzed, sickened, and unconscious conditions; and they may have Hardness based on the materials used to construct their bodies. Constructs are not living creatures, nor are they undead. When reduced to 0 Hit Points, a construct creature is destroyed.",TraitDescriptionConsumable:"An item with this trait can be used only once. Unless stated otherwise, it's destroyed after activation. Consumable items include alchemical items and magical consumables such as scrolls and talismans. When a character creates consumable items, they can make them in batches of four.",TraitDescriptionContact:"This poison is delivered by contact with the skin.",TraitDescriptionContingency:"Spells with this trait grant you an action during the spell's effects, typically a reaction with a special trigger. They typically have a long duration, such as 24 hours. You can have only one spell with the contingency trait, or one contingency spell, active at a time. If you cast another spell with the contingency trait or contingency, the newer casting supersedes the older.",TraitDescriptionContract:"A contract is a type of item that magically establishes an agreement between multiple parties and typically grants magical benefits.",TraitDescriptionCriticalFusion:"Critical fusion is a new trait for combination weapons that grants you two additional options for the critical specialization effect when using the combination weapon's melee version to make a melee attack while the firearm is loaded. If you choose to use one of them, they replace the melee usage's normal critical specialization effect. First, you can discharge the firearm to create a loud bang and concussion, using the critical specialization effect for firearms instead of the melee weapon group's critical specialization effect. Second, you can choose to discharge the firearm to increase the critical hit's momentum or shoot the foe as you attack them in melee, dealing 2 additional damage per weapon damage die. Both of these options discharge the firearm, which typically means you have to reload it before firing it again.",TraitDescriptionCurse:"A curse is an effect that places some long-term affliction on a creature. Curses are always magical and are typically the result of a spell or trap. Effects with this trait can be removed only by effects that specifically target curses.",TraitDescriptionCursebound:"Spells with this trait increase the severity of your oracular curse when cast. Usually, only revelation spells have this trait. You can't cast a cursebound spell if you don't have an oracular curse.",TraitDescriptionCursed:"An item with this trait is cursed to cause trouble for its owner. A curse isn't detected when the item is identified, though a critical success reveals both the presence and exact nature of the curse. Cursed items can't be discarded once they've been triggered or invested the first time. The item can be removed only if the curse is removed.",TraitDescriptionDarkness:"Darkness effects extinguish non-magical light in the area, and can counteract less powerful magical light. You must usually target light magic with your darkness magic directly to counteract the light, but some darkness spells automatically attempt to counteract light.",TraitDescriptionDarvakka:"Entropic undead creatures twisted by the Netherworld and the Void.",TraitDescriptionDeadly:"On a critical hit, the weapon adds a weapon damage die of the listed size. Roll this after doubling the weapon's damage. This increases to two dice if the weapon has a greater striking rune and three dice if the weapon has a major striking rune. For instance, a rapier with a greater striking rune deals 2d8 extra piercing damage on a critical hit. An ability that changes the size of the weapon's normal damage dice doesn't change the size of its deadly die.",TraitDescriptionDeath:"An effect with the death trait kills you immediately if it reduces you to 0 HP. Some death effects can bring you closer to death or slay you outright without reducing you to 0 HP.",TraitDescriptionDedication:"You must select a feat with this trait to apply an archetype to your character.",TraitDescriptionDeflecting:"This shield is designed to block or divert certain types of attacks or weapons. Increase the shield's Hardness against the listed type of attack by 2.",TraitDescriptionDetection:"Effects with this trait attempt to determine the presence or location of a person, object, or aura.",TraitDescriptionDeviant:"This trait describes strange supernatural or paranormal abilities.",TraitDescriptionDhampir:"A creature with this trait is a member of the dhampir ancestry. These humanoids are the mortal offspring of vampires and members of other ancestries.",TraitDescriptionDisarm:"You can use this weapon to Disarm with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls (if any) as an item bonus to the Athletics check. If you critically fail a check to Disarm using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure. On a critical success, you still need a free hand if you want to take the item.",TraitDescriptionDisease:"An effect with this trait applies one or more diseases. A disease is typically an affliction.",TraitDescriptionDivine:"This magic comes from the divine tradition, drawing power from deities or similar sources. Anything with this trait is magical.",TraitDescriptionDoubleBarrel:"This weapon has two barrels that are each loaded separately. You can fire both barrels of a double barrel weapon in a single Strike to increase the weapon damage die by one step. If the weapon has the fatal trait, this increases the fatal die by one step.",TraitDescriptionDowntime:"An activity with this trait takes a day or more, and can be used only during downtime.",TraitDescriptionDromaar:"A creature with this trait has the dromaar versatile heritage. Dromaars are of mixed ancestry, including orcs or other dromaars. An ability with this trait can be used or selected only by dromaars.",TraitDescriptionDrug:"An item with this trait is a drug, a poison that conveys short-term benefits in addition to harmful side effects and long-term consequences. Each time a creature uses a given drug it must also attempt a saving throw against addiction to that drug.",TraitDescriptionDruid:"This indicates abilities from the druid class.",TraitDescriptionDuskwalker:"A creature with this trait has the duskwalker versatile heritage. Duskwalkers are planar scions infused with the supernatural energy of psychopomps. An ability with this trait can be used or selected only by duskwalkers.",TraitDescriptionDwarf:"A creature with this trait is a member of the dwarf ancestry. Dwarves are stout folk who often live underground and typically have darkvision. An ability with this trait can be used or selected only by dwarves. An item with this trait is created and used by dwarves.",TraitDescriptionEarth:"Effects with the earth trait either manipulate or conjure earth. Those that manipulate earth have no effect in an area without earth. Creatures with this trait consist primarily of earth or have a magical connection to that element.",TraitDescriptionEidolon:"A creature with this trait is a summoner's eidolon. An item with this trait can be worn by an eidolon. An eidolon can have up to two items invested.",TraitDescriptionElectricity:"Effects with this trait deal electricity damage. A creature with this trait has a magical connection to electricity.",TraitDescriptionElf:"A creature with this trait is a member of the elf ancestry. Elves are mysterious people with rich traditions of magic and scholarship who typically have low-light vision. An ability with this trait can be used or selected only by elves. A weapon with this trait is created and used by elves.",TraitDescriptionElixir:"Elixirs are alchemical liquids that are used by drinking them.",TraitDescriptionEmotion:"This effect alters a creature's emotions. Effects with this trait always have the mental trait as well. Creatures with special training or that have mechanical or artificial intelligence are immune to emotion effects.",TraitDescriptionEntrench:"You can position yourself in the armor or reposition its articulated pieces to better protect against some attacks. If you're trained in this armor, while wearing it you can spend a single action to gain a +1 circumstance bonus to AC against a certain type of attack until the start of your next turn. The entrench trait lists the type of attack this bonus applies against, typically entrench melee or entrench ranged.",TraitDescriptionEnvironment:"A hazard with this trait is something dangerous that's part of the natural world, such as quicksand or harmful mold.",TraitDescriptionEsoterica:"The esoterica trait is present in many thaumaturge feats and class features that incorporate the various talismans, supernatural trinkets, and other objects you carry with you. Abilities that have the esoterica trait require you to be in possession of your esoterica to use them. Normally, you're assumed to always have your esoterica with you, but in some rare circumstances, you might either not have them on hand or have your gear stripped from you.",TraitDescriptionEvolution:"Feats with this trait affect your eidolon instead of you, typically by granting it additional physical capabilities.",TraitDescriptionExpandable:"An item with the expandable trait increases to a specific size when activated. Unless otherwise noted, this space must be adjacent to you and on the ground, and the item needs to have enough open space to expand into or else the activation has no effect. When the effect ends, the expanded item disintegrates if it's a consumable or shrinks back to its normal size if it's not a consumable.",TraitDescriptionExploration:"An activity with this trait takes more than a turn to use, and can usually be used only during exploration mode.",TraitDescriptionExtradimensional:"This effect or item creates an extradimensional space. An extradimensional effect placed inside another extradimensional space ceases to function until it is removed.",TraitDescriptionFatal:"The fatal trait includes a die size. On a critical hit, the weapon's damage die increases to that die size instead of the normal die size, and the weapon adds one additional damage die of the listed size.",TraitDescriptionFatalAim:"It's possible to hold the stock of this weapon under one arm so you can fire it with a single hand as long as the other hand isn't holding a weapon, shield, or anything else you would need to move and position, to ensure the weapon doesn't slip out from under your arm. However, if you use both hands, the weapon can make fatal attacks. When you wield the weapon in two hands, it gains the fatal trait with the listed damage die. Holding the weapon underarm stably enough to fire is significantly more complicated than just releasing one hand from the weapon, so to switch between the two grips, you must do so with an Interact action rather than Releasing or as part of reloading.",TraitDescriptionFear:"Fear effects evoke the emotion of fear. Effects with this trait always have the mental and emotion traits as well.",TraitDescriptionFetchling:"A creature with this trait is a member of the fetchling ancestry. Fetchlings were once human, but generations of life in the Netherworld have transformed them.",TraitDescriptionFey:"Creatures of the First World are called the fey.",TraitDescriptionFighter:"This indicates abilities from the fighter class.",TraitDescriptionFigurehead:"While many ships are adorned with decorative carvings, daring crews sometimes procure magical figureheads for their vessels.",TraitDescriptionFinesse:"You can use your Dexterity modifier instead of your Strength modifier on attack rolls using this melee weapon. You still use your Strength modifier when calculating damage.",TraitDescriptionFinisher:"Finishers are spectacular finishing moves. You can use a finisher only if you have panache, and you lose your panache immediately after performing a finisher. Once you use a finisher, you can't use actions that have the attack trait for the rest of your turn. Some finisher actions also grant an effect on a failure. If your finisher succeeds, you can choose to apply the failure effect instead.",TraitDescriptionFinite:"Planes with this trait consist of a limited amount of space.",TraitDescriptionFire:"Effects with the fire trait deal fire damage or either conjure or manipulate fire. Those that manipulate fire have no effect in an area without fire. Creatures with this trait consist primarily of fire or have a magical connection to that element.",TraitDescriptionFleshwarp:"A humanoid transformed so completely by outside forces that they are now a unique ancestry.",TraitDescriptionFlexible:"The armor is flexible enough that it doesn't hinder most actions. You don't apply its check penalty to Acrobatics or Athletics checks.",TraitDescriptionFlourish:"Flourish actions are actions that require too much exertion to perform a large number in a row. You can use only 1 action with the flourish trait per turn.",TraitDescriptionFocus:"Focus spells are a special type of spell attained directly from a branch of study, from a deity, or from another specific source. You can learn focus spells only through special class features or feats, rather than choosing them from a spell list. Furthermore, you cast focus spells using a special pool of Focus Points\u2014you can't prepare a focus spell in a spell slot or use your spell slots to cast focus spells; similarly, you can't spend your Focus Points to cast spells that aren't focus spells.",TraitDescriptionFocused:"An item with this trait can give you an additional Focus Point. This focus point is separate from your focus pool and doesn't count toward the cap on your focus pool. You can gain this benefit only if you have a focus pool, and there might be restrictions on how the point can be used. You can't gain more than 1 Focus Point per day from focused items.",TraitDescriptionFoldaway:"<p>This shield can collapse into a smaller form attached to a gauntlet for stability and easy travel. You can use an Interact action to deploy or stow the shield. While it's deployed, you can Raise the Shield as long as you have that hand free or are holding an object of light Bulk that's not a weapon in that hand. The shield impedes the use of your hand while it's deployed. Though you can still hold items in that hand, you can't wield weapons in that hand, operate anything that takes two hands, or attack with the gauntlet.</p><p>A foldaway shield must be attached to a gauntlet for stability. It can be affixed to an item with 10 minutes of work and a successful DC 10 Crafting check; this includes the time needed to remove the shield from a previous gauntlet, if necessary. If the gauntlet is destroyed, the foldaway shield can usually be salvaged. The collapsible nature of the shield makes it impossible to affix an attached weapon to it.</p>",TraitDescriptionForce:"Effects with this trait deal force damage or create objects made of pure magical force.",TraitDescriptionForceful:"This weapon becomes more dangerous as you build momentum. When you attack with it more than once on your turn, the second attack gains a circumstance bonus to damage equal to the number of weapon damage dice, and each subsequent attack gains a circumstance bonus to damage equal to double the number of weapon damage dice.",TraitDescriptionFortune:"A fortune effect beneficially alters how you roll your dice. You can never have more than one fortune effect alter a single roll. If multiple fortune effects would apply, you have to pick which to use. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionFreeHand:"This weapon doesn't take up your hand, usually because it is built into your armor. A free-hand weapon can't be Disarmed. You can use the hand covered by your free-hand weapon to wield other items, perform manipulate actions, and so on. You can't attack with a free-hand weapon if you're wielding anything in that hand or otherwise using that hand. When you're not wielding anything and not otherwise using the hand, you can use abilities that require you to have a hand free as well as those that require you to be wielding a weapon in that hand. Each of your hands can have only one free-hand weapon on it.",TraitDescriptionFulu:"Fulus are small paper charms that can be affixed to a suit of armor, a shield, a weapon, a creature, or even a structure. Some fulus are composed of multiple such charms, taking effect only once all have been affixed. Normal fulus have effects immediately once affixed, while fulu talismans have an effect only once activated. Once a fulu has been activated, it lasts for the given duration and then burns out. Unless otherwise noted, fulus expire one year after being created, reverting to mundane paper. All fulus have the fulu and consumable traits. Fulus also have a tradition trait\u2014either arcane, divine, occult or primal\u2014determined by the magical tradition of its creator. For example, a fulu created by a priest would have the divine trait, whereas a witch who dabbles in fate might create a fulu with the occult trait. Some fulus also have the talisman trait, if they work similarly to talismans (such as being affixed to a suit of armor, a shield, or a weapon. Each fulu's stat block indicates the type of item or creature it can be affixed to. Affixing or removing a fulu requires using the Affix a Fulu activity, or the Affix a Talisman action instead if the fulu is also a talisman.",TraitDescriptionGadget:"Gadgets are consumable technological inventions with innovative uses.",TraitDescriptionGanzi:"A planar scion descended from a chaotic being of the Maelstrom, such as a protean.",TraitDescriptionGeneral:"A type of feat that any character can select, regardless of ancestry and class, as long as they meet the prerequisites. You can select a feat with this trait when your class grants a general feat.",TraitDescriptionGenie:"The diverse families of genies hold positions of prominence on the Elemental Planes. They have powerful magical abilities.",TraitDescriptionGeniekin:"An umbrella term for planar scions descended from beings from the Elemental Planes.",TraitDescriptionGhoran:"An intelligent plant ancestry that maintain long lives by rejuvenating themselves from seeds.",TraitDescriptionGhul:"Greedy and gluttonous undead originally formed from genie.",TraitDescriptionGnoll:"Gnolls are humanoids that resemble hyenas.",TraitDescriptionGnome:"A creature with this trait is a member of the gnome ancestry. Gnomes are small people skilled at magic who seek out new experiences and usually have low-light vision. An ability with this trait can be used or selected only by gnomes. A weapon with this trait is created and used by gnomes.",TraitDescriptionGoblin:"A creature with this trait can come from multiple tribes of creatures, including goblins, hobgoblins, and bugbears. Goblins tend to have darkvision. An ability with this trait can be used or chosen only by goblins. A weapon with this trait is created and used by goblins.",TraitDescriptionGoloma:"Insular humanoids that bear countless eyes.",TraitDescriptionGrapple:"You can use this weapon to Grapple with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Grapple using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionGrimoire:"Spellbooks are useful tools for any magic user to write down incantations and runes of power, but where most spellbooks are nothing more than ink on parchment, grimoires have absorbed the magic of the spells within\u2014magic that knowledgeable spellcasters can use to augment their spells.",TraitDescriptionGrippli:"Gripplis are a family of frog-like humanoids",TraitDescriptionGunslinger:"This indicates abilities from the gunslinger class.",TraitDescriptionHalfling:"A creature with this trait is a member of the halfling ancestry. These small people are friendly wanderers considered to be lucky. An ability with this trait can be used or selected only by halflings. A weapon with this trait is created and used by halflings.",TraitDescriptionHampering:"A weapon with the hampering trait includes a disruptive limb or flange. You can use an Interact action to thrash the weapon in a square within the weapon's reach. That square becomes difficult terrain until you attack with the weapon, move, would otherwise stop thrashing it, or at the beginning of your next turn.",TraitDescriptionHarnessed:"This shield features a special brace or opening designed to hold jousting weapons.",TraitDescriptionHaunt:"A hazard with this trait is a spiritual echo, often of someone with a tragic death. Putting a haunt to rest often involves resolving the haunt's unfinished business. A haunt that hasn't been properly put to rest always returns after a time.",TraitDescriptionHealing:"A healing effect restores a creature's body, typically by restoring Hit Points, but sometimes by removing diseases or other debilitating effects.",TraitDescriptionHefty:"A hefty shield is so heavy that raising it takes more effort. Raising a Shield with the hefty trait is a 2-action activity unless your Strength score equals or exceeds the number with the trait.",TraitDescriptionHex:"A hex is a type of focus spell a witch can cast.",TraitDescriptionHindering:"This armor is so heavy and bulky it slows you down no matter what. You take a -5 penalty to all your Speeds (to a minimum of a 5-foot Speed). This is separate from and in addition to the armor's Speed penalty, and affects you even if your Strength or an ability lets you reduce or ignore the armor's Speed penalty.",TraitDescriptionHobgolin:"Hobgoblins are a sturdy, clever people with a propensity for militaristic order.",TraitDescriptionHoly:"Effects with the holy trait are tied to powerful magical forces of benevolence and virtue. They often have stronger effects on unholy creatures. Creatures with this trait are strongly devoted to holy causes and often have weakness to unholy. If a creature with weakness to holy uses a holy item or effect, it takes damage from its weaknes",TraitDescriptionHuman:"A creature with this trait is a member of the human ancestry. Humans are a diverse array of people known for their adaptability. An ability with this trait can be used or selected only by humans.",TraitDescriptionHumanoid:"Humanoid creatures reason and act much like humans. They typically stand upright and have two arms and two legs.",TraitDescriptionIfrit:"A type of geniekin descended from a being from the Plane of Fire.",TraitDescriptionIllusion:"Effects and magic items with this trait involve false sensory stimuli.",TraitDescriptionImpulse:"The primary magical actions kineticists use are called impulses. You can use an impulse only if your kinetic aura is active and channeling that element, and only if you have a hand free to shape the elemental flow. The impulse trait means the action has the concentrate trait unless another ability changes this. If an impulse allows you to choose an element, you can choose any element you're channeling, and the impulse gains that element's trait.",TraitDescriptionIncapacitation:"An ability with this trait can take a character completely out of the fight or even kill them, and it's harder to use on a more powerful character. If a spell has the incapacitation trait, any creature of more than twice the spell's rank treats the result of their check to prevent being incapacitated by the spell as one degree of success better, or the result of any check the spellcaster made to incapacitate them as one degree of success worse. If any other effect has the incapacitation trait, a creature of higher level than the item, creature, or hazard generating the effect gains the same benefits.",TraitDescriptionIncarnate:"A spell with the incarnate trait is similar in theme to spells that summon creatures, but it doesn't conjure a minion with the summoned trait. Instead, when summoned, the incarnate creature takes its Arrive action when you finish Casting the Spell. At the end of your next turn, the incarnate creature can either Step, Stride, or take the action for another movement type it has (such as Climb or Burrow), and then takes its Depart action. The spell then ends. The names of specific Arrive and Depart actions are listed in italics after the word \u201CArrive\u201D or \u201CDepart\u201D respectively, along with any traits. A creature summoned by an incarnate spell acts in your interests, directs its effects away from you and your allies as much as possible, and might listen to your requests, but ultimately makes its own decisions. If the spell indicates that the incarnate makes a decision, the GM determines what the incarnate would do. It might even become more inclined to do precisely as you wish over multiple summonings. The incarnate is not fully a creature. It can't take any other actions, nor can it be targeted or harmed by Strikes, spells, or other effects unless they would be able to target or end a spell effect (such as dispel magic). It has a size for the purposes of determining its placement for effects, but it doesn't block movement. If applicable, its effects use your spell DCs and spell attack roll modifier.",TraitDescriptionIncorporeal:"An incorporeal creature or object has no physical form. It can pass through solid objects, including walls. When inside an object, an incorporeal creature can't perceive, attack, or interact with anything outside the object, and if it starts its turn in an object, it is slowed 1. Corporeal creatures can pass through an incorporeal creature, but they can't end their movement in its space. An incorporeal creature can't attempt Strength-based checks against physical creatures or objects-only against incorporeal ones-unless those objects have the ghost touch property rune. Likewise, a corporeal creature can't attempt Strength-based checks against incorporeal creatures or objects. Incorporeal creatures usually have immunity to effects or conditions that require a physical body, like disease, poison, and precision damage. They usually have resistance against all damage (except force damage and damage from Strikes with the ghost touch property rune), with double the resistance against non-magical damage.",TraitDescriptionInfused:"You created an alchemical item with the infused trait using your infused reagents, and it has a limited time before it becomes inert. Any nonpermanent effects from your infused alchemical items, with the exception of afflictions such as slow-acting poisons, end when you make your daily preparations again.",TraitDescriptionInfusion:"Actions with the infusion trait tweak your kineticist impulses. You must use an infusion action directly before the impulse action you want to alter. If you use any action (including free actions and reactions) other than an impulse action directly after, you waste the benefits of the infusion action. Any additional effects added by an infusion action are part of the impulse's effect, not of the infusion action itself.",TraitDescriptionIngested:"This poison is delivered when drunk or eaten.",TraitDescriptionInhaled:"This poison is delivered when breathed in.",TraitDescriptionInjection:"This weapon can be filled with an injury poison. Immediately after a successful attack with the weapon, you can inject the target with the loaded poison with a single Interact action. Refilling the weapon with a new substance requires three Interact actions, and uses both hands.",TraitDescriptionInjury:"This poison is delivered by damaging the recipient.",TraitDescriptionInscribed:"The armor or shield has been treated so it can be inscribed with magical symbols using the same method as Crafting a scroll. Inscribed attire can hold one scroll inscribed on it. You need a free hand to Activate the scroll, but you don't need to Interact to draw it. You can also Activate the magic to erase the scroll the armor currently contains. You can't inscribe a new scroll onto the armor if a scroll is currently inscribed on it or if the armor is broken.",TraitDescriptionIntegrated:"This shield has been created to include a weapon in its construction, which works like an attached weapon but can't be removed from the shield.",TraitDescriptionIntelligent:"An item with this trait is intelligent and has its own will and personality, as well as several statistics that most items don't have. Intelligent items can't be crafted by normal means, and they are always rare or unique.",TraitDescriptionInventor:"This indicates abilities from the inventor class.",TraitDescriptionInvested:"A character can wear only 10 magical items that have the invested trait. None of the magical effects of the item apply if the character hasn't invested it, nor can it be activated, though the character still gains any normal benefits from wearing the physical item (like a hat keeping rain off their head).",TraitDescriptionInvestigator:"This indicates abilities from the investigator class.",TraitDescriptionJousting:"The weapon is suited for mounted combat with a harness or similar means. When mounted, if you moved at least 10 feet on the action before your attack, add a circumstance bonus to damage for that attack equal to the number of damage dice for the weapon. In addition, while mounted, you can wield the weapon in one hand, changing the damage die to the listed value.",TraitDescriptionKashrishi:"A stout ancestry bearing distinctive crystal horns and inherent psychic abilities.",TraitDescriptionKickback:"A kickback weapon is extra powerful and difficult to use due to its high recoil. A kickback weapon deals 1 additional damage with all attacks. Firing a kickback weapon gives a -2 circumstance penalty to the attack roll, but characters with 14 or more Strength ignore the penalty. Attaching a kickback weapon to a deployed bipod, tripod, or other stabilizer can lower or negate this penalty.",TraitDescriptionKineticist:"This indicates abilities from the kineticist class.",TraitDescriptionKitsune:"Shapeshifting humanoids whose true forms resemble foxes.",TraitDescriptionKobold:"A creature with this trait is a member of the kobold ancestry.",TraitDescriptionLaminar:"The armor is made up of layered sections, so when it breaks, it isn't as much of a problem. The status penalty to AC if this armor is broken is \u20131 for broken medium armor, \u20132 for broken heavy armor, or no penalty for broken light armor.",TraitDescriptionLaunching:`A mechanism within this shield can shoot projectiles, causing the shield to also function as a ranged weapon. The trait lists the type of weapon, such as "launching dart." Striking with the launcher requires the same number of hands as normal, except that the hand holding the shield counts toward this total, so a one-handed ranged weapon would require only one hand. Reloading takes the normal number of Interact actions, to a minimum of 1 action, and you can't use the hand holding your shield to reload.`,TraitDescriptionLeshy:"A creature with this trait is a member of the leshy ancestry.",TraitDescriptionLight:"Light effects overcome non-magical darkness in the area, and can counteract magical darkness. You must usually target darkness magic with your light magic directly to counteract the darkness, but some light spells automatically attempt to counteract darkness.",TraitDescriptionLinguistic:"An effect with this trait depends on language comprehension. A linguistic effect that targets a creature works only if the target understands the language you are using.",TraitDescriptionLitany:"Litanies are special devotion spells, typically used by champions and requiring a single action, that usually give temporary immunity to further litanies.",TraitDescriptionLizardfolk:"These reptilian humanoids, also known as iruxi, are extremely adaptable and patient.",TraitDescriptionLozenge:"You Activate an alchemical lozenge by putting it in your mouth. It stays there, slowly dissolving and releasing its ingredients over time. You can bite a lozenge for a secondary effect. The action this takes is noted in the item. As soon as this secondary effect is over, the lozenge is used up and its benefits for you end. You can drink elixirs, potions, and beverages with a lozenge in your mouth, but you can't benefit from more than one lozenge at a time. If you have two lozenges in your mouth at the same time, both become inert. You can also spit out a lozenge as a single action to end its effect and make it inert. A lozenge dissolves due to its alchemical ingredients, so it typically still works even if you don't have saliva.",TraitDescriptionMagical:"Something with the magical trait is imbued with magical energies not tied to a specific tradition of magic. Some items or effects are closely tied to a particular tradition of magic. In these cases, the item has the arcane, divine, occult, or primal trait instead of the magical trait. Any of these traits indicate that the item is magical.",TraitDescriptionMagus:"This indicates abilities from the magus class.",TraitDescriptionManipulate:"You must physically manipulate an item or make gestures to use an action with this trait. Creatures without a suitable appendage can't perform actions with this trait. Manipulate actions often trigger reactions.",TraitDescriptionMechanical:"A hazard with this trait is a constructed physical object.",TraitDescriptionMental:"A mental effect can alter the target's mind. It has no effect on an object or a mindless creature.",TraitDescriptionMetal:"Effects with the metal trait either manipulate or conjure metal. Those that manipulate metal have no effect in an area without metal. Creatures with this trait consist primarily of metal or have a magical connection to that element.",TraitDescriptionMindless:"A mindless creature has either programmed or rudimentary mental attributes. Most, if not all, of their mental attribute modifiers are -5. They are immune to all mental effects.",TraitDescriptionMindshift:"An action with this trait can always be altered to use the raw power of your mind. When you take this action, you can choose to replace any damage it deals with mental damage, give it the mental trait, and replace any save it requires with a Will save. The action loses any traits matching damage types it no longer deals.",TraitDescriptionMinion:"Minions are creatures that directly serve another creature. A creature with this trait can use only 2 actions per turn, doesn't have reactions, and can't act when it's not your turn. Your minion acts on your turn in combat, once per turn, when you spend an action to issue it commands. For an animal companion, you Command an Animal; for a minion that's a spell or magic item effect, like a summoned minion, you Sustain a Spell or Sustain an Activation; if not otherwise specified, you issue a verbal command as a single action with the auditory and concentrate traits. If given no commands, minions use no actions except to defend themselves or to escape obvious harm. If left unattended for long enough, typically 1 minute, mindless minions usually don't act, animals follow their instincts, and sapient minions act how they please. A minion can't control other creatures.",TraitDescriptionMisfortune:"A misfortune effect detrimentally alters how you roll your dice. You can never have more than one misfortune effect alter a single roll. If multiple misfortune effects would apply, the GM decides which is worse and applies it. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionMissive:"A missive is a piece of magical stationery that must be crafted and composed before it can be activated. All missives have the missive and consumable traits. Missives are often constructed of paper, parchment, or vellum, but any other thin, portable material that can hold writing or embossing upon it can be crafted into missives. After being crafted, the missive is a blank sheet until a message is composed upon it, completing its magic.",TraitDescriptionModification:"A feat with this trait alters the construction of your innovation. If you have the reconfigure class feature, you can retrain such a feat more easily.",TraitDescriptionModular:`The weapon has multiple configurations that you can switch between using an Interact action. Typically, switching between configurations of a modular weapon allows it to deal different types of damage (listed in the trait, such as "modular B, P, or S"), though it's possible for a modular weapon's description to list more complicated configurations.`,TraitDescriptionMonk:"Abilities with this trait are from the monk class. A weapon with this trait is primarily used by monks.",TraitDescriptionMonkWeapon:"Many monks learn to use these weapons.",TraitDescriptionMorph:"Effects that slightly alter a creature's form have the morph trait. Any Strikes specifically granted by a morph effect are magical. You can be affected by multiple morph spells at once, but if you morph the same body part more than once, the second morph effect attempts to counteract the first (in the same manner as two polymorph effects, described in that trait). Your morph effects might also end if you are polymorphed and the polymorph effect invalidates or overrides your morph effect. The GM determines which morph effects can be used together and which can't.",TraitDescriptionMounted:"Mounted siege weapons take up a certain size and space, and typically have statistics to allow them to be attacked. They're used for large-scale warfare.",TraitDescriptionMove:"An action with this trait involves moving from one space to another.",TraitDescriptionMulticlass:"Archetypes with the multiclass trait represent diversifying your training into another class's specialties. You can't select a multiclass archetype's dedication feat if you are a member of the class of the same name.",TraitDescriptionMutagen:"An elixir with the mutagen trait temporarily transmogrifies the subject's body and alters its mind. A mutagen always conveys one or more beneficial effects paired with one or more detrimental effects. Mutagens are polymorph effects, meaning you can benefit from only one at a time.",TraitDescriptionNagaji:"A traditionalist ancestry with reptilian features and serpentine heads.",TraitDescriptionNephilim:"A creature with this trait has the nephilim versatile heritage. Nephilim are planar scions descended from immortal beings from other planes. An ability with this trait can be used or selected only by nephilim.",TraitDescriptionNindoru:"Nindorus are chaotic evil fiends that rise from corruptions to the cycle of reincarnating souls and live on the Universe. Although they often have elements in their appearance that make them seem undead, they're actually living beings. Most nindorus have darkvision, are immune to death effects, have weakness to silver, and possess the power to manifest objects or creatures from their thoughts.",TraitDescriptionNoisy:"This armor is loud and likely to alert others to your presence when you're using the Avoid Notice exploration activity. The armor's check penalty applies to Stealth checks even if you meet the required Strength score.",TraitDescriptionNone:"This trait has no description.",TraitDescriptionNonlethal:"Attacks with this weapon are nonlethal, and are used to knock creatures unconscious instead of kill them. You can use a nonlethal weapon to make a lethal attack with a -2 circumstance penalty.",TraitDescriptionOath:"Oaths add an additional tenet to your code. You can usually have only one feat with this trait.",TraitDescriptionOccult:"This magic comes from the occult tradition, calling upon bizarre and ephemeral mysteries. Anything with this trait is magical.",TraitDescriptionOil:"Oils are magical gels, ointments, pastes, or salves that are typically applied to an object and are used up in the process.",TraitDescriptionOlfactory:"An olfactory effect can affect only creatures that can smell it. This applies only to olfactory parts of the effect, as determined by the GM.",TraitDescriptionOpen:"These maneuvers work only as the first salvo on your turn. You can use an open only if you haven't used an action with the attack or open trait yet this turn.",TraitDescriptionOracle:"This indicates abilities from the oracle class.",TraitDescriptionOrc:"A creature with this trait is a member of the orc ancestry. A weapon with this trait is a weapon which orcs craft and use.",TraitDescriptionOread:"A type of geniekin descended from a being from the Plane of Earth.",TraitDescriptionOverflow:"Powerful impulses temporarily overdraw the energy of your kinetic gate. When you use an impulse that has the overflow trait, your kinetic aura deactivates until you revitalize it (typically with Channel Elements). Extinguishing your element this severely is taxing, and consequently, you can use only one overflow impulse per round, even if you reactivate your kinetic gate.",TraitDescriptionParry:"This weapon can be used defensively to block attacks. While wielding this weapon, if your proficiency with it is trained or better, you can spend a single action to position your weapon defensively, gaining a +1 circumstance bonus to AC until the start of your next turn.",TraitDescriptionPeachwood:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",TraitDescriptionPlant:"Vegetable creatures have the plant trait. They are distinct from normal plants. Magical effects with this trait manipulate or conjure plants or plant matter in some way. Those that manipulate plants have no effect in an area with no plants.",TraitDescriptionPoison:"An effect with this trait delivers a poison or deals poison damage. An item with this trait is poisonous and might cause an affliction.",TraitDescriptionPolymorph:"These effects transform the target into a new form. A target can't be under the effect of more than one polymorph effect at a time. If it comes under the effect of a second polymorph effect, the second polymorph effect attempts to counteract the first. If it succeeds, it takes effect, and if it fails, the spell has no effect on that target. Any Strikes specifically granted by a polymorph effect are magical. Unless otherwise stated, polymorph spells don't allow the target to take on the appearance of a specific individual creature, but rather just a generic creature of a general type or ancestry. If you take on a battle form with a polymorph spell, the special statistics can be adjusted only by circumstance bonuses, status bonuses, and penalties. Unless otherwise noted, the battle form prevents you from casting spells, speaking, and using most manipulate actions that require hands. (If there's doubt about whether you can use an action, the GM decides.) Your gear is absorbed into you; the constant abilities of your gear still function, but you can't activate any items.",TraitDescriptionPonderous:"The armor has moving parts or other complications that lengthen the wearer's initial reaction time. While wearing the armor, you take a \u20131 penalty to initiative checks. If you don't meet the armor's required Strength score, this penalty increases to be equal to the armor's check penalty if it's worse.",TraitDescriptionPoppet:"A creature with this trait is a member of the poppet ancestry.",TraitDescriptionPortable:"Portable siege weapons, such as battering rams, can be more easily carried and have a role in both warfare and smaller conflicts or exploration.",TraitDescriptionPossession:"Effects with this trait allow a creature to project its mind and spirit into a target. A creature immune to mental effects can't use a possession effect. While possessing a target, a possessor's true body is unconscious (and can't wake up normally), unless the possession effect allows the creature to physically enter the target. Whenever the target takes damage, the possessor takes half that amount of damage as mental damage. A possessor loses the benefits of any of its active spells or abilities that affect its physical body, though it gains the benefits of the target's active spells and abilities that affect their body. A possessor can use any of the target's abilities that are purely physical, and it can't use any of its own abilities except spells and purely mental abilities. The GM decides whether an ability is purely physical or purely mental. A possessor uses the target's attack modifier, AC, Fortitude save, Reflex save, Perception, and physical skills, and its own Will save, mental skills, spell attack roll, and spell DC; benefits of invested items apply where relevant (the possessor's invested items apply when using its own values, and the target's invested items apply when using the target's values). A possessor gains no benefit from casting spells that normally affect only the caster, since it isn't in its own body. The possessor must use its own actions to make the possessed creature act. If a possessor reaches 0 Hit Points through any combination of damage to its true body and mental damage from the possession, it is knocked out as normal and the possession immediately ends. If the target reaches 0 Hit Points first, the possessor can either fall unconscious with the body and continue the possession or end the effect as a free action and return to its body. If the target dies, the possession ends immediately and the possessor is stunned for 1 minute.",TraitDescriptionPotion:"A potion is a magical liquid activated when you drink it.",TraitDescriptionPrecious:"Valuable materials with special properties have the precious trait. They can be substituted for base materials when you Craft items.",TraitDescriptionPrediction:"Effects with this trait determine what is likely to happen in the near future. Most predictions are divinations.",TraitDescriptionPress:"Actions with this trait allow you to follow up earlier attacks. An action with the press trait can be used only if you are currently affected by a multiple attack penalty. You can't use a press action when it's not your turn, even if you use the Ready activity. Some actions with the press trait also grant an effect on a failure. The effects that are added on a failure don't apply on a critical failure. If your press action succeeds, you can choose to apply the failure effect instead. (For example, you may wish to do this when an attack deals no damage due to resistance.)",TraitDescriptionPrimal:"This magic comes from the primal tradition, connecting to the natural world and instinct. Anything with this trait is magical.",TraitDescriptionProcessed:"An alchemical consumable with the processed trait can be created with Quick Alchemy but is too complex to create in a single action.",TraitDescriptionPropulsive:"You add half your Strength modifier (if positive) to damage rolls with a propulsive ranged weapon. If you have a negative Strength modifier, you add your full Strength modifier instead.",TraitDescriptionPsyche:"Your psyche must be unleashed to use abilities that have the psyche trait, and they end automatically when your unleashed psyche subsides.",TraitDescriptionPsychic:"This indicates abilities from the psychic class.",TraitDescriptionRadiation:"A dangerous, typically poisonous emission typically originating from radioactive minerals.",TraitDescriptionRage:"You must be raging to use abilities with the rage trait, and they end automatically when you stop raging.",TraitDescriptionRange:"These attacks will either list a finite range or a range increment, which follows the normal rules for range increments.",TraitDescriptionRangedTrip:"This weapon can be used to Trip with the Athletics skill at a distance up to the weapon's first range increment. The skill check takes a -2 circumstance penalty. You can add the weapon's item bonus to attack rolls as a bonus to the check. As with using a melee weapon to trip, a ranged trip doesn't deal any damage when used to Trip.",TraitDescriptionRanger:"This indicates abilities from the ranger class.",TraitDescriptionRare:"This rarity indicates that a rules element is very difficult to find in the game world. A rare feat, spell, item or the like is available to players only if the GM decides to include it in the game, typically through discovery during play. Creatures with this trait are rare. They typically can't be summoned. The DC of Recall Knowledge checks related to these creatures is increased by 5.",TraitDescriptionRatfolk:"A creature with this trait is a member of the ratfolk ancestry.",TraitDescriptionRazing:"Razing weapons are particularly good at damaging objects, structures, and vehicles. Whenever you deal damage to an object (including shields and animated objects), structure, or vehicle with a razing weapon, the object takes an amount of additional damage equal to double the number of weapon damage dice.",TraitDescriptionReach:"Natural attacks with this trait can be used to attack creatures up to the listed distance away instead of only adjacent creatures. Weapons with this trait are long and can be used to attack creatures up to 10 feet away instead of only adjacent creatures. For creatures that already have reach with the limb or limbs that wield the weapon, the weapon increases their reach by 5 feet.",TraitDescriptionReckless:"Actions with the reckless trait run the risk of the pilot losing control of a vehicle. When performing a reckless action, the pilot must first attempt an appropriate piloting check to keep control of the vehicle.",TraitDescriptionRecovery:"Recovery weapons are thrown weapons designed to return to the thrower when they miss the target. When you make an unsuccessful thrown Strike with this weapon, it flies back to your hand after the Strike is complete, allowing you to try again. If your hands are full when the weapon returns, it falls to the ground in your space.",TraitDescriptionReflection:"A creature with this trait has the reflection versatile heritage. Reflections are beings who are copies of living people, whether through cloning, planar duplication, or another mechanism. An ability with this trait can be used or selected only by reflections.",TraitDescriptionRelic:"An item with the relic trait grows in power with its wielder.",TraitDescriptionReload:"While all weapons need some amount of time to get into position, many ranged weapons also need to be loaded and reloaded. This entry indicates how many Interact actions it takes to reload such weapons. This can be 0 if drawing ammunition and firing the weapon are part of the same action. If an item takes 2 or more actions to reload, the GM determines whether they must be performed together as an activity, or you can spend some of those actions during one turn and the rest during your next turn.",TraitDescriptionRepeating:"A repeating weapon is typically a type of crossbow that has a shorter reload time. These weapons can't be loaded with individual bolts like other crossbows; instead, they require a magazine of specialized ammunition to be loaded into a special slot. Once that magazine is in place, the ammunition is automatically loaded each time the weapon is cocked to fire, reducing its reload to the value in its reload entry (typically 0). When the ammunition runs out, a new magazine must be loaded, which requires a free hand and 3 Interact actions (to remove the old magazine, retrieve the new magazine, and slot the new magazine in place). These actions don't need to be consecutive.",TraitDescriptionResonant:"This weapon can channel energy damage. You gain the Conduct Energy free action while wielding a resonant weapon.",TraitDescriptionRevelation:"Effects with this trait see things as they truly are.",TraitDescriptionRogue:"This indicates abilities from the rogue class.",TraitDescriptionSaggorak:"Ancient dwarven blacksmiths in Saggorak designed a series of spectacularly powerful runes. Only someone with legendary proficiency in Crafting, or a well-versed dwarven crafter from the city of Kovlar, can apply, transfer, or remove a rune with the Saggorak trait. Because of their considerable power, all Saggorak runes take up two property rune slots, and consequently they can be applied only to armor and weapons with at least a +2 potency rune.",TraitDescriptionSanctified:"If you are holy or unholy, your sanctified actions and spells gain the same trait.",TraitDescriptionScatter:"This weapon fires a cluster of pellets in a wide spray. Scatter always has an area listed with it, indicating the radius of the spray. On a hit, the primary target of attacks with a scatter weapon take the listed damage, and the target and all other creatures within the listed radius around it take 1 point of splash damage per weapon damage die.",TraitDescriptionScroll:"A scroll contains a single spell you can cast without a spell slot.",TraitDescriptionScrying:"A scrying effect lets you see, hear, or otherwise get sensory information from a distance using a sensor or apparatus, rather than your own eyes and ears.",TraitDescriptionSecret:"The GM rolls the check for this ability in secret.",TraitDescriptionShadow:"This magic involves shadows or the energy of the Netherworld.",TraitDescriptionShieldThrow:"A shield with this trait is designed to be thrown as a ranged attack.",TraitDescriptionShisk:"Secretive humanoids covered in bony plumage that reside underground.",TraitDescriptionShoony:"A creature with this trait is a member of the shoony ancestry.",TraitDescriptionShove:"You can use this weapon to Shove with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Shove using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionSkeleton:"This undead is made by animating a dead creature's skeleton with void energy. An ability with this trait can be used or selected only by skeletons.",TraitDescriptionSkill:"A general feat with the skill trait improves your skills and their actions or gives you new actions for a skill. A feat with this trait can be selected when a class grants a skill feat or general feat. Archetype feats with the skill trait can be selected in place of a skill feat if you have that archetype's dedication feat.",TraitDescriptionSleep:"This effect can cause a creature to fall asleep or get drowsy.",TraitDescriptionSnare:"Traps typically made by rangers, snares follow special rules that allow them to be constructed quickly and used on the battlefield.",TraitDescriptionSocial:"Actions and abilities with the social trait can be used only while a vigilante is in their social identity.",TraitDescriptionSonic:"An effect with the sonic trait functions only if it makes sound, meaning it has no effect in an area of silence or in a vacuum. This is different from an auditory spell, which is effective only if the target can hear it. A sonic effect might deal sonic damage.",TraitDescriptionSorcerer:"This indicates abilities from the sorcerer class.",TraitDescriptionSpellgun:"The spellgun trait appears on items that can generate a magical effect that flies out like a bullet. You can make either a spell attack roll with a spellgun or a ranged attack roll using your proficiency with simple firearms. Spellguns have a range increment, which applies regardless of which type of attack roll you make. Though you can use your modifier for simple firearms, a spellgun isn't actually a firearm. You don't get the damage of a firearm Strike, nor other benefits like critical specialization. Similarly, you can't load or reload a spellgun, affix talismans to one, make a spellgun Strike as part of an action that lets you make a firearm Strike, and so on.",TraitDescriptionSpellheart:"Spellhearts are permanent items that work similarly to talismans. You affix a spellheart using the Affix a Spellheart activity, which is otherwise identical to Affix a Talisman. The limit of one talisman per item remains\u2014an item can have one spellheart or one talisman, not both. When casting a cantrip from a spellheart, you can use your own spell attack roll or spell DC if it's higher. Crafting a spellheart requires the spells the spellheart can cast. For example, a major five-feather wreath requires air walk, gale blast, and wall of wind.",TraitDescriptionSpellshape:"Spellshape actions tweak the properties of your spells. You must use a spellshape action directly before casting the spell you want to alter. If you use any action (including free actions and reactions) other than casting a spell directly after, you waste the benefits of the spellshape action. The benefit is also lost if your turn ends before you cast the spell. Any additional effects added by a spellshape action are part of the spell's effect, not of the spellshape action itself.",TraitDescriptionSplash:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 5 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSplash10:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 10 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSpirit:"Effects with this trait can affect creatures with spiritual essence and might deal spirit damage. A creature with this trait is defined by its spiritual essence. Spirit creatures often lack a material form.",TraitDescriptionSprite:"A family of diminutive winged fey with a strong connection to primal magic.",TraitDescriptionStaff:"This magic item holds spells of a particular theme and allows a spellcaster to cast additional spells by preparing the staff.",TraitDescriptionStance:"A stance is a general combat strategy that you enter by using an action with the stance trait, and that you remain in for some time. A stance lasts until you get knocked out, until its requirements (if any) are violated, until the encounter ends, or until you enter a new stance, whichever comes first. After you use an action with the stance trait, you can't use another one for 1 round. You can enter or be in a stance only in encounter mode.",TraitDescriptionSteam:"Items with this trait are powered by engines that boil water to produce steam and move their components.",TraitDescriptionStrix:"Winged humanoids, most of whom live in and around Cheliax.",TraitDescriptionStructure:"An item with the structure trait creates a magical building or other structure when activated. The item must be activated on a plot of land free of other structures. The structure adapts to the natural terrain, adopting the structural requirements for being built there. The structure adjusts around small features such as ponds or spires of rock, but it can't be created on water or other nonsolid surfaces. If activated on snow, sand dunes, or other soft surfaces with a solid surface underneath, the structure's foundation (if any) reaches the solid ground. If an item with this trait is activated on a solid but unstable surface, such as a swamp or an area plagued by tremors, roll a @Check[type:flat|dc:3] each day; on a failure, the structure begins to sink or collapse. The structure doesn't harm creatures within the area when it appears, and it can't be created within a crowd or in a densely populated area. Any creature inadvertently caught inside the structure when the item is activated ends up unharmed inside the complete structure and always has a clear path of escape. A creature inside the structure when the activation ends isn't harmed, and it lands harmlessly on the ground if it was on an upper level of the structure.",TraitDescriptionSubjectiveGravity:"On planes with this trait, all bodies of mass can be centers of gravity with the same amount of force, but only if a non-mindless creature wills it.",TraitDescriptionSubtle:"A spell with the subtle trait can be cast without incantations and doesn't have obvious manifestations.",TraitDescriptionSuli:"Sulis are planar scions descended from jann.",TraitDescriptionSummon:"Spells with the summon trait can conjure creatures, typically ones with a particular trait. Such creatures can be found in Monster Core and similar books. Unless noted otherwise, the creature must be common, it gains the summoned trait, and it must appear in an unoccupied space in range large enough to contain it. The highest level of creature the spell can summon depends on the rank of the spell, as listed below. The spell can still summon a creature of a lower level if you so choose. These rules apply only to spells that have the summon trait; other spells that call or conjure items or beings but that don't have the trait, like summon instrument, work as explained in the spell.",TraitDescriptionSummoned:"A creature called by a spell or effect gains the summoned trait. A summoned creature can't summon other creatures, create things of value, or cast spells that require a cost. It has the minion trait. If it tries to Cast a Spell of equal or higher rank than the spell that summoned it, it overpowers the summoning magic, causing its own spell to fail and the summon spell to end. Otherwise, the summoned creature uses the standard abilities for a creature of its kind. It generally attacks your enemies to the best of its ability. If you can communicate with it, you can attempt to command it, but the GM determines the degree to which it follows your commands. Immediately when you finish Casting the Spell, the summoned creature uses its 2 actions for that turn. A spawn or other creature generated from a summoned creature returns to its unaltered state (usually a corpse in the case of spawn) once the summoned creature is gone. If it's unclear what this state would be, the GM decides. Summoned creatures can be banished by various spells and effects. They are automatically banished if reduced to 0 Hit Points or if the spell that called them ends.",TraitDescriptionSummoner:"This indicates abilities from the Summoner class.",TraitDescriptionSwashbuckler:"This indicates abilities from the Swashbuckler class.",TraitDescriptionSweep:"This weapon makes wide sweeping or spinning attacks, making it easier to attack multiple enemies. When you attack with this weapon, you gain a +1 circumstance bonus to your attack roll if you already attempted to attack a different target this turn using this weapon.",TraitDescriptionSylph:"A type of geniekin descended from a being from the Plane of Air.",TraitDescriptionTalisman:"A talisman is a small object affixed to armor, a shield, or a weapon (called the affixed item). You must be wielding or wearing an item to activate a talisman attached to it. Once activated, a talisman burns out permanently.",TraitDescriptionTalos:"Taloses are planar scions descended from zuhras.",TraitDescriptionTandem:"Actions with this trait involve you and your eidolon acting in concert. You can't use a tandem action if either you or your eidolon can't act, if you haven't Manifested your Eidolon, or if you've Manifested your Eidolon in a way where it isn't a separate entity (such as with the Meld into Eidolon feat). Tandem actions often let both you and your eidolon take separate actions, but these must be actions taken separately by you and your eidolon; you can't use a tandem action to take another tandem action.",TraitDescriptionTattoo:"A tattoo is a type of item that is drawn or cut into a creature's skin and usually takes the form of images or symbols.",TraitDescriptionTea:"<p>Magic tea is a type of potion. It activates when you drink it, which uses it up. Magic tea has the potion and tea traits. When you craft a dose of magic tea, the raw materials you supply are in the form of unusual and costly tea leaves. The process of crafting magic tea includes infusing the leaves with magical reagents, purifying the water, and steeping the tea in the water, resulting in what's essentially a particularly delicious-tasting potion. You can activate magic tea with an Interact action as you drink it or feed it to another creature, as if it were a potion. You can also activate magic tea with a 10-minute activity that requires sterling tea ware (these artisan's tools can be shared by up to four people who take this activity simultaneously) to prepare the tea and then consume it or present it to someone during a short tea ceremony, after which the magic tea's effects begin; activating magic tea in this way enhances its effect, as detailed in each entry's Tea Ceremony.</p><p>Once you drink a dose of magic tea, you're temporarily immune to that particular type of magic tea for 24 hours.</p>",TraitDescriptionTech:"Items with this trait are associated with the technology of Numeria.",TraitDescriptionTelepathy:"A creature with telepathy can communicate mentally with creatures. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.",TraitDescriptionTeleportation:"Teleportation effects allow you to instantaneously move from one point in space to another. Teleportation does not usually trigger reactions based on movement.",TraitDescriptionTengu:"A creature with this trait is a member of the tengu ancestry. Tengus are humanoids who resemble birds. An ability with this trait can be used or selected only by tengus. An item with this trait is created and used by tengus.",TraitDescriptionTethered:"This weapon is attached to a length of rope or chain that allows you to retrieve it after it has left your hand. If you have a free hand while wielding this weapon, you can use an Interact action to pull the weapon back into your grasp after you have thrown it as a ranged attack or after it has been disarmed (unless it is being held by another creature).",TraitDescriptionThaumaturge:"This indicates abilities from the thaumaturge class.",TraitDescriptionThrown:"You can throw this weapon as a ranged attack. A thrown weapon adds your Strength modifier to damage just like a melee weapon does. When this trait appears on a melee weapon, it also includes the range increment.",TraitDescriptionTraining:"A training weapon is designed to be used when training an animal to participate in combat by identifying the target for the animal to attack. Striking a creature with a training weapon gives your animal companion or your bonded animal a +1 circumstance bonus to its next attack roll against that target.",TraitDescriptionTrap:"A hazard or item with this trait is constructed to hinder interlopers.",TraitDescriptionTrip:"You can use this weapon to Trip with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Trip using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionTrueName:"Certain spells, feats, and items have the true name trait. This trait means they require you to know a creature's true name to use them.",TraitDescriptionTwin:"These weapons are used as a pair, complementing each other. When you attack with a twin weapon, you add a circumstance bonus to the damage roll equal to the weapon's number of damage dice if you have previously attacked with a different weapon of the same type this turn. The weapons must be of the same type to benefit from this trait, but they don't need to have the same runes.",TraitDescriptionTwoHand:"This weapon can be wielded with two hands. Doing so changes its weapon damage die to the indicated value. This change applies to all the weapon's damage dice, such as those from striking runes.",TraitDescriptionUnarmed:"An unarmed attack uses your body rather than a manufactured weapon. An unarmed attack isn't a weapon, though it's categorized with weapons for weapon groups, and it might have weapon traits. Since it's part of your body, an unarmed attack can't be Disarmed. It also doesn't take up a hand, though a fist or other grasping appendage follows the same rules as a free-hand weapon.",TraitDescriptionUncommon:"Something of uncommon rarity requires special training or comes from a particular culture or part of the world. Some character choices give access to uncommon options, and the GM can choose to allow access for anyone. Less is known about uncommon creatures than common creatures. They typically can't be summoned. The DC of Recall Knowledge checks related to these creature is increased by 2.",TraitDescriptionUndead:"Once living, these creatures were infused after death with void energy and soul-corrupting unholy magic. When reduced to 0 Hit Points, an undead creature is destroyed. Undead creatures are damaged by vitality energy and are healed by void energy, and don't benefit from healing vitality effects.",TraitDescriptionUndine:"A type of geniekin descended from a being from the Plane of Water.",TraitDescriptionUnholy:"Effects with the unholy trait are tied to powerful magical forces of cruelty and sin. They often have stronger effects on holy creatures. Creatures with this trait are strongly devoted to unholy causes, and often have weakness to holy. If a creature with weakness to unholy uses an unholy item or effect, it takes damage from its weakness.",TraitDescriptionUnique:"A rules element with this trait is one-of-a-kind. The DC of Recall Knowledge checks related to creatures with this trait is increased by 10.",TraitDescriptionUnstable:"Unstable actions rely on experimental functions of your innovation that even you can't fully predict. After an unstable action is used on an innovation, using another one is dangerous.",TraitDescriptionVanara:"An inquisitive ancestry with primate-like features and prehensile tails.",TraitDescriptionVehicular:"A vehicular weapon is attached to a vehicle or worn by a mount and can typically only be wielded by the driver of the vehicle or the mount's primary rider. The driver or rider can control a vehicular weapon with the same hands they use to steer the vehicle or guide the mount. A vehicular weapon can be Disarmed by knocking the controls (typically reins for a mount or a steering device for a vehicle) out of the wielder's hands.",TraitDescriptionVersatile:"A versatile weapon can be used to deal a different type of damage than that listed in the Damage entry. This trait indicates the alternate damage type. For instance, a piercing weapon that is versatile S can be used to deal piercing or slashing damage. You choose the damage type each time you make an attack.",TraitDescriptionVirulent:"Afflictions with the virulent trait are harder to remove. You must succeed at two consecutive saves to reduce a virulent affliction's stage by 1. A critical success reduces a virulent affliction's stage by only 1 instead of by 2.",TraitDescriptionVishkanya:"An ancestry with snake-like features and powerful venom.",TraitDescriptionVisual:"A visual effect can affect only creatures that can see it. This applies only to visible parts of the effect, as determined by the GM.",TraitDescriptionVitality:"Effects with this trait heal living creatures with energy from the Forge of Creation, deal vitality energy damage to undead, or manipulate vitality energy.",TraitDescriptionVoid:"Effects with this trait heal undead creatures with void energy, deal void damage to living creatures, or manipulate void energy.",TraitDescriptionVolley:"This ranged weapon is less effective at close distances. Your attacks against targets that are at a distance within the range listed take a -2 penalty.",TraitDescriptionWand:"A wand contains a single spell which you can cast once per day.",TraitDescriptionWater:"Effects with the water trait either manipulate or conjure water. Those that manipulate water have no effect in an area without water. Creatures with this trait consist primarily of water or have a magical connection to the element.",TraitDescriptionWildHunt:"Creatures with the wild hunt trait are never below 14th level. They possess greater darkvision, greensight, planar acclimation, wild gaze, instinctive cooperation, weakness to cold iron, the ability to speak with plants and animals, and their own specific wild hunt link.",TraitDescriptionWitch:"This indicates abilities from the witch class.",TraitDescriptionWizard:"This indicates abilities from the wizard class.",TraitDescriptionWood:"Effects with the wood trait conjure or manipulate wood. Those that manipulate wood have no effect in an area without wood. Creatures with this trait consist primarily of wood or have a connection to magical wood.",TraitCenser:"Censer",TraitDetection:"Detection",TraitDeviant:"Deviant",TraitDevil:"Devil",TraitDhampir:"Dhampir",TraitDinosaur:"Dinosaur",TraitDisarm:"Disarm",TraitDisease:"Disease",TraitDiv:"Div",TraitDivine:"Divine",TraitDoubleBarrel:"Double Barrel",TraitDowntime:"Downtime",TraitDragon:"Dragon",TraitDream:"Dream",TraitDromaar:"Dromaar",TraitDrow:"Drow",TraitDrug:"Drug",TraitDruid:"Druid",TraitDuergar:"Duergar",TraitDuskwalker:"Duskwalker",TraitDwarf:"Dwarf",TraitEachRuneAppliedToASeparateItemThatHasPockets:"Each rune applied to a separate item that has pockets",TraitEarth:"Earth",TraitEidolon:"Eidolon",TraitElectricity:"Electricity",TraitElemental:"Elemental",TraitElf:"Elf",TraitElixir:"Elixir",TraitEmotion:"Emotion",TraitEnergy:"Energy",TraitEntrenchMelee:"Entrench Melee",TraitEntrenchRanged:"Entrench Ranged",TraitEnvironmental:"Environmental",TraitEsoterica:"Esoterica",TraitEtchedOntoABludgeoningWeapon:"Etched on Bludgeoning Weapon",TraitEtchedOntoAClanDagger:"Etched on Clan Dagger",TraitEtchedOntoAMeleeWeapon:"Etched on Melee Weapon",TraitEtchedOntoAMeleeWeaponMonk:"Etched onto a melee weapon with the monk trait",TraitEtchedOntoAPiercingOrSlashingMeleeWeapon:"Etched on Piercing/Slashing Melee Weapon",TraitEtchedOntoAPiercingOrSlashingWeapon:"Etched on Piercing/Slashing Weapon",TraitEtchedOntoAShield:"Etched onto a Shield",TraitEtchedOntoASlashingMeleeWeapon:"Etched on Slashing Melee Weapon",TraitEtchedOntoAThrownWeapon:"Etched on Thrown Weapon",TraitEtchedOntoAWeapon:"Etched onto a Weapon",TraitEtchedOntoAWeaponWOAnarchicRune:"Etched on Weapon w/o Anarchic Rune",TraitEtchedOntoAWeaponWOAxiomaticRune:"Etched on Weapon w/o Axiomatic Rune",TraitEtchedOntoAWeaponWOHolyRune:"Etched on Weapon that isn't Holy",TraitEtchedOntoAWeaponWOUnholyRune:"Etched on Weapon that isn't Unholy",TraitEtchedOntoArmor:"Etched onto Armor",TraitEtchedOntoHeavyArmor:"Etched onto Heavy Armor",TraitEtchedOntoLightArmor:"Etched onto Light Armor",TraitEtchedOntoLightMedNMArmor:"Etched on L/M Nonmetal Armor",TraitEtchedOntoMedHeavyArmor:"Etched onto Medium or Heavy Armor",TraitEtchedOntoMediumHeavyMetalArmor:"Etched onto Medium or Heavy Metal Armor",TraitEtchedOntoMetalArmor:"Etched onto Metal Armor",TraitEthereal:"Ethereal",TraitEvolution:"Evolution",TraitExpandable:"Expandable",TraitExploration:"Exploration",TraitExtradimensional:"Extradimensional",TraitFatal:"Fatal",TraitFatalAim:"Fatal Aim",TraitFatalAimD10:"Fatal Aim d10",TraitFatalAimD12:"Fatal Aim d12",TraitFatalD10:"Fatal d10",TraitFatalD12:"Fatal d12",TraitFatalD8:"Fatal d8",TraitFear:"Fear",TraitFetchling:"Fetchling",TraitFey:"Fey",TraitFiend:"Fiend",TraitFighter:"Fighter",TraitFigurehead:"Figurehead",TraitFinesse:"Finesse",TraitFinisher:"Finisher",TraitFinite:"Finite",TraitFire:"Fire",TraitFleshwarp:"Fleshwarp",TraitFlexible:"Flexible",TraitFlourish:"Flourish",TraitFocus:"Focus",TraitFocused:"Focused",TraitFoldaway:"Foldaway",TraitForce:"Force",TraitForceful:"Forceful",TraitFormian:"Formian",TraitFortune:"Fortune",TraitFreeHand:"Free-Hand",TraitFulu:"Fulu",TraitFungus:"Fungus",TraitGadget:"Gadget",TraitGanzi:"Ganzi",TraitGeneral:"General",TraitGenie:"Genie",TraitGeniekin:"Geniekin",TraitGhoran:"Ghoran",TraitGhost:"Ghost",TraitGhoul:"Ghoul",TraitGhul:"Ghul",TraitGiant:"Giant",TraitGnoll:"Gnoll",TraitGnome:"Gnome",TraitGoblin:"Goblin",TraitGolem:"Golem",TraitGoloma:"Goloma",TraitGrapple:"Grapple",TraitGremlin:"Gremlin",TraitGrimoire:"Grimoire",TraitGrioth:"Grioth",TraitGrippli:"Grippli",TraitGunslinger:"Gunslinger",TraitHag:"Hag",TraitHalcyon:"Halcyon",TraitHalfling:"Halfling",TraitHampering:"Hampering",TraitHantu:"Hantu",TraitHarnessed:"Harnessed",TraitHarrowCourt:"Harrow Court",TraitHaunt:"Haunt",TraitHealing:"Healing",TraitHefty2:"Hefty 2",TraitHeldOneHand:"Held in 1 hand",TraitHeldOneHandFreeStanding:"Held in 1 hand or free-standing",TraitHeldOneTwoHands:"Held in 1 or 2 hands",TraitHeldTwoHands:"Held in 2 hands",TraitHerald:"Herald",TraitHeritage:"Heritage",TraitHex:"Hex",TraitHindering:"Hindering",TraitHobgoblin:"Hobgoblin",TraitHoly:"Holy",TraitHryngar:"Hryngar",TraitHuman:"Human",TraitHumanoid:"Humanoid",TraitIfrit:"Ifrit",TraitIkeshti:"Ikeshti",TraitIllusion:"Illusion",TraitImpulse:"Impulse",TraitIncapacitation:"Incapacitation",TraitIncarnate:"Incarnate",TraitIncorporeal:"Incorporeal",TraitInevitable:"Inevitable",TraitInfused:"Infused",TraitInfusion:"Infusion",TraitIngested:"Ingested",TraitInhaled:"Inhaled",TraitInjection:"Injection",TraitInjury:"Injury",TraitInscribed:"Inscribed",TraitIntegrated1d6B:"Integrated 1d6 B",TraitIntegrated1d6P:"Integrated 1d6 P",TraitIntegrated1d6S:"Integrated 1d6 S",TraitIntegrated1d6SVersatileP:"Integrated 1d6 S (Versatile P)",TraitIntelligent:"Intelligent",TraitInteract:"Interact",TraitInventor:"Inventor",TraitInvested:"Invested",TraitInvestigator:"Investigator",TraitJousting:"Jousting",TraitJoustingD6:"Jousting d6",TraitKaiju:"Kaiju",TraitKami:"Kami",TraitKashrishi:"Kashrishi",TraitKickback:"Kickback",TraitKineticist:"Kineticist",TraitKingdom:"Kingdom",TraitKitsune:"Kitsune",TraitKobold:"Kobold",TraitKovintus:"Kovintus",TraitLaminar:"Laminar",TraitLaunching:"Launching",TraitLeshy:"Leshy",TraitLight:"Light",TraitLilu:"Lilu",TraitLineage:"Lineage",TraitLinguistic:"Linguistic",TraitLitany:"Litany",TraitLizardfolk:"Lizardfolk",TraitLocathah:"Locathah",TraitLozenge:"Lozenge",TraitMagic:"Magic",TraitMagical:"Magical",TraitMagus:"Magus",TraitManipulate:"Manipulate",TraitMechanical:"Mechanical",TraitMental:"Mental",TraitMerfolk:"Merfolk",TraitMetal:"Metal",TraitMindless:"Mindless",TraitMindshift:"Mindshift",TraitMinion:"Minion",TraitMisfortune:"Misfortune",TraitMisfortuneEffects:"Misfortune Effects",TraitMissive:"Missive",TraitModification:"Modification",TraitModular:"Modular B, P, or S",TraitMonitor:"Monitor",TraitMonk:"Monk",TraitMorlock:"Morlock",TraitMorph:"Morph",TraitMortic:"Mortic",TraitMounted:"Mounted",TraitMove:"Move",TraitMulticlass:"Multiclass",TraitMummy:"Mummy",TraitMunavri:"Munavri",TraitMutagen:"Mutagen",TraitMutant:"Mutant",TraitNaari:"Naari",TraitNagaji:"Nagaji",TraitNephilim:"Nephilim",TraitNindoru:"Nindoru",TraitNoisy:"Noisy",TraitNonlethal:"Nonlethal",TraitNymph:"Nymph",TraitOath:"Oath",TraitOccult:"Occult",TraitOil:"Oil",TraitOlfactory:"Olfactory",TraitOni:"Oni",TraitOoze:"Ooze",TraitOpen:"Open",TraitOracle:"Oracle",TraitOrc:"Orc",TraitOread:"Oread",TraitOverflow:"Overflow",TraitPaaridar:"Paaridar",TraitParry:"Parry",TraitPervasiveMagic:"Pervasive Magic",TraitPetitioner:"Petitioner",TraitPhantom:"Phantom",TraitPhysical:"Physical",TraitPiercing:"Piercing",TraitPlant:"Plant",TraitPoison:"Poison",TraitPolymorph:"Polymorph",TraitPonderous:"Ponderous",TraitPoppet:"Poppet",TraitPortable:"Portable",TraitPossession:"Possession",TraitPotion:"Potion",TraitPrecious:"Precious",TraitPrediction:"Prediction",TraitPress:"Press",TraitPrimal:"Primal",TraitProcessed:"Processed",TraitPropulsive:"Propulsive",TraitProtean:"Protean",TraitPsyche:"Psyche",TraitPsychic:"Psychic",TraitPsychopomp:"Psychopomp",TraitQlippoth:"Qlippoth",TraitRadiation:"Radiation",TraitRage:"Rage",TraitRakshasa:"Rakshasa",TraitRange:"Range",TraitRange10:"Range 10 feet",TraitRange100:"Range 100 feet",TraitRange110:"Range 110 feet",TraitRange120:"Range 120 feet",TraitRange130:"Range 130 feet",TraitRange140:"Range 140 feet",TraitRange15:"Range 15 feet",TraitRange150:"Range 150 feet",TraitRange160:"Range 160 feet",TraitRange170:"Range 170 feet",TraitRange180:"Range 180 feet",TraitRange190:"Range 190 feet",TraitRange20:"Range 20 feet",TraitRange200:"Range 200 feet",TraitRange210:"Range 210 feet",TraitRange220:"Range 220 feet",TraitRange230:"Range 230 feet",TraitRange240:"Range 240 feet",TraitRange25:"Range 25 feet",TraitRange250:"Range 250 feet",TraitRange260:"Range 260 feet",TraitRange270:"Range 270 feet",TraitRange280:"Range 280 feet",TraitRange290:"Range 290 feet",TraitRange30:"Range 30 feet",TraitRange300:"Range 300 feet",TraitRange310:"Range 310 feet",TraitRange320:"Range 320 feet",TraitRange40:"Range 40 feet",TraitRange5:"Range 5 feet",TraitRange50:"Range 50 feet",TraitRange500:"Range 500 feet",TraitRange60:"Range 60 feet",TraitRange70:"Range 70 feet",TraitRange80:"Range 80 feet",TraitRange90:"Range 90 feet",TraitRangeIncrement10:"Range Increment 10 feet",TraitRangeIncrement100:"Range Increment 100 feet",TraitRangeIncrement110:"Range Increment 110 feet",TraitRangeIncrement120:"Range Increment 120 feet",TraitRangeIncrement130:"Range Increment 130 feet",TraitRangeIncrement140:"Range Increment 140 feet",TraitRangeIncrement15:"Range Increment 15 feet",TraitRangeIncrement150:"Range Increment 150 feet",TraitRangeIncrement160:"Range Increment 160 feet",TraitRangeIncrement170:"Range Increment 170 feet",TraitRangeIncrement180:"Range Increment 180 feet",TraitRangeIncrement190:"Range Increment 190 feet",TraitRangeIncrement20:"Range Increment 20 feet",TraitRangeIncrement200:"Range Increment 200 feet",TraitRangeIncrement210:"Range Increment 210 feet",TraitRangeIncrement220:"Range Increment 220 feet",TraitRangeIncrement230:"Range Increment 230 feet",TraitRangeIncrement240:"Range Increment 240 feet",TraitRangeIncrement25:"Range Increment 25 feet",TraitRangeIncrement250:"Range Increment 250 feet",TraitRangeIncrement260:"Range Increment 260 feet",TraitRangeIncrement270:"Range Increment 270 feet",TraitRangeIncrement280:"Range Increment 280 feet",TraitRangeIncrement290:"Range Increment 290 feet",TraitRangeIncrement30:"Range Increment 30 feet",TraitRangeIncrement300:"Range Increment 300 feet",TraitRangeIncrement310:"Range Increment 310 feet",TraitRangeIncrement320:"Range Increment 320 feet",TraitRangeIncrement40:"Range Increment 40 feet",TraitRangeIncrement5:"Range Increment 5 feet",TraitRangeIncrement50:"Range Increment 50 feet",TraitRangeIncrement60:"Range Increment 60 feet",TraitRangeIncrement70:"Range Increment 70 feet",TraitRangeIncrement75:"Range Increment 75 feet",TraitRangeIncrement80:"Range Increment 80 feet",TraitRangeIncrement90:"Range Increment 90 feet",TraitRangedTrip:"Ranged Trip",TraitRanger:"Ranger",TraitRare:"Rare",TraitRatajin:"Ratajin",TraitRatfolk:"Ratfolk",TraitRazing:"Razing",TraitReach:"Reach",TraitReach0:"Reach 0 feet",TraitReach10:"Reach 10 feet",TraitReach100:"Reach 100 feet",TraitReach120:"Reach 120 feet",TraitReach1000:"Reach 1,000 feet",TraitReach15:"Reach 15 feet",TraitReach20:"Reach 20 feet",TraitReach200:"Reach 200 feet",TraitReach25:"Reach 25 feet",TraitReach30:"Reach 30 feet",TraitReach40:"Reach 40 feet",TraitReach50:"Reach 50 feet",TraitReach60:"Reach 60 feet",TraitReckless:"Reckless",TraitRecovery:"Recovery",TraitReflection:"Reflection",TraitRelic:"Relic",TraitReload:"Reload",TraitReload0:"Reload 0",TraitReload1:"Reload 1",TraitReload1Min:"Reload 1 min",TraitReload2:"Reload 2",TraitRepeating:"Repeating",TraitResonant:"Resonant",TraitRevelation:"Revelation",TraitRogue:"Rogue",TraitSaggorak:"Saggorak",TraitSahkil:"Sahkil",TraitSamsaran:"Samsaran",TraitSanctified:"Sanctified",TraitScatter:"Scatter",TraitScatter10:"Scatter 10",TraitScatter15:"Scatter 15",TraitScatter20:"Scatter 20",TraitScatter5:"Scatter 5",TraitScroll:"Scroll",TraitScrying:"Scrying",TraitSeaDevil:"Sea Devil",TraitSecret:"Secret",TraitSerpentfolk:"Serpentfolk",TraitSeugathi:"Seugathi",TraitSewnIntoClothing:"Sewn Into Clothing",TraitShabti:"Shabti",TraitShadow:"Shadow",TraitShieldThrow20:"Shield Throw 20 ft",TraitShieldThrow30:"Shield Throw 30 ft",TraitShisk:"Shisk",TraitShobhad:"Shobhad",TraitShoony:"Shoony",TraitShove:"Shove",TraitSiktempora:"Siktempora",TraitSkeleton:"Skeleton",TraitSkelm:"Skelm",TraitSkill:"Skill",TraitSkulk:"Skulk",TraitSlashing:"Slashing",TraitSleep:"Sleep",TraitSnare:"Snare",TraitSocial:"Social",TraitSonic:"Sonic",TraitSorcerer:"Sorcerer",TraitSoulbound:"Soulbound",TraitSpellDeflection:"Spell Deflection",TraitSpellgun:"Spellgun",TraitSpellheart:"Spellheart",TraitSpellshape:"Spellshape",TraitSpellshot:"Spellshot",TraitSpirit:"Spirit",TraitSplash:"Splash",TraitSplash10:"Splash 10 ft",TraitSporeborn:"Sporeborn",TraitSpriggan:"Spriggan",TraitSprite:"Sprite",TraitStaff:"Staff",TraitStamina:"Stamina",TraitStance:"Stance",TraitSteam:"Steam",TraitStheno:"Stheno",TraitStrix:"Strix",TraitStructure:"Structure",TraitSubjectiveGravity:"Subjective Gravity",TraitSubtle:"Subtle",TraitSuli:"Suli",TraitSummon:"Summon",TraitSummoned:"Summoned",TraitSummoner:"Summoner",TraitSwarm:"Swarm",TraitSwashbuckler:"Swashbuckler",TraitSweep:"Sweep",TraitSylph:"Sylph",TraitTalisman:"Talisman",TraitTalos:"Talos",TraitTandem:"Tandem",TraitTane:"Tane",TraitTanggal:"Tanggal",TraitTattoo:"Tattoo",TraitTattooedOnTheBody:"Tattooed on the Body",TraitTea:"Tea",TraitTech:"Tech",TraitTechnological:"Technological",TraitTelepathy:"Telepathy",TraitTeleportation:"Teleportation",TraitTengu:"Tengu",TraitTethered:"Tethered",TraitThaumaturge:"Thaumaturge",TraitThrown:"Thrown",TraitThrown10:"Thrown 10 ft.",TraitThrown100:"Thrown 100 ft.",TraitThrown15:"Thrown 15 ft.",TraitThrown20:"Thrown 20 ft.",TraitThrown200:"Thrown 200 ft.",TraitThrown30:"Thrown 30 ft.",TraitThrown40:"Thrown 40 ft.",TraitThrown60:"Thrown 60 ft.",TraitThrown80:"Thrown 80 ft.",TraitTime:"Time",TraitTitan:"Titan",TraitTouched:"Touched",TraitTraining:"Training",TraitTrap:"Trap",TraitTrip:"Trip",TraitTroll:"Troll",TraitTroop:"Troop",TraitTrueName:"True Name",TraitTwin:"Twin",TraitTwoHand:"Two-Hand",TraitTwoHandD10:"Two-Hand d10",TraitTwoHandD12:"Two-Hand d12",TraitTwoHandD6:"Two-Hand d6",TraitTwoHandD8:"Two-Hand d8",TraitUnarmed:"Unarmed",TraitUncommon:"Uncommon",TraitUndead:"Undead",TraitUndine:"Undine",TraitUnholy:"Unholy",TraitUnique:"Unique",TraitUnstable:"Unstable",TraitUntyped:"Untyped",TraitUrdefhan:"Urdefhan",TraitVampire:"Vampire",TraitVanara:"Vanara",TraitVehicular:"Vehicular",TraitVelstrac:"Velstrac",TraitVersatile:"Versatile",TraitVersatileAcid:"Versatile Acid",TraitVersatileB:"Versatile B",TraitVersatileCold:"Versatile Cold",TraitVersatileElectricity:"Versatile Electricity",TraitVersatileFire:"Versatile Fire",TraitVersatileForce:"Versatile Force",TraitVersatileP:"Versatile P",TraitVersatilePoison:"Versatile Poison",TraitVersatileS:"Versatile S",TraitVersatileSonic:"Versatile Sonic",TraitVersatileSpirit:"Versatile Spirit",TraitVersatileVitality:"Versatile Vitality",TraitVersatileVoid:"Versatile Void",TraitVersatileX:"Versatile {x}",TraitVigilante:"Vigilante",TraitVirulent:"Virulent",TraitVishkanya:"Vishkanya",TraitVisual:"Visual",TraitVitality:"Vitality",TraitVoid:"Void",TraitVolley:"Volley",TraitVolley20:"Volley 20 ft.",TraitVolley30:"Volley 30 ft.",TraitVolley50:"Volley 50 ft.",TraitVorpalFear:"Vorpal Fear",TraitWand:"Wand",TraitWater:"Water",TraitWayang:"Wayang",TraitWeapons:"Weapons",TraitWerecreature:"Werecreature",TraitWight:"Wight",TraitWildHunt:"Wild Hunt",TraitWitch:"Witch",TraitWizard:"Wizard",TraitWood:"Wood",TraitWorn:"Worn",TraitWornAmulet:"Worn Amulet",TraitWornAndAttachedToTwoWeapons:"Worn and Attached to Two Weapons",TraitWornAnklets:"Worn Anklets",TraitWornArmbands:"Worn Armbands",TraitWornBackpack:"Worn Backpack",TraitWornBarding:"Worn Barding",TraitWornBelt:"Worn Belt",TraitWornBeltPouch:"Worn Belt Pouch",TraitWornBoots:"Worn Boots",TraitWornBracelet:"Worn Bracelet",TraitWornBracers:"Worn Bracers",TraitWornCap:"Worn Cap",TraitWornCape:"Worn Cape",TraitWornCirclet:"Worn Circlet",TraitWornCloak:"Worn Cloak",TraitWornClothing:"Worn Clothing",TraitWornCollar:"Worn Collar",TraitWornCrown:"Worn Crown",TraitWornEpaulet:"Worn Epaulets",TraitWornEyeglasses:"Worn Eyeglasses",TraitWornEyepiece:"Worn Eyepiece",TraitWornFootwear:"Worn Footwear",TraitWornGarment:"Worn Garment",TraitWornGloves:"Worn Gloves",TraitWornHeadwear:"Worn Headwear",TraitWornHorseshoes:"Worn Horseshoes",TraitWornMask:"Worn Mask",TraitWornNecklace:"Worn Necklace",TraitWornOnBelt:"Worn on Belt",TraitWornOnWrists:"Worn on Wrists",TraitWornOrOneHand:"Worn or Held in One Hand",TraitWornRing:"Worn Ring",TraitWornSaddle:"Worn Saddle",TraitWornSandles:"Worn Sandles",TraitWornShoes:"Worn Shoes",TraitWornUnderArmor:"Worn Under Light Armor or Clothes",TraitWraith:"Wraith",TraitWyrwood:"Wyrwood",TraitXulgath:"Xulgath",TraitZombie:"Zombie",Traits:"Traits",TraitsLabel:"Traits",Trap:"Trap",TravelSpeed:{Days:"Days",DetectBeforeRunningIntoIt:"Notice Everything in Advance",DetectEverything:"Notice Everything",DetectionMode:"Detection Mode",DifficultTerrain:"Difficult Terrain Speed",Distance:"Distance",ExplorationActivities:{AvoidNotice:"Avoid Notice",CoverTracks:"Cover Tracks",Defend:"Defend",DetectMagic:"Detect Magic",HalfSpeed:"Other (Half Speed)",Investigate:"Investigate",None:"None (Full Speed)",RepeatASpell:"Repeat a Spell",Scout:"Scout",Search:"Search",Track:"Track"},ExplorationActivity:"Exploration Activity",ExplorationSpeed:"Exploration Speed",Feet:"Feet",FeetAcronym:"ft",GreaterDifficultTerrain:"Greater Difficult Terrain Speed",HexplorationActivities:"Hexploration Activities",Hours:"Hours",HoursPerDay:"Hours Spent Traveling Per Day",HustleMinutes:"Minutes Spent Hustling Per Day",Journey:"Journey",Label:"Travel Speed",Miles:"Miles",Name:"Name",None:"Full Speed",NormalTerrain:"Normal Terrain Speed",PartySpeed:"Party Speed",Speed:"Speed",TerrainSlowdown:"Terrain Speed",Title:"Travel Duration Calculator (Alpha)",TravelDuration:"Travel Duration",Weeks:"Weeks"},TrickMagicItemPopup:{InvalidActor:"Only a character or NPC can use Trick Magic Item.",Label:"Select a skill to use with Trick Magic Item.",Title:"Trick Magic Item"},UI:{applyDamage:{by:"by",damaged:"damaged for ",healed:"healed for ",shieldActive:"and their {shield} gets ",shieldInActive:"gets"},noDamageInfoForOutcome:"No damage information for outcome {outcome}.",shiftModifyDamageLabel:"Amount",shiftModifyDamageTitle:"Adjust Damage",shiftModifyHealingTitle:"Adjust Healing"},UUID:{Label:"UUID",SourceId:"Source ID"},UnitPriceLabel:"Unit price",UnitedPaizoWorkers:{PFSNote:'Note for Pathfinder Society players: In support of UPW, merchandise purchased from the union store will count in the Online PFS region for the <span class="hover" title="When you use a Hero Point to reroll a check, add a +1 circumstance bonus to the reroll">Promotional Vestments</a> boon.',ReleaseIntro:"Redmond, WA (October 14th, 2021) \u2014 Today, the workers at Paizo, Inc - publisher of the Pathfinder and Starfinder roleplaying games - are announcing their formation of the United Paizo Workers union (UPW), with the Communication Workers of America's CODE-CWA project. This union is the first of its kind in the tabletop roleplaying games industry.",Title:"Announcement: United Paizo Workers"},UnprepareItemTitle:"Unprepare Item",UpdateLabelUniversal:"Update",Usage:"Usage",UserSettings:{DarkvisionFilter:{Hint:"Add a (usually monochrome) filter when viewing a scene through the sight of a creature with darkvision",Label:"Darkvision Filter"}},ValueLabel:"Value",WeaknessesLabel:"Weaknesses",Weapon:{Base:{adze:"Adze","air-repeater":"Air Repeater",aklys:"Aklys","alchemical-bomb":"Alchemical Bomb","alchemical-crossbow":"Alchemical Crossbow","aldori-dueling-sword":"Aldori Dueling Sword",arbalest:"Arbalest",arquebus:"Arquebus","asp-coil":"Asp Coil",atlatl:"Atlatl","axe-musket":"Axe Musket","barricade-buster":"Barricade Buster","bastard-sword":"Bastard Sword","battle-axe":"Battle Axe","battle-lute":"Battle Lute","battle-saddle":"Battle Saddle","bec-de-corbin":"Bec de Corbin","big-boom-gun":"Big Boom Gun","black-powder-knuckle-dusters":"Black Powder Knuckle Dusters","bladed-diabolo":"Bladed Diabolo","bladed-gauntlet":"Bladed Gauntlet","bladed-hoop":"Bladed Hoop","bladed-scarf":"Bladed Scarf",blowgun:"Blowgun","blowgun-darts":"Blowgun Darts",blunderbuss:"Blunderbuss","bo-staff":"Bo Staff","boarding-axe":"Boarding Axe","boarding-pike":"Boarding Pike",bola:"Bola",boomerang:"Boomerang","bow-staff":"Bow Staff","breaching-pike":"Breaching Pike",broadspear:"Broadspear","butchering-axe":"Butchering Axe","butterfly-sword":"Butterfly Sword",buugeng:"Buugeng","cane-pistol":"Cane Pistol","chain-sword":"Chain Sword",chakram:"Chakram",chakri:"Chakri","clan-dagger":"Clan Dagger","clan-pistol":"Clan Pistol",claw:"Claw","claw-blade":"Claw Blade",club:"Club","coat-pistol":"Coat Pistol","combat-grapnel":"Combat Grapnel","combat-lure":"Combat Lure","composite-longbow":"Composite Longbow","composite-shortbow":"Composite Shortbow","corset-knife":"Corset Knife","crescent-cross":"Crescent Cross",crossbow:"Crossbow",dagger:"Dagger","dagger-pistol":"Dagger Pistol",daikyu:"Daikyu","dancers-spear":"Dancer's Spear",dandpatta:"Dandpatta",dart:"Dart",dogslicer:"Dogslicer",donchak:"Donchak","double-barreled-musket":"Double-Barreled Musket","double-barreled-pistol":"Double-Barreled Pistol","dragon-mouth-pistol":"Dragon Mouth Pistol","dueling-pistol":"Dueling Pistol","dueling-spear":"Dueling Spear","dwarven-dorn-dergar":"Dwarven Dorn-Dergar","dwarven-scattergun":"Dwarven Scattergun","dwarven-war-axe":"Dwarven War Axe",earthbreaker:"Earthbreaker","elven-branched-spear":"Elven Branched Spear","elven-curve-blade":"Elven Curve Blade","explosive-dogslicer":"Explosive Dogslicer","exquisite-sword-cane":"Exquisite Sword Cane","exquisite-sword-cane-sheath":"Exquisite Sword Cane Sheath",falcata:"Falcata",falchion:"Falchion",fangwire:"Fangwire",fauchard:"Fauchard","feng-huo-lun":"Feng Huo Lun","fighting-fan":"Fighting Fan","fighting-stick":"Fighting Stick","filchers-fork":"Filcher's Fork","fire-lance":"Fire Lance","fire-poi":"Fire Poi",fist:"Fist",flail:"Flail",flingflenser:"Flingflenser","flintlock-musket":"Flintlock Musket","flintlock-pistol":"Flintlock Pistol","flying-talon":"Flying Talon",flyssa:"Flyssa","forked-bipod":"Forked Bipod","frying-pan":"Frying Pan",gada:"Gada",gaff:"Gaff",gakgung:"Gakgung",gauntlet:"Gauntlet","gauntlet-bow":"Gauntlet Bow","gill-hook":"Gill Hook",glaive:"Glaive","gnome-amalgam-musket":"Gnome Amalgam Musket","gnome-flickmace":"Gnome Flickmace","gnome-hooked-hammer":"Gnome Hooked Hammer",greataxe:"Greataxe",greatclub:"Greatclub",greatpick:"Greatpick",greatsword:"Greatsword","griffon-cane":"Griffon Cane",guisarme:"Guisarme","gun-sword":"Gun Sword",halberd:"Halberd","halfling-sling-staff":"Halfling Sling Staff","hammer-gun":"Hammer Gun","hand-adze":"Hand Adze","hand-cannon":"Hand Cannon","hand-crossbow":"Hand Crossbow","harmona-gun":"Harmona Gun",harpoon:"Harpoon",hatchet:"Hatchet","heavy-crossbow":"Heavy Crossbow","hongali-hornbow":"Hongali Hornbow","hook-sword":"Hook Sword",horsechopper:"Horsechopper","injection-spear":"Injection Spear",javelin:"Javelin",jaws:"Jaws",jezail:"Jezail","jiu-huan-dao":"Jiu Huan Dao","juggling-club":"Juggling Club",kalis:"Kalis",kama:"Kama",karambit:"Karambit",katana:"Katana",katar:"Katar",khakkhara:"Khakkhara",khopesh:"Khopesh","knuckle-duster":"Knuckle Duster",kris:"Kris",kukri:"Kukri",kusarigama:"Kusarigama",lance:"Lance",lancer:"Lancer",leiomano:"Leiomano","light-hammer":"Light Hammer","light-mace":"Light Mace","light-pick":"Light Pick","lion-scythe":"Lion Scythe","long-air-repeater":"Long Air Repeater","long-hammer":"Long Hammer",longbow:"Longbow",longspear:"Longspear",longsword:"Longsword",mace:"Mace","mace-multipistol":"Mace Multipistol",machete:"Machete","main-gauche":"Main-Gauche",mambele:"Mambele",maul:"Maul","meteor-hammer":"Meteor Hammer",mikazuki:"Mikazuki","mithral-tree":"Mithral Tree","monkeys-fist":"Monkey's Fist",morningstar:"Morningstar",naginata:"Naginata",nightstick:"Nightstick","nine-ring-sword":"Nine-Ring Sword",nodachi:"Nodachi",nunchaku:"Nunchaku","ogre-hook":"Ogre Hook","orc-knuckle-dagger":"Orc Knuckle Dagger","orc-necksplitter":"Orc Necksplitter",panabas:"Panabas",pepperbox:"Pepperbox","phalanx-piercer":"Phalanx Piercer",pick:"Pick","piercing-wind":"Piercing Wind","piranha-kiss":"Piranha Kiss",poi:"Poi",polytool:"Polytool","probing-cane":"Probing Cane",ranseur:"Ranseur",rapier:"Rapier","rapier-pistol":"Rapier Pistol","reinforced-wheels":"Reinforced Wheels","repeating-crossbow":"Repeating Crossbow","repeating-hand-crossbow":"Repeating Hand Crossbow","repeating-heavy-crossbow":"Repeating Heavy Crossbow","rhoka-sword":"Rhoka Sword","rope-dart":"Rope Dart","rotary-bow":"Rotary Bow",rungu:"Rungu",sai:"Sai",sansetsukon:"Sansetsukon",sap:"Sap","sawtooth-saber":"Sawtooth Saber",scimitar:"Scimitar",scizore:"Scizore","scorpion-whip":"Scorpion Whip",scourge:"Scourge",scythe:"Scythe","shauth-lash":"Shauth Lash",shears:"Shears","shield-bash":"Shield Bash","shield-boss":"Shield Boss","shield-bow":"Shield Bow","shield-pistol":"Shield Pistol","shield-spikes":"Shield Spikes","shobhad-longrifle":"Shobhad Longrifle",shortbow:"Shortbow",shortsword:"Shortsword",shuriken:"Shuriken",sickle:"Sickle","sickle-saber":"Sickle-saber","slide-pistol":"Slide Pistol",sling:"Sling","sling-bullets":"Sling Bullets",spear:"Spear","spiked-chain":"Spiked Chain","spiked-gauntlet":"Spiked Gauntlet","spiral-rapier":"Spiral Rapier","spoon-gun":"Spoon Gun",spraysling:"Spraysling",staff:"Staff",starknife:"Starknife","stiletto-pen":"Stiletto Pen",sukgung:"Sukgung","sun-sling":"Sun Sling",switchscythe:"Switchscythe","sword-cane":"Sword Cane",talwar:"Talwar","tamchal-chakram":"Tamchal Chakram","taw-launcher":"Taw Launcher","tekko-kagi":"Tekko-kagi","temple-sword":"Temple Sword","tengu-gale-blade":"Tengu Gale Blade","thorn-whip":"Thorn whip","three-peaked-tree":"Three Peaked Tree","three-section-naginata":"Three-Section Naginata","throwing-knife":"Throwing Knife","thunder-sling":"Thunder Sling",thundermace:"Thundermace",tonfa:"Tonfa","tri-bladed-katar":"Tri-bladed Katar","tricky-pick":"Tricky Pick",trident:"Trident",triggerbrand:"Triggerbrand",urumi:"Urumi",visap:"Visap",wakizashi:"Wakizashi","war-flail":"War Flail","war-lance":"War Lance","war-razor":"War Razor",warhammer:"Warhammer","wheel-blades":"Wheel Blades","wheel-spikes":"Wheel Spikes",whip:"Whip","whip-claw":"Whip Claw","whip-staff":"Whip Staff","wish-blade":"Wish Blade","wish-knife":"Wish Knife","wooden-taws":"Wooden Taws",wrecker:"Wrecker","wrist-launcher":"Wrist Launcher",zulfikar:"Zulfikar"}},WeaponAbilityLabel:"Weapon Ability",WeaponBaseDamageTitle:"This section configures the base damage for the weapon. Additional die from Striking runes should not be added here and instead configured in the Weapon Runes section above.",WeaponBaseLabel:"Base",WeaponBonusAttackLabel:"Bonus Attack",WeaponBonusDamageLabel:"Bonus Damage",WeaponCustomDamageLabel:"Additional Custom Damage",WeaponCustomDamageTitle:"This section adds any custom damage that is not covered by the Rune system. The Strike Effect and Critical Effect attributes are not currently used in the system and are informational only.",WeaponDamageLabel:"Base Damage",WeaponGroupAxe:"Axe",WeaponGroupBomb:"Bomb",WeaponGroupBow:"Bow",WeaponGroupBrawling:"Brawling",WeaponGroupClub:"Club",WeaponGroupCrossbow:"Crossbow",WeaponGroupDart:"Dart",WeaponGroupFirearm:"Firearm",WeaponGroupFlail:"Flail",WeaponGroupHammer:"Hammer",WeaponGroupKnife:"Knife",WeaponGroupLabel:"Group",WeaponGroupPick:"Pick",WeaponGroupPolearm:"Polearm",WeaponGroupShield:"Shield",WeaponGroupSling:"Sling",WeaponGroupSpear:"Spear",WeaponGroupSword:"Sword",WeaponGroups:"Weapon Groups",WeaponHands1:"One",WeaponHands1Plus:"One Plus",WeaponHands2:"Two",WeaponMAPDefaultOption:"Default (uses Agile trait if present)",WeaponMAPLabel:"Multiple Attack Penalty",WeaponPotencyRune1:"Weapon Potency (+1)",WeaponPotencyRune2:"Weapon Potency (+2)",WeaponPotencyRune3:"Weapon Potency (+3)",WeaponPotencyRune4:"Weapon Potency (+4)",WeaponPropertyCriticalDamageLabel:"Critical Damage",WeaponPropertyCriticalEffectLabel:"Critical Effect",WeaponPropertyRune:{ancestralEchoing:{Name:"Ancestral Echoing"},anchoring:{Name:"Anchoring",Note:{criticalSuccess:"If you critically hit a target with an anchoring weapon, the weapon casts <em>@UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor}</em> on the target (@Check[type:will|dc:27|name:Anchoring Rune], counteract modifier [[/r 1d20+17 # Anchoring Rune Counteract Check]]{+17})."}},ashen:{Name:"Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:25] save."}},astral:{Name:"Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:26] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. An astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to astral weapons. Incorporeal creatures can touch, hold, and wield astral weapons (unlike most physical objects)."}},authorized:{Name:"Authorized"},bane:{Name:"Bane"},bloodbane:{Name:"Bloodbane"},bloodthirsty:{Name:"Bloodthirsty",Note:{criticalSuccess:"When you critically hit a target that's taking @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR]{Drained 1}."}},brilliant:{Name:"Brilliant",Note:{criticalSuccess:"On a critical hit, the target must succeed at a @Check[type:fortitude|dc:29|name:Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round."}},called:{Name:"Called"},coating:{Name:"Coating"},conducting:{Name:"Conducting"},corrosive:{Name:"Corrosive",Note:{criticalSuccess:"On a critical hit, the target's armor (if any) takes [[/r 3d6[acid] #Corrosive Rune]]{3d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead."}},crushing:{Name:"Crushing",Note:{criticalSuccess:"When you critically hit a target with this weapon, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.zNHvhwHsC8ckhKVp]{Effect: Crushing}"}},cunning:{Name:"Cunning"},dancing:{Name:"Dancing"},decaying:{Name:"Decaying"},deathdrinking:{Name:"Deathdrinking"},demolishing:{Name:"Demolishing"},disrupting:{Name:"Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},earthbinding:{Name:"Earthbinding"},energizing:{Name:"Energizing"},extending:{Name:"Extending"},fanged:{Name:"Fanged"},fearsome:{Name:"Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}."}},flaming:{Name:"Flaming",Note:{criticalSuccess:"On a critical hit, you deal an additional [[/r 1d10[persistent,fire]]]."}},flurrying:{Name:"Flurrying"},frost:{Name:"Frost",Note:{criticalSuccess:"On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:24|name:Frost Rune] save."}},ghostTouch:{Name:"Ghost Touch",Note:"The weapon can harm creatures without physical form. A ghost touch weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to ghost touch weapons. Incorporeal creatures can touch, hold, and wield ghost touch weapons (unlike most physical objects)."},giantKilling:{Name:"Giant-Killing",Note:{criticalSuccess:"On a critical hit with this weapon, the giant is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},greaterAnchoring:{Name:"Greater Anchoring",Note:{criticalSuccess:"When you critically hit a target with a weapon with the anchoring rune, the weapon casts 8th-rank <em>@UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor}</em> on the target (@Check[type:will|dc:38|name:Greater Anchoring Rune], counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28}), except that if the target critically succeeds at its Will save, instead of having no effect, the <em>dimensional anchor</em> lasts for 1 round.",success:"When you hit a target with the weapon but don't critically hit, the target is affected by 4th-rank <em>@UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor}</em> for 1 round without a save (counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28})."}},greaterAshen:{Name:"Greater Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:35] save. On a critical failure, the effect lasts for 1 minute."}},greaterAstral:{Name:"Greater Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:36] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. A greater astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to greater astral weapons. Incorporeal creatures can touch, hold, and wield greater astral weapons (unlike most physical objects). The spirit damage granted by a greater astral weapon ignores any spirit resistance the target has."}},greaterBloodbane:{Name:"Greater Bloodbane"},greaterBrilliant:{Name:"Greater Brilliant",Note:{criticalSuccess:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance. On a critical hit, the target must succeed at a @Check[type:fortitude|dc:41|name:Greater Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round.",success:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance."}},greaterCorrosive:{Name:"Greater Corrosive",Note:{criticalSuccess:"The acid damage dealt by this weapon ignores the target's acid resistance. On a critical hit, the target's armor (if any) takes [[/r 6d6[acid]]]{6d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead.",success:"The acid damage dealt by this weapon ignores the target's acid resistance."}},greaterCrushing:{Name:"Greater Crushing",Note:{criticalSuccess:"Your critical hits leave the target @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 2} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.czdEHtLsrUcZxSDx]{Effect: Crushing (Greater)}"}},greaterDecaying:{Name:"Greater Decaying"},greaterDisrupting:{Name:"Greater Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead creature is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} and @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} as long as it has the persistent damage from this rune."}},greaterExtending:{Name:"Greater Extending"},greaterFanged:{Name:"Greater Fanged"},greaterFearsome:{Name:"Greater Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}."}},greaterFlaming:{Name:"Greater Flaming",Note:{criticalSuccess:"Fire damage dealt by this weapon (including the persistent fire damage) ignores the target's fire resistance.",success:"Fire damage dealt by this weapon ignores the target's fire resistance."}},greaterFrost:{Name:"Greater Frost",Note:{criticalSuccess:"Cold damage dealt by this weapon ignores the target's cold resistance. On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:34|name:Greater Frost Rune] save.",success:"Cold damage dealt by this weapon ignores the target's cold resistance."}},greaterGiantKilling:{Name:"Greater Giant-Killing",Note:{success:"Mental damage dealt by this weapon ignores the target's mental resistance.",criticalSuccess:"On a critical hit with this weapon, the giant must attempt a @Check[type:fortitude|dc:34] with the following effects.<br /><strong>Critical Success</strong> The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn.<br /><strong>Success</strong> The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn and takes @Damage[1d10[mental]].<br /><strong>Failure</strong> The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} for the next minute and takes @Damage[2d10[mental]].<br/><strong>Critical Failure</strong> The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 4} for the next minute and takes @Damage[4d10[mental]]."}},greaterHauling:{Name:"Greater Hauling"},greaterImpactful:{Name:"Greater Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:37|name:Greater Impactful Rune] save or be pushed 10 feet away from you."}},greaterRooting:{Name:"Greater Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (<span data-pf2-action="escape" data-pf2-glyph="A" data-pf2-dc="28">Escape DC 28</span>) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},greaterShock:{Name:"Greater Shock",Note:{criticalSuccess:"Electricity damage dealt by this weapon ignores the targets electricity resistance (and the other creatures' on a critical hit). On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target.",success:"Electricity damage dealt by this weapon ignores the target's electricity resistance."}},greaterThundering:{Name:"Greater Thundering",Note:{criticalSuccess:"Sonic damage dealt by this weapon ignores the target's sonic resistance. On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:34|name:Greater Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} permanently.",success:"Sonic damage dealt by this weapon ignores the target's sonic resistance."}},grievous:{Name:"Grievous",Note:{Axe:"You can damage a third creature, with the same restrictions.",Bow:"The Athletics check to pull the missile free is DC 20.",Brawling:"The target takes a -4 circumstance penalty to its save.",Club:"You can knock the target up to 15 feet away.",Dart:"The base persistent bleed damage increases to [[/r 2d6[bleed]]].",Flail:"You move the target 5 feet. You can't move it away from you, but you can move it in another direction of your choice.",Hammer:"You can also knock the target 5 feet away from you.",Knife:"The target takes a -5-foot status penalty to its Speed while it has the @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}.",Pick:"The extra damage from the critical specialization effect increases to 4 per weapon damage die.",Polearm:"You can move the target up to 10 feet.",Shield:"You can knock the target up to 10 feet away.",Sling:"The target also takes a -10-foot status penalty to its Speed for 1 round if it fails the save.",Spear:"The clumsy condition lasts for 2 rounds.",Sword:"The target is off-guard until the end of your next turn."}},hauling:{Name:"Hauling"},holy:{Name:"Holy",Note:{criticalSuccess:`(<span class="pf2-icon">R</span> command; once per day)<br /><strong>Trigger</strong> You critically succeed at an attack roll against an evil creature with the weapon<br /><strong>Effect</strong> You regain HP equal to double the evil creature's level. This is a good, vitality, healing effect.`}},hopeful:{Name:"Hopeful",Note:{criticalSuccess:"On a critical hit with this weapon, you inspire your comrades, pushing them to fight harder and stand for your shared convictions. Allies within 30 feet that share at least one alignment component with you gain a +1 status bonus to attack rolls until the end of your next turn."}},hooked:{Name:"Hooked",Note:{criticalSuccess:"If a hooked weapon normally has the trip trait, you can attempt to Trip a foe as a reaction when you critically hit it with the hooked weapon."}},impactful:{Name:"Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:27|name:Impactful Rune] save or be pushed 5 feet away from you."}},impossible:{Name:"Impossible"},keen:{Name:"Keen"},kinWarding:{Name:"Kin-Warding"},majorRooting:{Name:"Major Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (<span data-pf2-action="escape" data-pf2-glyph="A" data-pf2-dc="34">Escape DC 34</span>) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},merciful:{Name:"Merciful"},majorFanged:{Name:"Major Fanged"},pacifying:{Name:"Pacifying"},returning:{Name:"Returning",Note:"When you make a thrown Strike with this weapon, it flies back to your hand after the Strike is complete. If your hands are full when the weapon returns, it falls to the ground in your space."},rooting:{Name:"Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (<span data-pf2-action="escape" data-pf2-glyph="A" data-pf2-dc="23">Escape DC 23</span>) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},serrating:{Name:"Serrating"},shifting:{Name:"Shifting"},shock:{Name:"Shock",Note:{criticalSuccess:"On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target."}},speed:{Name:"Speed"},spellStoring:{Name:"Spell-Storing"},swarming:{Name:"Swarming"},thundering:{Name:"Thundering",Note:{criticalSuccess:"On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:24|name:Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} for 1 minute (or 1 hour on a critical failure)."}},trueRooting:{Name:"True Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (<span data-pf2-action="escape" data-pf2-glyph="A" data-pf2-dc="41">Escape DC 41</span>) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},underwater:{Name:"Underwater"},unholy:{Name:"Unholy",Note:{criticalSuccess:'(<span class="pf2-icon">R</span> command; once per day)<br /><strong>Trigger</strong> You critically succeed at an attack roll against a good creature with the weapon<br /><strong>Effect</strong> The target takes @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage} equal to 1d8 per weapon damage die of the etched weapon.'}},vorpal:{Name:"Vorpal",Note:{criticalSuccess:`(<span class="pf2-icon">R</span> envision (death, incapacitation))<br /><strong>Trigger</strong> You roll a natural 20 on a Strike with the weapon, critically succeed, and deal slashing damage. The target must have a head<br /><strong>Effect</strong> The target must succeed at a @Check[type:fortitude|dc:37|traits:death,incapacitation|name:Vorpal Rune] save or be decapitated. This kills any creature except ones that don't require a head to live. For creatures with multiple heads, this usually kills the creature only if you sever its last head.`}},wounding:{Name:"Wounding"}},WeaponPropertyStrikeDamageLabel:"Strike Damage",WeaponPropertyStrikeEffectLabel:"Strike Effect",WeaponRange10:"10 ft.",WeaponRange100:"100 ft.",WeaponRange120:"120 ft.",WeaponRange140:"140 ft.",WeaponRange150:"150 ft.",WeaponRange180:"180 ft.",WeaponRange20:"20 ft.",WeaponRange200:"200 ft",WeaponRange240:"240 ft.",WeaponRange30:"30 ft.",WeaponRange300:"300 ft.",WeaponRange40:"40 ft.",WeaponRange50:"50 ft.",WeaponRange60:"60 ft.",WeaponRange70:"70 ft.",WeaponRange80:"80 ft.",WeaponRange90:"90 ft.",WeaponRangeMelee:"Melee",WeaponRangeN:"{range} ft.",WeaponRangeReach:"Reach",WeaponReloadLabel:"Reload Time",WeaponSpecialization:"Weapon Specialization",WeaponSplashDamageLabel:"Splash Damage",WeaponStrikeLabel:"Strike",WeaponTypeAdvanced:"Advanced Weapon",WeaponTypeMartial:"Martial Weapon",WeaponTypeSimple:"Simple Weapon",WeaponTypeSpecial:"Other Weapons",WeaponTypeUnarmed:"Unarmed Attack",Weight:"Weight",WorldClock:{AD:{Era:"AD"},AR:{Era:"AR",Months:{April:"Gozran",August:"Arodus",December:"Kuthona",February:"Calistril",January:"Abadius",July:"Erastus",June:"Sarenith",March:"Pharast",May:"Desnus",November:"Neth",October:"Lamashan",September:"Rova"},Weekdays:{Friday:"Fireday",Monday:"Moonday",Saturday:"Starday",Sunday:"Sunday",Thursday:"Oathday",Tuesday:"Toilday",Wednesday:"Wealday"}},Button:{AddOneDay:"1 Day",AddOneHour:"1 Hour",AddOneMinute:"1 Minute",AddOneRound:"1 Round",AddOneWeek:"1 Week",AddTenMinutes:"10 Minutes",Advance:"Advance",Retract:"Retract",TimeOfDay:{Advance:{Dawn:"Advance to Dawn",Dusk:"Advance to Dusk",Midnight:"Advance to Midnight",Noon:"Advance to Noon"},Retract:{Dawn:"Retract to Dawn",Dusk:"Retract to Dusk",Midnight:"Retract to Midnight",Noon:"Retract to Noon"}}},CE:{Era:"CE"},Date:"{weekday}, {day} of {month}, {year} {era}",IC:{Era:"IC"},Placeholder:"Number",Title:"World Clock"},condition:{blinded:{name:"Blinded",rules:"<p>You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a -4 status penalty to Perception checks. You are immune to visual effects. Blinded overrides dazzled.</p>",summary:"You're unable to see."},broken:{name:"Broken",rules:`<p>Broken is a condition that affects objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses-with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: -1 for broken light armor, -2 for broken medium armor, or -3 for broken heavy armor.</p>
|
|
<p>A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth.</p>
|
|
<p>If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.</p>`,summary:"This item can't be used for its normal function until repaired."},clumsy:{name:"Clumsy",rules:"<p>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.</p>",summary:"You can't move as easily or gracefully as usual."},concealed:{name:"Concealed",rules:`<p>While you are concealed from a creature, such as in a thick fog, you are difficult for that creature to see. You can still be observed, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|dc:5] when targeting you with an attack, spell, or other effect.</p>
|
|
<p>Area effects aren't subject to this flat check. If the check fails, the attack, spell, or effect doesn't affect you.</p>`,summary:"Fog or similar obscuration makes you difficult to see and target."},confused:{name:"Confused",rules:`<p>You don't have your wits about you, and you attack wildly. You are off-guard, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.<p></p>You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so that a target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.</p>
|
|
<p>Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|dc:11] to recover from your confusion and end the condition.</p>`,summary:"You attack indiscriminately."},controlled:{name:"Controlled",rules:"<p>Someone else is making your decisions for you, usually because you're being commanded or magically dominated. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even Delay. The controller usually does not have to spend their own actions when controlling you.</p>",summary:"Another creature determines your actions."},dazzled:{name:"Dazzled",rules:"<p>Your eyes are overstimulated. If vision is your only precise sense, all creatures and objects are concealed from you.</p>",summary:"Everything is concealed to you."},deafened:{name:"Deafened",rules:"<p>You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a -2 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action with the auditory trait, you must succeed at a @Check[type:flat|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects.</p>",summary:"You're unable to hear."},doomed:{name:"Doomed",rules:`<p>Your life is ebbing away, bringing you ever closer to death. Some powerful spells and evil creatures can inflict the doomed condition on you. Doomed always includes a value. The maximum dying value at which you die is reduced by your doomed value. For example, if you were doomed 1, you would die upon reaching dying 3 instead of dying 4. If your maximum dying value is ever reduced to 0, you instantly die. When you die, you're no longer doomed.</p>
|
|
<p>Your doomed value decreases by 1 each time you get a full night's rest.</p>`,summary:"With your soul in peril, you are now closer to death."},drained:{name:"Drained",rules:`<p>When a creature successfully drains you of blood or life force, you become less healthy. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you're hit by an effect that inflicts drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.</p>
|
|
<p>Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.</p>`,summary:"Blood loss or something similar has leached your vitality."},dying:{name:"Dying",rules:`<p>You are bleeding out or otherwise at death's door. While you have this condition, you are unconscious. Dying always includes a value, and if it ever reaches dying 4, you die. If you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.</p>
|
|
<p>If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the wounded 1 condition, or increase your wounded condition value by 1 if you already have that condition.</p>`,summary:"You're slipping closer to death."},encumbered:{name:"Encumbered",rules:"<p>You are carrying more weight than you can manage. While you're encumbered, you're clumsy 1 and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.</p>",summary:"You're carrying more weight than you can manage."},enfeebled:{name:"Enfeebled",rules:"<p>You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.</p>",summary:"Your strength has been sapped away."},fascinated:{name:"Fascinated",rules:"<p>You are compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a -2 status penalty to Perception and skill checks, and you can't use actions with the concentrate trait unless they or their intended consequences are related to the subject of your fascination (as determined by the GM). For instance, you might be able to Seek and Recall Knowledge about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.</p>",summary:"You are compelled to focus your attention on something."},fatigued:{name:"Fatigued",rules:`<p>You're tired and can't summon much energy. You take a -1 status penalty to AC and saving throws. While exploring, you can't choose an exploration activity.</p>
|
|
<p>You recover from fatigue after a full night's rest.</p>`,summary:"Your defenses are lower and you can't focus while exploring."},"off-guard":{name:"Off-Guard",rules:`<p>You're distracted or otherwise unable to focus your full attention on defense. You take a -2 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you universally off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them; for example, many effects simply say "The target is off-guard."</p>`,summary:"You're unable to defend yourself to your full capability."},fleeing:{name:"Fleeing",rules:"<p>You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or caster that gave you the condition, though some effects might define something else as the source. You can't Delay or Ready while fleeing.</p>",summary:"You must run away."},friendly:{name:"Friendly",rules:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is friendly to a character likes that character. The character can attempt to make a Request of a friendly creature, and the friendly creature is likely to agree to a simple and safe request that doesn't cost it much to fulfill. If the character or one of their allies uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.</p>",summary:"An NPC with this condition has a good attitude toward you."},frightened:{name:"Frightened",rules:"<p>You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.</p>",summary:"Fear makes you less capable of attacking and defending."},grabbed:{name:"Grabbed",rules:"<p>You're held in place by another creature, giving you the off-guard and immobilized conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.</p>",summary:"A creature, object, or magic holds you in place."},group:{attitudes:"Attitudes",death:"Death and Dying",detection:"Degrees of Detection",senses:"Senses"},helpful:{name:"Helpful",rules:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable Requests from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character or one of their allies uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.</p>",summary:"An NPC with this condition wants to assist you."},hidden:{name:"Hidden",rules:`<p>While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to Hide. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed. A creature you're hidden from is off-guard to you, and it must succeed at a @Check[type:flat|dc:11] when targeting you with an attack, spell, or other effect or it fails affect you. Area effects aren't subject to this flat check.</p>
|
|
<p>A creature might be able to use the Seek action to try to observe you.</p>`,summary:"A creature you're hidden from knows your location but can't see you."},hostile:{name:"Hostile",rules:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept Requests from the character.</p>",summary:"An NPC with this condition wants to harm you."},immobilized:{name:"Immobilized",rules:"<p>You can't use any action with the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.</p>",summary:"You can't move."},indifferent:{name:"Indifferent",rules:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.</p>",summary:"An NPC with this condition doesn't have a strong opinion about you."},invisible:{name:"Invisible",rules:"<p>While invisible, you can't be seen. You're undetected to everyone. Creatures can Seek to attempt to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become hidden to that creature until you Sneak to become undetected again. If you become invisible while someone can already see you, you start out hidden to the observer (instead of undetected) until you successfully Sneak. You can't become observed while invisible except via special abilities or magic.</p>",summary:"Creatures can't see you."},observed:{name:"Observed",rules:"<p>Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to Hide, it can become hidden or undetected instead of observed. If you have another precise sense instead of or in addition to sight, you might be able to observe a creature or object using that sense instead. You can observe a creature only with precise senses. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed.</p>",summary:"You're in plain view."},paralyzed:{name:"Paralyzed",rules:"<p>Your body is frozen in place. You have the off-guard condition and can't act except to Recall Knowledge and use actions that require only the use of your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving your body, so you can't Seek while paralyzed.</p>",summary:"Your body is frozen in place."},"persistent-damage":{name:"Persistent Damage",rules:'<p>Persistent damage comes from effects like acid, being on fire, or many other situations. It appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.</p>',summary:"You keep taking damage every round."},petrified:{name:"Petrified",rules:"<p>You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When you're turned back into flesh, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.</p>",summary:"You've been turned to stone."},prone:{name:"Prone",rules:`<p>You're lying on the ground. You are off-guard and take a -2 circumstance penalty to attack rolls. The only move actions you can use while you're prone are Crawl and Stand. Standing up ends the prone condition. You can Take Cover while prone to hunker down and gain cover against ranged attacks, even if you don't have an object to get behind, gaining a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).</p>
|
|
<p>If you would be knocked prone while you're Climbing or Flying, you fall. You can't be knocked prone when Swimming.</p>`,summary:"You're lying on the ground and are easier to attack."},quickened:{name:"Quickened",rules:"<p>You gain 1 additional action at the start of your turn each round. Many effects that make you quickened specify the types of actions you can use with this additional action. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.</p>",summary:"You get an extra action each turn."},restrained:{name:"Restrained",rules:"<p>You're tied up and can barely move, or a creature has you pinned. You have the off-guard and immobilized conditions, and you can't use any actions with the attack or manipulate traits except to attempt to Escape or Force Open your bonds. Restrained overrides grabbed.</p>",summary:"You're tied up and can't move, or a grappling creature has you pinned."},sickened:{name:"Sickened",rules:`<p>You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything-including elixirs and potions-while sickened.</p>
|
|
<p>You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).</p>`,summary:"You're sick to your stomach."},slowed:{name:"Slowed",rules:"<p>You have fewer actions. Slowed always includes a value. When you regain your actions at the start of your turn, reduce the number of actions you regain by your slowed value. Because slowed has its effect at the start of your turn, you don't immediately lose actions if you become slowed during your turn.</p>",summary:"You lose actions each turn."},stunned:{name:"Stunned",rules:`<p>You've become senseless. You can't act while stunned. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions (such as at the start of your turn), reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead of a value, such as "stunned for 1 minute." In this case, you lose all your actions for the listed duration.</p>
|
|
<p>Stunned overrides slowed. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.</p>`,summary:"You can't use actions."},stupefied:{name:"Stupefied",rules:"<p>Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack rolls, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to Cast a Spell while stupefied, the spell is disrupted unless you succeed at a flat check with a DC equal to 5 + your stupefied value.</p>",summary:"You can't access your full mental faculties, and you have trouble casting spells."},unconscious:{name:"Unconscious",rules:`<p>You're sleeping, or you've been knocked out. You can't act. You take a -4 status penalty to AC, Perception, and Reflex saves, and you have the blinded and off-guard conditions. When you gain this condition, you fall prone and drop items you are wielding or holding unless the effect states otherwise or the GM determines you're in a position in which you wouldn't.</p>
|
|
<p>If you're unconscious because you're dying, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more via healing, you lose the dying and unconscious conditions and can act normally on your next turn.</p>
|
|
<p>If you are unconscious and at 0 Hit Points, but not dying, you naturally return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you receive healing during this time, you lose the unconscious condition and can act normally on your next turn.</p>
|
|
<p>If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways. Each causes you to lose the unconscious condition.</p><ul><li>You take damage, provided the damage doesn't reduce you to 0 Hit Points. If the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.</li><li>You receive healing, other than the natural healing you get from resting.</li><li>Someone shakes you awake with an Interact action.</li><li>There's loud noise going on around you-though this isn't automatic. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some magical effects make you sleep so deeply that they don't allow you to attempt this Perception check.</li><li>If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.</ul>`,summary:"You're asleep or knocked out."},undetected:{name:"Undetected",rules:`<p>When you are undetected by a creature, that creature cannot see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is off-guard to you.</p>
|
|
<p>A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a hidden creature (requiring a @Check[type:flat|dc:11]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square.</p>
|
|
<p>A creature can use the Seek action to try to find you.</p>`,summary:"A creature you're undetected by doesn't know where you are."},unfriendly:{name:"Unfriendly",rules:"<p>This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is unfriendly to a character dislikes and specifically distrusts that character. The unfriendly creature won't accept Requests from the character.</p>",summary:"An NPC with this condition doesn't like you."},unnoticed:{name:"Unnoticed",rules:"<p>If you are unnoticed by a creature, that creature has no idea you are present at all. When you're unnoticed, you're also undetected by the creature. This condition matters for abilities that can be used only against targets totally unaware of your presence.</p>",summary:"A creature is entirely unaware you're present."},wounded:{name:"Wounded",rules:`<p>You have been seriously injured. If you lose the dying condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.</p>
|
|
<p>The wounded condition ends if someone successfully restores Hit Points to you with Treat Wounds, or if you are restored to full Hit Points and rest for 10 minutes.</p>`,summary:"You've been brought back from the brink of death but haven't fully recovered."}},identification:{DisplayDetails:"Display Details",Identified:"Identified",Identify:"Identify Item",IdentifyAlchemyDCs:"Identify Alchemy DCs",IdentifyGenericDCs:"Identify Generic DCs",IdentifyMagicDCs:"Identify Magic DCs",IsIdentified:"Identified?",MisidentifiedItem:"Misidentified {item}",Misidentify:"Misidentify Item",MystificationStatus:"Mystification status",Mystify:"Mystify Item",PostSkillsToChat:"Post skill checks to chat",PostSkillsToChatText:"Identify item: Skill checks",TraitGMNote:"Note: this trait is hidden from players.",Unidentified:"Unidentified",UnidentifiedDescription:"The nature of this {item} is unclear.",UnidentifiedHint:"Change the basic details seen by players when this item is unidentified.",UnidentifiedItem:"Unusual {item}",UnidentifiedType:{Amulet:"Amulet",Anklets:"Anklets",Armbands:"Armbands",Backpack:"Backpack",Belt:"Belt",Book:"Book",Bracers:"Bracers",Circlet:"Circlet",Cloak:"Cloak",Collar:"Collar",Epaulets:"Epaulets",Eyepiece:"Eyepiece",Garment:"Garment",Gloves:"Gloves",Headwear:"Headwear",Horseshoes:"Horseshoes",Liquid:"Liquid",Mask:"Mask",Necklace:"Necklace",Object:"Object",Ring:"Ring",Saddle:"Saddle",Shoes:"Shoes",Substance:"Substance",Tool:"Tool"}},loot:{BuySubtitle:"Buy item",DepositMessage:"{depositor} deposits {quantity} \xD7 {item} in {container}.",DepositSubtitle:"Deposit item",EditLootLabel:"Configure Loot?",GMSupervisionError:"A GM must be online in order to interact with {loot}.",GiveMessage:"{giver} gives {quantity} \xD7 {item} to {recipient}.",GiveSubtitle:"Give item",HiddenWhenEmpty:{Hint:"Hide this actor's token(s) when its inventory is empty.",Label:"Hidden When Empty"},InsufficientCurrencyError:"Insufficient currency for purchase by {buyer}",InsufficientFundsMessage:"{buyer} reaches for their coins but comes up short!",LootDescription:"Allows for distribution of coins across players",LootLabel:"Loot",LootMessage:"{looter} loots {quantity} \xD7 {item} off {corpse}.",LootNPCsLabel:"Loot Selected Tokens",LootNPCsPopupHeader:"Choose tokens to loot from",LootNamePlaceholder:"Loot",LootSubtitle:"Loot item",MerchantDescription:"Allows players to purchase items directly from the sheet",MerchantLabel:"Merchant",MoveLoot:"Move Items",MoveLootMessage:"How many items do you wish to move?",MoveLootPopupTitle:"Item Quantity",PartyStash:"the party stash",PermissionError:"A GM must be online in order to loot or stow an item.",PlantMessage:"{planter} plants {quantity} \xD7 {item} on {corpse}.",PlantSubtitle:"Plant Item",PurchaseLoot:"Purchase Items",PurchaseLootMessage:"How many items do you wish to purchase?",Quantity:"Quantity",SellMessage:"{seller} sells {quantity} \xD7 {item} to {buyer}.",SellSubtitle:"Sell item",SheetType:"Sheet Type",SplitCoinsLabel:"Distribute Coins",SplitCoinsPopupHeader:"Choose actors to receive a share",Stack:"Create new stack?",TakeMessage:"{taker} takes {quantity} \xD7 {item} from {container}.",TakeSubtitle:"Take item",TransferMessage:"{transferrer} moves {quantity} \xD7 {item} from {fromContainer} to {toContainer}.",TransferSubtitle:"Transfer item"},ui:{armorEquipped:"Toggle wearing your equipment",equipmentInvested:"Toggle Investment",sell:"Sell",weaponEquipped:"Toggle holding your weapon"},vehicle:{BrokenThresholdShortLabel:"BT",CrewLabel:"Crew",CurrentHPTitle:"Current Hitpoints",DescriptionHeading:"Description",HardnessLabel:"Hardness",HardnessShortLabel:"Hard.",LevelN:"Vehicle {level}",MaxHPTitle:"Maximum Hitpoints",NamePlaceholder:"Vehicle",PassengersLabel:"Passengers",PilotingCheckLabel:"Piloting Check",PropertyDescriptionCollisionDC:"The vehicle's DC for saving throws to mitigate damage.",PropertyDescriptionCollisionDamage:"The vehicle's collision damage. Unless otherwise stated, collisions deal bludgeoning damage.",PropertyDescriptionCrew:"The crew members required to operate the vehicle.",PropertyDescriptionPassengers:"The number of passengers the vehicle is typically configured to carry, if any.",PropertyDescriptionPilotingCheck:"This entry lists the skills that can be used for piloting checks while operating the vehicle. Some skills may increase the DC; these list the DC adjustment in parentheses following the skill name.",PropertyDescriptionPrice:"Vehicle's Price. This does not include creatures for pulling a vehicle, materials needed to power the vehicle, or the cost of rowers.",PropertyDescriptionSpace:"Vehicle's dimensions, not including any creatures pulling the vehicle.",PropertyDescriptionSpeed:"The vehicle's Speeds, each followed by the propulsion type for that Speed in parentheses. A pulled vehicle indicates the number and size of the pulling creatures.",SpaceHighLabel:"Height",SpaceLongLabel:"Length",SpaceWideLabel:"Width",VehicleLevelLabel:"Vehicle",VehicleString:"Vehicle",collisionDCLabel:"Collision DC",collisionDamageLabel:"Collision Damage"}},SIDEBAR:{TabCombat:"Encounter Tracker"},TYPES:{Actor:{army:"Army",character:"Player Character",eidolon:"Eidolon",familiar:"Familiar",hazard:"Hazard",loot:"Loot",npc:"NPC",party:"Party",vehicle:"Vehicle"},Item:{action:"Ability",affliction:"Affliction",ancestry:"Ancestry",armor:"Armor",background:"Background",backpack:"Container",book:"Book",campaignFeature:"Campaign Feature",class:"Class",condition:"Condition",consumable:"Consumable",deity:"Deity",effect:"Effect",equipment:"Equipment",feat:"Feat/Feature",heritage:"Heritage",kit:"Kit",lore:"Lore Skill",melee:"NPC Attack",shield:"Shield",spell:"Spell",spellcastingEntry:"Spellcasting Entry",treasure:"Treasure",weapon:"Weapon"}}};const actorTypes={army:"TYPES.Actor.army",character:"TYPES.Actor.character",familiar:"TYPES.Actor.familiar",hazard:"TYPES.Actor.hazard",loot:"TYPES.Actor.loot",npc:"TYPES.Actor.npc",party:"TYPES.Actor.party",vehicle:"TYPES.Actor.vehicle"},abilities={str:"PF2E.AbilityStr",dex:"PF2E.AbilityDex",con:"PF2E.AbilityCon",int:"PF2E.AbilityInt",wis:"PF2E.AbilityWis",cha:"PF2E.AbilityCha"},senses={darkvision:"PF2E.Actor.Creature.Sense.Type.Darkvision",echolocation:"PF2E.Actor.Creature.Sense.Type.Echolocation",greaterDarkvision:"PF2E.Actor.Creature.Sense.Type.GreaterDarkvision",heatsight:"PF2E.Actor.Creature.Sense.Type.Heatsight",lifesense:"PF2E.Actor.Creature.Sense.Type.Lifesense",lowLightVision:"PF2E.Actor.Creature.Sense.Type.LowLightVision",motionsense:"PF2E.Actor.Creature.Sense.Type.Motionsense",scent:"PF2E.Actor.Creature.Sense.Type.Scent",seeInvisibility:"PF2E.Actor.Creature.Sense.Type.SeeInvisibility",spiritsense:"PF2E.Actor.Creature.Sense.Type.Spiritsense",thoughtsense:"PF2E.Actor.Creature.Sense.Type.Thoughtsense",tremorsense:"PF2E.Actor.Creature.Sense.Type.Tremorsense",wavesense:"PF2E.Actor.Creature.Sense.Type.Wavesense"},senseAcuity={imprecise:"PF2E.Actor.Creature.Sense.Acuity.Imprecise",precise:"PF2E.Actor.Creature.Sense.Acuity.Precise",vague:"PF2E.Actor.Creature.Sense.Acuity.Vague"},tokenHUDConditions={blinded:"PF2E.ConditionTypeBlinded",broken:"PF2E.ConditionTypeBroken",clumsy:"PF2E.ConditionTypeClumsy",concealed:"PF2E.ConditionTypeConcealed",confused:"PF2E.ConditionTypeConfused",controlled:"PF2E.ConditionTypeControlled",dazzled:"PF2E.ConditionTypeDazzled",deafened:"PF2E.ConditionTypeDeafened",doomed:"PF2E.ConditionTypeDoomed",drained:"PF2E.ConditionTypeDrained",dying:"PF2E.ConditionTypeDying",encumbered:"PF2E.ConditionTypeEncumbered",enfeebled:"PF2E.ConditionTypeEnfeebled",fascinated:"PF2E.ConditionTypeFascinated",fatigued:"PF2E.ConditionTypeFatigued",fleeing:"PF2E.ConditionTypeFleeing",frightened:"PF2E.ConditionTypeFrightened",grabbed:"PF2E.ConditionTypeGrabbed",hidden:"PF2E.ConditionTypeHidden",immobilized:"PF2E.ConditionTypeImmobilized",invisible:"PF2E.ConditionTypeInvisible","off-guard":"PF2E.ConditionTypeOffGuard",paralyzed:"PF2E.ConditionTypeParalyzed","persistent-damage":"PF2E.ConditionTypePersistent",petrified:"PF2E.ConditionTypePetrified",prone:"PF2E.ConditionTypeProne",quickened:"PF2E.ConditionTypeQuickened",restrained:"PF2E.ConditionTypeRestrained",sickened:"PF2E.ConditionTypeSickened",slowed:"PF2E.ConditionTypeSlowed",stunned:"PF2E.ConditionTypeStunned",stupefied:"PF2E.ConditionTypeStupefied",unconscious:"PF2E.ConditionTypeUnconscious",undetected:"PF2E.ConditionTypeUndetected",wounded:"PF2E.ConditionTypeWounded"},conditionTypes={...tokenHUDConditions,friendly:"PF2E.ConditionTypeFriendly",helpful:"PF2E.ConditionTypeHelpful",hostile:"PF2E.ConditionTypeHostile",indifferent:"PF2E.ConditionTypeIndifferent",malevolence:"PF2E.ConditionTypeMalevolence",observed:"PF2E.ConditionTypeObserved",unfriendly:"PF2E.ConditionTypeUnfriendly",unnoticed:"PF2E.ConditionTypeUnnoticed"},weaponCategories={simple:"PF2E.WeaponTypeSimple",martial:"PF2E.WeaponTypeMartial",advanced:"PF2E.WeaponTypeAdvanced",unarmed:"PF2E.WeaponTypeUnarmed"},baseArmorTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Armor.Base,(_v,slug)=>`PF2E.Item.Armor.Base.${slug}`),baseShieldTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Shield.Base,(_v,slug)=>`PF2E.Item.Shield.Base.${slug}`),baseWeaponTypes=mapValues$1(define_EN_JSON_default.PF2E.Weapon.Base,(_v,slug)=>`PF2E.Weapon.Base.${slug}`),equivalentWeapons={"composite-longbow":"longbow","composite-shortbow":"shortbow","big-boom-gun":"hand-cannon","spoon-gun":"hand-cannon"},preciousMaterialGrades={low:"PF2E.PreciousMaterialLowGrade",standard:"PF2E.PreciousMaterialStandardGrade",high:"PF2E.PreciousMaterialHighGrade"},meleeWeaponGroups={axe:"PF2E.WeaponGroupAxe",brawling:"PF2E.WeaponGroupBrawling",club:"PF2E.WeaponGroupClub",dart:"PF2E.WeaponGroupDart",flail:"PF2E.WeaponGroupFlail",hammer:"PF2E.WeaponGroupHammer",knife:"PF2E.WeaponGroupKnife",pick:"PF2E.WeaponGroupPick",polearm:"PF2E.WeaponGroupPolearm",shield:"PF2E.WeaponGroupShield",spear:"PF2E.WeaponGroupSpear",sword:"PF2E.WeaponGroupSword"},weaponGroups={...meleeWeaponGroups,bomb:"PF2E.WeaponGroupBomb",bow:"PF2E.WeaponGroupBow",crossbow:"PF2E.WeaponGroupCrossbow",firearm:"PF2E.WeaponGroupFirearm",sling:"PF2E.WeaponGroupSling"},sizeTypes={tiny:"PF2E.ActorSizeTiny",sm:"PF2E.ActorSizeSmall",med:"PF2E.ActorSizeMedium",lg:"PF2E.ActorSizeLarge",huge:"PF2E.ActorSizeHuge",grg:"PF2E.ActorSizeGargantuan"},featCategories={ancestry:"PF2E.FeatTypeAncestry",ancestryfeature:"PF2E.FeatTypeAncestryfeature",class:"PF2E.FeatTypeClass",classfeature:"PF2E.FeatTypeClassfeature",skill:"PF2E.FeatTypeSkill",general:"PF2E.FeatTypeGeneral",bonus:"PF2E.FeatTypeBonus",pfsboon:"PF2E.FeatTypePfsboon",deityboon:"PF2E.FeatTypeDeityboon",curse:"PF2E.FeatTypeCurse"},creatureTypes=pick(creatureTraits,["aberration","animal","astral","beast","celestial","construct","dragon","dream","elemental","ethereal","fey","fiend","fungus","giant","humanoid","monitor","ooze","petitioner","plant","shadow","spirit","time","vitality","void","undead"]),consumableCategories=mapToObj(Array.from(CONSUMABLE_CATEGORIES),c=>[c,`PF2E.Item.Consumable.Category.${c}`]),deityDomains=mapToObj(Object.keys(define_EN_JSON_default.PF2E.Item.Deity.Domain),key=>{const label=`PF2E.Item.Deity.Domain.${key}.Label`,description=`PF2E.Item.Deity.Domain.${key}.Description`;return[sluggify(key),{label,description}]}),weaponReload={"-":"\u2014",0:"0",1:"1",2:"2",3:"3",10:"PF2E.Item.Weapon.Reload.OneMinute"};function notifyDeprecatedPath(configPath,locPath){foundry.utils.logCompatibilityWarning(`CONFIG.PF2E.${configPath} is deprecated. Use localization path ${locPath} directly instead.`,{since:"5.2.0",until:"6.0.0"})}__name(notifyDeprecatedPath,"notifyDeprecatedPath"),__name2(notifyDeprecatedPath,"notifyDeprecatedPath");const PF2ECONFIG={defaultPartyId:"xxxPF2ExPARTYxxx",chatDamageButtonShieldToggle:!1,statusEffects:{lastIconTheme:"default",iconDir:"systems/pf2e/icons/conditions/",conditions:tokenHUDConditions},levels:{1:"PF2E.Level1",2:"PF2E.Level2",3:"PF2E.Level3",4:"PF2E.Level4",5:"PF2E.Level5",6:"PF2E.Level6",7:"PF2E.Level7",8:"PF2E.Level8",9:"PF2E.Level9",10:"PF2E.Level10",11:"PF2E.Level11",12:"PF2E.Level12",13:"PF2E.Level13",14:"PF2E.Level14",15:"PF2E.Level15",16:"PF2E.Level16",17:"PF2E.Level17",18:"PF2E.Level18",19:"PF2E.Level19",20:"PF2E.Level20"},abilities,attributes:{get perception(){const locPath="PF2E.PerceptionLabel";return notifyDeprecatedPath("attributes.perception",locPath),locPath},get stealth(){const locPath="PF2E.StealthLabel";return notifyDeprecatedPath("attributes.stealth",locPath),locPath},get initiative(){const locPath="PF2E.InitiativeLabel";return notifyDeprecatedPath("attributes.initiative",locPath),locPath}},dcAdjustments:{"incredibly-easy":"PF2E.DCAdjustmentIncrediblyEasy","very-easy":"PF2E.DCAdjustmentVeryEasy",easy:"PF2E.DCAdjustmentEasy",normal:"PF2E.DCAdjustmentNormal",hard:"PF2E.DCAdjustmentHard","very-hard":"PF2E.DCAdjustmentVeryHard","incredibly-hard":"PF2E.DCAdjustmentIncrediblyHard"},checkDCs:configFromLocalization(define_EN_JSON_default.PF2E.Check.DC,"PF2E.Check.DC"),skills:{acr:"PF2E.SkillAcr",arc:"PF2E.SkillArc",ath:"PF2E.SkillAth",cra:"PF2E.SkillCra",dec:"PF2E.SkillDec",dip:"PF2E.SkillDip",itm:"PF2E.SkillItm",med:"PF2E.SkillMed",nat:"PF2E.SkillNat",occ:"PF2E.SkillOcc",prf:"PF2E.SkillPrf",rel:"PF2E.SkillRel",soc:"PF2E.SkillSoc",ste:"PF2E.SkillSte",sur:"PF2E.SkillSur",thi:"PF2E.SkillThi"},saves:{fortitude:"PF2E.SavesFortitude",reflex:"PF2E.SavesReflex",will:"PF2E.SavesWill"},savingThrowDefaultAttributes:{fortitude:"con",reflex:"dex",will:"wis"},currencies:{pp:"PF2E.CurrencyPP",gp:"PF2E.CurrencyGP",sp:"PF2E.CurrencySP",cp:"PF2E.CurrencyCP"},preciousMaterialGrades,preciousMaterials,accessoryPropertyRunes:{called:"PF2E.AccessoryPropertyRuneCalled",dragonsBreath:"PF2E.AccessoryPropertyRuneDragonsBreath",paired:"PF2E.AccessoryPropertyRunePaired",greaterPaired:"PF2E.AccessoryPropertyRuneGreaterPaired",majorPaired:"PF2E.AccessoryPropertyRuneMajorPaired",presentable:"PF2E.AccessoryPropertyRunePresentable",snagging:"PF2E.AccessoryPropertyRuneSnagging",softLanding:"PF2E.AccessoryPropertyRuneSoftLanding",spellBastion:"PF2E.AccessoryPropertyRuneSpellBastion",windCatcher:"PF2E.AccessoryPropertyRuneWindCatcher",greaterWindCatcher:"PF2E.AccessoryPropertyRuneGreaterWindCatcher"},damageTraits,damageTypes,damageRollFlavors,damageCategories,elementTraits,materialDamageEffects,resistanceTypes,stackGroups:{arrows:"PF2E.StackGroupArrows",blowgunDarts:"PF2E.StackGroupBlowgunDarts",bolts:"PF2E.StackGroupBolts",coins:"PF2E.StackGroupCoins",gems:"PF2E.StackGroupGems",rounds5:"PF2E.StackGroupRounds5",rounds10:"PF2E.StackGroupRounds10",slingBullets:"PF2E.StackGroupSlingBullets",sprayPellets:"PF2E.StackGroupSprayPellets",woodenTaws:"PF2E.StackGroupWoodenTaws"},weaknessTypes,weaponCategories,weaponGroups,meleeWeaponGroups,baseArmorTypes,baseShieldTypes,baseWeaponTypes,equivalentWeapons,weaponDescriptions:{club:"PF2E.WeaponDescriptionClub",knife:"PF2E.WeaponDescriptionKnife",brawling:"PF2E.WeaponDescriptionBrawling",spear:"PF2E.WeaponDescriptionSpear",sword:"PF2E.WeaponDescriptionSword",axe:"PF2E.WeaponDescriptionAxe",flail:"PF2E.WeaponDescriptionFlail",polearm:"PF2E.WeaponDescriptionPolearm",pick:"PF2E.WeaponDescriptionPick",hammer:"PF2E.WeaponDescriptionHammer",shield:"PF2E.WeaponDescriptionShield",dart:"PF2E.WeaponDescriptionDart",bow:"PF2E.WeaponDescriptionBow",sling:"PF2E.WeaponDescriptionSling",bomb:"PF2E.WeaponDescriptionBomb"},usages:{"affixed-to-a-creature":"PF2E.TraitAffixedToCreature","affixed-to-a-magical-staff":"PF2E.TraitAffixedToMagicalStaff","affixed-to-a-metal-weapon":"PF2E.TraitAffixedToAMetalWeapon","affixed-to-a-ranged-weapon":"PF2E.TraitAffixedToARangedWeapon","affixed-to-a-shield":"PF2E.TraitAffixedToAShield","affixed-to-a-shield-or-weapon":"PF2E.TraitAffixedToAShieldOrWeapon","affixed-to-a-thrown-weapon":"PF2E.TraitAffixedToThrownWeapon","affixed-to-a-two-handed-firearm-or-crossbow":"PF2E.TraitAffixedToATwoHandedFirearmOrCrossbow","affixed-to-an-innovation":"PF2E.TraitAffixedToInnovation","affixed-to-an-object-or-structure":"PF2E.TraitAffixedToObjectOrStructure","affixed-to-armor":"PF2E.TraitAffixedToArmor","affixed-to-medium-heavy-armor":"PF2E.TraitAffixedToMediumHeavyArmor","affixed-to-medium-heavy-metal-armor":"PF2E.TraitAffixedToMediumHeavyMetalArmor","affixed-to-armor-or-a-weapon":"PF2E.TraitAffixedToArmorOrAWeapon","affixed-to-armor-or-travelers-clothing":"PF2E.TraitAffixedToArmorOrTravelersClothing","affixed-to-crossbow-or-firearm":"PF2E.TraitAffixedToCrossbowOrFirearm","affixed-to-firearm":"PF2E.TraitAffixedToFirearm","affixed-to-firearm-with-a-reload-of-1":"PF2E.TraitAffixedToFirearmWithAReloadOf1","affixed-to-firearm-with-the-kickback-trait":"PF2E.TraitAffixedToFirearmWithTheKickbackTrait","affixed-to-ground-in-10-foot-radius":"PF2E.TraitAffixedToGroundIn10FtRadius","affixed-to-ground-in-20-foot-radius":"PF2E.TraitAffixedToGroundIn20FtRadius","affixed-to-harness":"PF2E.TraitAffixedToHarness","affixed-to-headgear":"PF2E.TraitAffixedToHeadgear","affixed-to-instrument":"PF2E.TraitAffixedToInstrument","affixed-to-load-bearing-wall-or-pillar":"PF2E.TraitAffixedToLoadBearingWallOrPillar","affixed-to-melee-weapon":"PF2E.TraitAffixedToMeleeWeapon","affixed-to-metal-weapon":"PF2E.TraitAffixedToMetalWeapon","affixed-to-object-structure-or-creature":"PF2E.TraitAffixedToStructureObjectOrCreature","affixed-to-the-ground":"PF2E.TraitAffixedToGround","affixed-to-unarmored-defense-item":"PF2E.TraitAffixedToUnarmoredItem","affixed-to-weapon":"PF2E.TraitAffixedToWeapon","applied-to-a-basket-bag-or-other-container":"PF2E.TraitAppliedToBasketBagOrContainer","applied-to-a-weapon":"PF2E.TraitAppliedToAWeapon","applied-to-a-wind-powered-vehicle":"PF2E.TraitAppliedToAWindPoweredVehicle","applied-to-a-non-injection-melee-weapon-piercing-damage":"PF2E.TraitAppliedToANoninjectionMeleePiercingWeapon","applied-to-any-item-of-light-or-negligible-bulk":"PF2E.TraitAppliedToAnyItemOfLightOrNegligibleBulk","applied-to-any-visible-article-of-clothing":"PF2E.TraitAppliedToAnyVisibleArticleOfClothing","applied-to-armor":"PF2E.TraitAppliedToArmor","applied-to-armor-or-unarmored-defense-clothing":"PF2E.TraitAppliedToArmorOrUnarmored","applied-to-belt-cape-cloak-or-scarf":"PF2E.TraitAppliedToBeltCapeCloakOrScarf","applied-to-boots-cape-cloak-or-umbrella":"PF2E.TraitAppliedToBootsCapeCloakOrUmbrella","applied-to-buckler-shield":"PF2E.TraitAppliedToBucklerShield","applied-to-dueling-cape-or-shield":"PF2E.TraitAppliedToDuelingCapeOrShield","applied-to-footwear":"PF2E.TraitAppliedToFootwear","applied-to-medium-heavy-armor":"PF2E.TraitAppliedToMediumHeavyArmor","applied-to-shield":"PF2E.TraitAppliedToShield","attached-to-a-thrown-weapon":"PF2E.TraitAttachedToAThrownWeapon","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm","attached-to-crossbow-or-firearm-firing-mechanism":"PF2E.TraitAttachedToCrossbowOrFirearmFiringMechanism","attached-to-crossbow-or-firearm-scope":"PF2E.TraitAttachedToCrossbowOrFirearmScope","attached-to-firearm":"PF2E.TraitAttachedToFirearm","attached-to-firearm-scope":"PF2E.TraitAttachedToFirearmScope","attached-to-ships-bow":"PF2E.TraitAttachedToShipsBow",bonded:"PF2E.TraitBonded",carried:"PF2E.TraitCarried","each-rune-applied-to-a-separate-item-that-has-pockets":"PF2E.TraitEachRuneAppliedToASeparateItemThatHasPockets","etched-onto-a-weapon":"PF2E.TraitEtchedOntoAWeapon","etched-onto-a-shield":"PF2E.TraitEtchedOntoAShield","etched-onto-armor":"PF2E.TraitEtchedOntoArmor","etched-onto-heavy-armor":"PF2E.TraitEtchedOntoHeavyArmor","etched-onto-light-armor":"PF2E.TraitEtchedOntoLightArmor","etched-onto-metal-armor":"PF2E.TraitEtchedOntoMetalArmor","etched-onto-clan-dagger":"PF2E.TraitEtchedOntoAClanDagger","etched-onto-lm-nonmetal-armor":"PF2E.TraitEtchedOntoLightMedNMArmor","etched-onto-med-heavy-armor":"PF2E.TraitEtchedOntoMedHeavyArmor","etched-onto-medium-heavy-metal-armor":"PF2E.TraitEtchedOntoMediumHeavyMetalArmor","etched-onto-bludgeoning-weapon":"PF2E.TraitEtchedOntoABludgeoningWeapon","etched-onto-melee-weapon":"PF2E.TraitEtchedOntoAMeleeWeapon","etched-onto-slashing-melee-weapon":"PF2E.TraitEtchedOntoASlashingMeleeWeapon","etched-onto-piercing-or-slashing-melee-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingMeleeWeapon","etched-onto-piercing-or-slashing-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingWeapon","etched-onto-weapon-wo-anarchic-rune":"PF2E.TraitEtchedOntoAWeaponWOAxiomaticRune","etched-onto-weapon-wo-axiomatic-rune":"PF2E.TraitEtchedOntoAWeaponWOAnarchicRune","etched-onto-weapon-wo-unholy-rune":"PF2E.TraitEtchedOntoAWeaponWOHolyRune","etched-onto-weapon-wo-holy-rune":"PF2E.TraitEtchedOntoAWeaponWOUnholyRune","etched-onto-melee-weapon-monk":"PF2E.TraitEtchedOntoAMeleeWeaponMonk","etched-onto-thrown-weapon":"PF2E.TraitEtchedOntoAThrownWeapon","held-in-one-hand":"PF2E.TraitHeldOneHand","held-in-one-hand-or-free-standing":"PF2E.TraitHeldOneHandFreeStanding","held-in-one-or-two-hands":"PF2E.TraitHeldOneTwoHands","held-in-two-hands":"PF2E.TraitHeldTwoHands",other:"Other","sewn-into-clothing":"PF2E.TraitSewnIntoClothing","tattooed-on-the-body":"PF2E.TraitTattooedOnTheBody",touched:"PF2E.TraitTouched",worn:"PF2E.TraitWorn",wornamulet:"PF2E.TraitWornAmulet",wornanklets:"PF2E.TraitWornAnklets",wornarmbands:"PF2E.TraitWornArmbands",wornbackpack:"PF2E.TraitWornBackpack",wornbarding:"PF2E.TraitWornBarding",wornbelt:"PF2E.TraitWornBelt",wornbeltpouch:"PF2E.TraitWornBeltPouch",wornboots:"PF2E.TraitWornBoots",wornbracelet:"PF2E.TraitWornBracelet",wornbracers:"PF2E.TraitWornBracers",worncap:"PF2E.TraitWornCap",worncape:"PF2E.TraitWornCape",worncirclet:"PF2E.TraitWornCirclet",worncloak:"PF2E.TraitWornCloak",wornclothing:"PF2E.TraitWornClothing",worncollar:"PF2E.TraitWornCollar",worncrown:"PF2E.TraitWornCrown",wornepaulet:"PF2E.TraitWornEpaulet",worneyeglasses:"PF2E.TraitWornEyeglasses",worneyepiece:"PF2E.TraitWornEyepiece",wornfootwear:"PF2E.TraitWornFootwear",worngarment:"PF2E.TraitWornGarment",worngloves:"PF2E.TraitWornGloves",wornheadwear:"PF2E.TraitWornHeadwear",wornhorseshoes:"PF2E.TraitWornHorseshoes",wornmask:"PF2E.TraitWornMask",wornnecklace:"PF2E.TraitWornNecklace",wornonbelt:"PF2E.TraitWornOnBelt",wornoronehand:"PF2E.TraitWornOrOneHand",wornring:"PF2E.TraitWornRing",wornsaddle:"PF2E.TraitWornSaddle",wornsandles:"PF2E.TraitWornSandles",wornshoes:"PF2E.TraitWornShoes",wornwrist:"PF2E.TraitWornOnWrists","worn-and-attached-to-two-weapons":"PF2E.TraitWornAndAttachedToTwoWeapons","worn-under-armor":"PF2E.TraitWornUnderArmor"},rarityTraits:{common:"PF2E.TraitCommon",uncommon:"PF2E.TraitUncommon",rare:"PF2E.TraitRare",unique:"PF2E.TraitUnique"},magicTraditions,classTraits,ancestryTraits,deityDomains,weaponTraits,otherWeaponTags,armorTraits,otherArmorTags,equipmentTraits,consumableTraits,otherConsumableTags,actionTraits,shieldTraits,spellTraits,featTraits,creatureTraits,kingmakerTraits,npcAttackTraits,hazardTraits,vehicleTraits,traitsDescriptions:traitDescriptions,creatureTypes,weaponHands:{1:"PF2E.WeaponHands1","1+":"PF2E.WeaponHands1Plus",2:"PF2E.WeaponHands2"},itemBonuses:{"-2":"PF2E.ItemBonusMinus2",0:"PF2E.ItemBonus0",1:"PF2E.ItemBonus1",2:"PF2E.ItemBonus2",3:"PF2E.ItemBonus3"},damageDice:{0:"0",1:"1",2:"2",3:"3",4:"4"},damageDie:{d4:"PF2E.DamageDieD4",d6:"PF2E.DamageDieD6",d8:"PF2E.DamageDieD8",d10:"PF2E.DamageDieD10",d12:"PF2E.DamageDieD12"},weaponMAP:{1:"-1/-2",2:"-2/-4",3:"-3/-6",4:"-4/-8",5:"-5/-10"},weaponReload,armorCategories:{unarmored:"PF2E.ArmorTypeUnarmored",light:"PF2E.ArmorTypeLight",medium:"PF2E.ArmorTypeMedium",heavy:"PF2E.ArmorTypeHeavy","light-barding":"PF2E.Item.Armor.Category.light-barding","heavy-barding":"PF2E.Item.Armor.Category.heavy-barding"},armorGroups:{composite:"PF2E.ArmorGroupComposite",chain:"PF2E.ArmorGroupChain",cloth:"PF2E.ArmorGroupCloth",leather:"PF2E.ArmorGroupLeather",plate:"PF2E.ArmorGroupPlate",skeletal:"PF2E.ArmorGroupSkeletal",wood:"PF2E.ArmorGroupWood"},consumableCategories,identification:configFromLocalization(define_EN_JSON_default.PF2E.identification,"PF2E.identification"),preparationType:{prepared:"PF2E.PreparationTypePrepared",spontaneous:"PF2E.PreparationTypeSpontaneous",innate:"PF2E.PreparationTypeInnate",focus:"PF2E.TraitFocus",items:"PF2E.PreparationTypeItems",ritual:"PF2E.Item.Spell.Ritual.Label"},areaTypes:{burst:"PF2E.AreaTypeBurst",cone:"PF2E.AreaTypeCone",cube:"PF2E.AreaTypeCube",emanation:"PF2E.AreaTypeEmanation",line:"PF2E.AreaTypeLine",square:"PF2E.AreaTypeSquare"},areaSizes:{5:"PF2E.AreaSize5",10:"PF2E.AreaSize10",15:"PF2E.AreaSize15",20:"PF2E.AreaSize20",25:"PF2E.AreaSize25",30:"PF2E.AreaSize30",40:"PF2E.AreaSize40",45:"PF2E.AreaSize45",50:"PF2E.AreaSize50",60:"PF2E.AreaSize60",65:"PF2E.AreaSize65",75:"PF2E.AreaSize75",80:"PF2E.AreaSize80",90:"PF2E.AreaSize90",100:"PF2E.AreaSize100",120:"PF2E.AreaSize120",360:"PF2E.AreaSize360",500:"PF2E.AreaSize500",1e3:"PF2E.AreaSize1000",1320:"PF2E.AreaSizeQuarterMile",5280:"PF2E.AreaSize1Mile"},attitude:{hostile:"PF2E.Attitudes.Hostile",unfriendly:"PF2E.Attitudes.Unfriendly",indifferent:"PF2E.Attitudes.Indifferent",friendly:"PF2E.Attitudes.Friendly",helpful:"PF2E.Attitudes.Helpful"},skillList:{acrobatics:"PF2E.SkillAcrobatics",arcana:"PF2E.SkillArcana",athletics:"PF2E.SkillAthletics",crafting:"PF2E.SkillCrafting",deception:"PF2E.SkillDeception",diplomacy:"PF2E.SkillDiplomacy",intimidation:"PF2E.SkillIntimidation",medicine:"PF2E.SkillMedicine",nature:"PF2E.SkillNature",occultism:"PF2E.SkillOccultism",performance:"PF2E.SkillPerformance",religion:"PF2E.SkillReligion",society:"PF2E.SkillSociety",stealth:"PF2E.SkillStealth",survival:"PF2E.SkillSurvival",thievery:"PF2E.SkillThievery",lore:"PF2E.SkillLore"},spellComponents:{V:"PF2E.SpellComponentV",S:"PF2E.SpellComponentS",M:"PF2E.SpellComponentM",F:"PF2E.SpellComponentF"},featCategories,actionTypes:{action:"PF2E.ActionTypeAction",reaction:"PF2E.ActionTypeReaction",free:"PF2E.ActionTypeFree",passive:"PF2E.ActionTypePassive"},actionsNumber:{1:"PF2E.ActionNumber1",2:"PF2E.ActionNumber2",3:"PF2E.ActionNumber3"},actionCategories:{interaction:"PF2E.Item.Action.Category.Interaction",defensive:"PF2E.Item.Action.Category.Defensive",offensive:"PF2E.Item.Action.Category.Offensive",familiar:"PF2E.Item.Action.Category.Familiar"},frequencies:{turn:"PF2E.Duration.turn",round:"PF2E.Duration.round",PT1M:"PF2E.Duration.PT1M",PT10M:"PF2E.Duration.PT10M",PT1H:"PF2E.Duration.PT1H",PT24H:"PF2E.Duration.PT24H",day:"PF2E.Duration.day",P1W:"PF2E.Duration.P1W",P1M:"PF2E.Duration.P1M",P1Y:"PF2E.Duration.P1Y"},timeUnits:{rounds:"PF2E.Time.Unit.Rounds",minutes:"PF2E.Time.Unit.Minutes",hours:"PF2E.Time.Unit.Hours",days:"PF2E.Time.Unit.Days",unlimited:"PF2E.Time.Unit.Unlimited",encounter:"PF2E.Time.Unit.UntilEncounterEnds"},proficiencyLevels:["PF2E.ProficiencyLevel0","PF2E.ProficiencyLevel1","PF2E.ProficiencyLevel2","PF2E.ProficiencyLevel3","PF2E.ProficiencyLevel4"],actorSizes:sizeTypes,actorTypes,speedTypes:{swim:"PF2E.SpeedTypesSwim",climb:"PF2E.SpeedTypesClimb",fly:"PF2E.SpeedTypesFly",burrow:"PF2E.SpeedTypesBurrow"},prerequisitePlaceholders:{prerequisite1:"PF2E.Prerequisite1",prerequisite2:"PF2E.Prerequisite2",prerequisite3:"PF2E.Prerequisite3",prerequisite4:"PF2E.Prerequisite4",prerequisite5:"PF2E.Prerequisite5"},senses,senseAcuity,conditionTypes,pfsFactions:{EA:"PF2E.PFS.Factions.EA",GA:"PF2E.PFS.Factions.GA",HH:"PF2E.PFS.Factions.HH",VS:"PF2E.PFS.Factions.VS",RO:"PF2E.PFS.Factions.RO",VW:"PF2E.PFS.Factions.VW"},pfsSchools:{none:"PF2E.PFS.School.None",scrolls:"PF2E.PFS.School.Scrolls",spells:"PF2E.PFS.School.Spells",swords:"PF2E.PFS.School.Swords"},immunityTypes,languages:mapToObj(LANGUAGES,l=>[l,`PF2E.Actor.Creature.Language.${l}`]),attackEffects:{grab:"PF2E.AttackEffectGrab","improved-grab":"PF2E.AttackEffectImprovedGrab",constrict:"PF2E.AttackEffectConstrict","greater-constrict":"PF2E.AttackEffectGreaterConstrict",knockdown:"PF2E.AttackEffectKnockdown","improved-knockdown":"PF2E.AttackEffectImprovedKnockdown",push:"PF2E.AttackEffectPush","improved-push":"PF2E.AttackEffectImprovedPush",trip:"PF2E.AttackEffectTrip"},worldClock:foundry.utils.mergeObject(configFromLocalization(define_EN_JSON_default.PF2E.WorldClock,"PF2E.WorldClock"),{AR:{yearOffset:2700},IC:{yearOffset:5200},AD:{yearOffset:-95},CE:{yearOffset:0}}),hexplorationActivities:{10:.5,25:1,40:2,55:3,Infinity:4},SETTINGS:{automation:{rulesBasedVision:{name:"PF2E.SETTINGS.Automation.RulesBasedVision.Name",hint:"PF2E.SETTINGS.Automation.RulesBasedVision.Hint"},iwr:{name:"PF2E.SETTINGS.Automation.IWR.Name",hint:"PF2E.SETTINGS.Automation.IWR.Hint"},effectExpiration:{name:"PF2E.SETTINGS.Automation.EffectExpiration.Name",hint:"PF2E.SETTINGS.Automation.EffectExpiration.Hint"},removeExpiredEffects:{name:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Name",hint:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Hint"},flankingDetection:{name:"PF2E.SETTINGS.Automation.FlankingDetection.Name",hint:"PF2E.SETTINGS.Automation.FlankingDetection.Hint"},actorsDeadAtZero:{name:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Name",hint:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Hint",neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},lootableNPCs:{name:"PF2E.SETTINGS.Automation.LootableNPCs.Name",hint:"PF2E.SETTINGS.Automation.LootableNPCs.Hint"}},homebrew:{creatureTraits:{name:"PF2E.SETTINGS.Homebrew.CreatureTraits.Name",hint:"PF2E.SETTINGS.Homebrew.CreatureTraits.Hint"},featTraits:{name:"PF2E.SETTINGS.Homebrew.FeatTraits.Name",hint:"PF2E.SETTINGS.Homebrew.FeatTraits.Hint"},languages:{name:"PF2E.SETTINGS.Homebrew.Languages.Name",hint:"PF2E.SETTINGS.Homebrew.Languages.Hint"},spellTraits:{name:"PF2E.SETTINGS.Homebrew.SpellTraits.Name",hint:"PF2E.SETTINGS.Homebrew.SpellTraits.Hint"},weaponCategories:{name:"PF2E.SETTINGS.Homebrew.WeaponCategories.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponCategories.Hint"},weaponGroups:{name:"PF2E.SETTINGS.Homebrew.WeaponGroups.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponGroups.Hint"},baseWeapons:{name:"PF2E.SETTINGS.Homebrew.BaseWeapons.Name",hint:"PF2E.SETTINGS.Homebrew.BaseWeapons.Hint"},weaponTraits:{name:"PF2E.SETTINGS.Homebrew.WeaponTraits.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponTraits.Hint"},equipmentTraits:{name:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Name",hint:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Hint"}},worldClock:{name:"PF2E.SETTINGS.WorldClock.Name",label:"PF2E.SETTINGS.WorldClock.Label",hint:"PF2E.SETTINGS.WorldClock.Hint",dateTheme:{name:"PF2E.SETTINGS.WorldClock.DateTheme.Name",hint:"PF2E.SETTINGS.WorldClock.DateTheme.Hint",AR:"PF2E.SETTINGS.WorldClock.DateTheme.AR",AD:"PF2E.SETTINGS.WorldClock.DateTheme.AD",CE:"PF2E.SETTINGS.WorldClock.DateTheme.CE"},timeConvention:{name:"PF2E.SETTINGS.WorldClock.TimeConvention.Name",hint:"PF2E.SETTINGS.WorldClock.TimeConvention.Hint",twentyFour:"PF2E.SETTINGS.WorldClock.TimeConvention.TwentyFour",twelve:"PF2E.SETTINGS.WorldClock.TimeConvention.Twelve"},showClockButton:{name:"PF2E.SETTINGS.WorldClock.ShowClockButton.Name",hint:"PF2E.SETTINGS.WorldClock.ShowClockButton.Hint"},playersCanView:{name:"PF2E.SETTINGS.WorldClock.PlayersCanView.Name",hint:"PF2E.SETTINGS.WorldClock.PlayersCanView.Hint"},syncDarkness:{name:"PF2E.SETTINGS.WorldClock.SyncDarkness.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarkness.Hint"},syncDarknessScene:{name:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Hint",enabled:"PF2E.SETTINGS.EnabledDisabled.Enabled",default:"PF2E.SETTINGS.EnabledDisabled.Default",disabled:"PF2E.SETTINGS.EnabledDisabled.Disabled"},worldCreatedOn:{name:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Name",hint:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Hint"}},CampaignFeats:{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint"}},Actor:{documentClasses:{army:ArmyPF2e,character:CharacterPF2e,npc:NPCPF2e,hazard:HazardPF2e,loot:LootPF2e,familiar:FamiliarPF2e,party:PartyPF2e,vehicle:VehiclePF2e}},Item:{documentClasses:{action:AbilityItemPF2e,affliction:AfflictionPF2e,ancestry:AncestryPF2e,armor:ArmorPF2e,background:BackgroundPF2e,backpack:ContainerPF2e,book:BookPF2e,campaignFeature:CampaignFeaturePF2e,class:ClassPF2e,condition:ConditionPF2e,consumable:ConsumablePF2e,deity:DeityPF2e,effect:EffectPF2e,equipment:EquipmentPF2e,feat:FeatPF2e,heritage:HeritagePF2e,kit:KitPF2e,lore:LorePF2e,melee:MeleePF2e,shield:ShieldPF2e,spell:SpellPF2e,spellcastingEntry:SpellcastingEntryPF2e,treasure:TreasurePF2e,weapon:WeaponPF2e},traits:{action:actionTraits,affliction:actionTraits,armor:armorTraits,ancestry:creatureTraits,background:backgroundTraits,backpack:equipmentTraits,book:equipmentTraits,campaignFeature:kingmakerTraits,consumable:consumableTraits,equipment:equipmentTraits,feat:featTraits,heritage:featTraits,kit:classTraits,melee:npcAttackTraits,shield:shieldTraits,spell:spellTraits,weapon:weaponTraits}},JournalEntry:{sheetClass:JournalSheetPF2e},Canvas:{darkness:{default:CONFIG.Canvas.darknessColor,gmVision:9473209}}};function registerHandlebarsHelpers(){Handlebars.registerHelper("pad",(value,length,character)=>`${value}`.padStart(length,character)),Handlebars.registerHelper("add",(a,b)=>Number(a)+Number(b)),Handlebars.registerHelper("nor",(...args)=>!args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("any",(...args)=>args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("disabled",condition=>condition?"disabled":""),Handlebars.registerHelper("coalesce",(...args)=>args.find(a=>a!=null)??null),Handlebars.registerHelper("lower",str=>String(str).toLowerCase()),Handlebars.registerHelper("capitalize",str=>String(str).capitalize()),Handlebars.registerHelper("multiply",(a,b)=>Number(a)*Number(b)),Handlebars.registerHelper("percentage",(value,max)=>Number(value)*100/Number(max)),Handlebars.registerHelper("ordinal",value=>{const numericValue=Number(value);return isNaN(numericValue)?null:ordinalString(numericValue)}),Handlebars.registerHelper("sluggify",text=>sluggify(String(text))),Handlebars.registerHelper("json",data=>JSON.stringify(data)),Handlebars.registerHelper("actionGlyph",(value,options)=>{const glyph=getActionGlyph(value??"");return glyph?`<span class="action-glyph">${glyph}</span>`:options?.hash.fallback?Handlebars.escapeExpression(value):null}),Handlebars.registerHelper("times",(count,options)=>[...Array(Number(count)||0).keys()].map(i=>options.fn(i,{data:options.data,blockParams:[i]})).join("")),Handlebars.registerHelper("concat",(...params)=>params.slice(0,-1).join("")),Handlebars.registerHelper("developMode",function(options){return""}),Handlebars.registerHelper("isNumber",value=>typeof value=="number"),Handlebars.registerHelper("isNullish",value=>value==null),Handlebars.registerHelper("signedInteger",(value,options)=>{const number=Number(value)||0,emptyStringZero=!!options.hash.emptyStringZero,zeroIsNegative=!!options.hash.zeroIsNegative;return signedInteger(number,{emptyStringZero,zeroIsNegative})}),Handlebars.registerHelper("coinLabel",value=>value?"value"in value?new CoinsPF2e(value.value):new CoinsPF2e(value):null),Handlebars.registerHelper("includes",(arr,element)=>Array.isArray(arr)?arr.includes(element):arr instanceof Set?arr.has(element):arr&&typeof arr=="object"?(typeof element=="number"||typeof element=="string")&&element in arr:!1),Handlebars.registerHelper("raw",function(options){return options.fn(this)})}__name(registerHandlebarsHelpers,"registerHandlebarsHelpers"),__name2(registerHandlebarsHelpers,"registerHandlebarsHelpers");function registerFonts(){CONFIG.fontDefinitions.Eczar={editor:!0,fonts:[{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-800.woff2"],style:"normal",weight:"800"}]},CONFIG.fontDefinitions.Gelasio={editor:!1,fonts:[{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600italic.woff2"],style:"italic",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["La Belle Aurore"]={editor:!0,fonts:[{urls:["systems/pf2e/fonts/la-belle-aurore-v16-latin-regular.woff2"],style:"normal",weight:"400"}]},CONFIG.fontDefinitions.Pathfinder2eActions={editor:!1,fonts:[{urls:["systems/pf2e/fonts/pathfinder-2e-actions.woff2"]}]},CONFIG.fontDefinitions.Roboto={editor:!0,fonts:[{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"900"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900italic.woff2"],style:"italic",weight:"900"}]},CONFIG.fontDefinitions["Roboto Condensed"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["Roboto Mono"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-700.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions.Signika={editor:!0,fonts:[{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-700.woff2"],style:"normal",weight:"700"}]},CONFIG.fontDefinitions.Vollkorn={editor:!0,fonts:[{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"700"}]},delete CONFIG.fontDefinitions.Courier,delete CONFIG.fontDefinitions.Times,CONFIG._fontFamilies=[]}__name(registerFonts,"registerFonts"),__name2(registerFonts,"registerFonts");function registerKeybindings(){game.keybindings.register("pf2e","cycle-token-stack",{name:"PF2E.Keybinding.CycleTokenStack.Label",hint:"PF2E.Keybinding.CycleTokenStack.Hint",editable:[{key:"KeyZ",modifiers:[]}],onUp:()=>canvas.tokens.cycleStack()}),game.keybindings.register("pf2e","toggle-party-sheet",{name:"PF2E.Keybinding.TogglePartySheet.Label",hint:"PF2E.Keybinding.TogglePartySheet.Hint",editable:[{key:"KeyP",modifiers:[]}],onDown:()=>{const party=(()=>{if(game.user.isGM){const token=canvas.ready&&canvas.tokens.controlled.length===1?canvas.tokens.controlled[0]:null;return token?.actor?.isOfType("party")?token.actor:game.actors.party}else if(game.user.character?.isOfType("character")){const pcParties=Array.from(game.user.character.parties);return pcParties.find(p=>p.active)??pcParties.at(0)??null}return null})();if(!party)return!1;const{sheet}=party;return sheet.rendered?sheet._minimized?sheet.maximize():sheet.close():sheet.render(!0),!0}}),!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.keybindings.register("pf2e","gm-vision",{name:"PF2E.Keybinding.GMVision.Label",hint:"PF2E.Keybinding.GMVision.Hint",editable:[{key:"KeyG",modifiers:["Control"]}],restricted:!0,onDown:context=>(context.event.preventDefault(),!0),onUp:()=>(ui.controls.control?.name==="lighting"?ui.controls.control.tools.find(t=>t.name==="gm-vision")?.onClick?.():game.settings.set("pf2e","gmVision",!game.settings.get("pf2e","gmVision")),!0)})}__name(registerKeybindings,"registerKeybindings"),__name2(registerKeybindings,"registerKeybindings");function registerTemplates(){const templatePaths=["systems/pf2e/templates/chat/check/roll.hbs","systems/pf2e/templates/chat/check/target-dc-result.hbs","systems/pf2e/templates/chat/damage/damage-taken.hbs","systems/pf2e/templates/dice/damage-roll.hbs","systems/pf2e/templates/dice/damage-tooltip.hbs","systems/pf2e/templates/actors/character/partials/elemental-blast.hbs","systems/pf2e/templates/actors/character/partials/feat-slot.hbs","systems/pf2e/templates/actors/character/partials/header.hbs","systems/pf2e/templates/actors/character/partials/sidebar.hbs","systems/pf2e/templates/actors/character/partials/strike.hbs","systems/pf2e/templates/actors/character/tabs/general.hbs","systems/pf2e/templates/actors/character/tabs/actions.hbs","systems/pf2e/templates/actors/character/tabs/biography.hbs","systems/pf2e/templates/actors/character/tabs/effects.hbs","systems/pf2e/templates/actors/character/tabs/feats.hbs","systems/pf2e/templates/actors/character/tabs/inventory.hbs","systems/pf2e/templates/actors/character/tabs/pfs.hbs","systems/pf2e/templates/actors/character/tabs/proficiencies.hbs","systems/pf2e/templates/actors/character/tabs/spellcasting.hbs","systems/pf2e/templates/actors/character/tabs/crafting.hbs","systems/pf2e/templates/actors/hazard/partials/header.hbs","systems/pf2e/templates/actors/hazard/partials/sidebar.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/main.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/activities.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/world.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/features.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/ongoing.hbs","systems/pf2e/templates/actors/party/kingdom/partials/build-entry-boosts.hbs","systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs","systems/pf2e/templates/actors/partials/action.hbs","systems/pf2e/templates/actors/partials/carry-type.hbs","systems/pf2e/templates/actors/partials/coinage.hbs","systems/pf2e/templates/actors/partials/dying-pips.hbs","systems/pf2e/templates/actors/partials/effects.hbs","systems/pf2e/templates/actors/partials/encumbrance.hbs","systems/pf2e/templates/actors/partials/inventory.hbs","systems/pf2e/templates/actors/partials/item-line.hbs","systems/pf2e/templates/actors/partials/modifiers-tooltip.hbs","systems/pf2e/templates/actors/partials/spell-collection.hbs","systems/pf2e/templates/actors/partials/toggles.hbs","systems/pf2e/templates/actors/partials/total-bulk.hbs","systems/pf2e/templates/actors/crafting-entry-alchemical.hbs","systems/pf2e/templates/actors/crafting-entry-list.hbs","systems/pf2e/templates/actors/character/partials/proficiencylevels-dropdown.hbs","systems/pf2e/templates/actors/character/icons/d20.hbs","systems/pf2e/templates/actors/character/icons/pfs.hbs","systems/pf2e/templates/actors/character/icons/plus.hbs","systems/pf2e/templates/actors/npc/tabs/main.hbs","systems/pf2e/templates/actors/npc/tabs/inventory.hbs","systems/pf2e/templates/actors/npc/tabs/effects.hbs","systems/pf2e/templates/actors/npc/tabs/spells.hbs","systems/pf2e/templates/actors/npc/tabs/notes.hbs","systems/pf2e/templates/actors/npc/partials/header.hbs","systems/pf2e/templates/actors/npc/partials/sidebar.hbs","systems/pf2e/templates/actors/npc/partials/action.hbs","systems/pf2e/templates/actors/npc/partials/attack.hbs","systems/pf2e/templates/items/action-details.hbs","systems/pf2e/templates/items/action-sidebar.hbs","systems/pf2e/templates/items/activation-panel.hbs","systems/pf2e/templates/items/affliction-details.hbs","systems/pf2e/templates/items/affliction-sidebar.hbs","systems/pf2e/templates/items/ancestry-details.hbs","systems/pf2e/templates/items/ancestry-sidebar.hbs","systems/pf2e/templates/items/armor-details.hbs","systems/pf2e/templates/items/background-details.hbs","systems/pf2e/templates/items/backpack-details.hbs","systems/pf2e/templates/items/book-details.hbs","systems/pf2e/templates/items/campaign-feature-details.hbs","systems/pf2e/templates/items/campaign-feature-sidebar.hbs","systems/pf2e/templates/items/class-details.hbs","systems/pf2e/templates/items/condition-details.hbs","systems/pf2e/templates/items/condition-sidebar.hbs","systems/pf2e/templates/items/consumable-details.hbs","systems/pf2e/templates/items/deity-details.hbs","systems/pf2e/templates/items/effect-details.hbs","systems/pf2e/templates/items/effect-sidebar.hbs","systems/pf2e/templates/items/equipment-details.hbs","systems/pf2e/templates/items/feat-details.hbs","systems/pf2e/templates/items/feat-sidebar.hbs","systems/pf2e/templates/items/heritage-details.hbs","systems/pf2e/templates/items/heritage-sidebar.hbs","systems/pf2e/templates/items/kit-details.hbs","systems/pf2e/templates/items/lore-details.hbs","systems/pf2e/templates/items/melee-details.hbs","systems/pf2e/templates/items/mystify-panel.hbs","systems/pf2e/templates/items/physical-sidebar.hbs","systems/pf2e/templates/items/rules-panel.hbs","systems/pf2e/templates/items/shield-details.hbs","systems/pf2e/templates/items/spell-details.hbs","systems/pf2e/templates/items/spell-overlay.hbs","systems/pf2e/templates/items/treasure-details.hbs","systems/pf2e/templates/items/weapon-details.hbs","systems/pf2e/templates/items/partials/ability-activation.hbs","systems/pf2e/templates/items/partials/duration.hbs","systems/pf2e/templates/items/partials/other-tags.hbs","systems/pf2e/templates/items/partials/self-applied-effect.hbs","systems/pf2e/templates/actors/loot/inventory.hbs","systems/pf2e/templates/actors/loot/sidebar.hbs","systems/pf2e/templates/actors/vehicle/vehicle-header.hbs","systems/pf2e/templates/actors/vehicle/sidebar.hbs","systems/pf2e/templates/actors/vehicle/tabs/details.hbs","systems/pf2e/templates/actors/vehicle/tabs/actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/description.hbs","systems/pf2e/templates/actors/vehicle/tabs/effects.hbs","systems/pf2e/templates/compendium-browser/settings/settings.hbs","systems/pf2e/templates/compendium-browser/settings/pack-settings.hbs","systems/pf2e/templates/compendium-browser/settings/source-settings.hbs","systems/pf2e/templates/compendium-browser/filters.hbs","systems/pf2e/templates/chat/action/header.hbs","systems/pf2e/templates/system/actions/repair/chat-button-partial.hbs","systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs","systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs","systems/pf2e/templates/scene/token/partials/appearance.hbs","systems/pf2e/templates/scene/token/partials/identity.hbs","systems/pf2e/templates/scene/token/partials/lighting.hbs","systems/pf2e/templates/partials/publication-data.hbs"];loadTemplates(templatePaths)}__name(registerTemplates,"registerTemplates"),__name2(registerTemplates,"registerTemplates");class PackLoader{static{__name(this,"PackLoader")}static{__name2(this,"PackLoader")}loadedSources=[];sourcesSettings;constructor(){this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){const localize=localizer("PF2E.ProgressBar"),sources=this.#getSources(),progress=new Progress({max:packs.length});for(const packId of packs){const pack=game.packs.get(packId);if(!pack){progress.advance();continue}if(progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),pack.documentName===documentType){const index=await pack.getIndex({fields:indexFields});if((index.contents.at(0)??{}).system){const filteredIndex=this.#createFilteredIndex(index,sources);this.#setModuleArt(packId,filteredIndex),yield{pack,index:filteredIndex}}else ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}))}}progress.close({label:localize("LoadingComplete")})}#setModuleArt(packName,index){if(packName.startsWith("pf2e."))for(const record of index){const uuid=`Compendium.${packName}.${record._id}`,actorArt=game.pf2e.system.moduleArt.map.get(uuid)?.img;record.img=actorArt??record.img}}#getSources(){const sources=new Set;for(const source of Object.values(this.sourcesSettings.sources))source?.load&&sources.add(source.name);return sources}#createFilteredIndex(index,sources){if(sources.size===0||game.user.isGM&&this.sourcesSettings.ignoreAsGM)return index;const filteredIndex=new Collection,knownSources=Object.values(this.sourcesSettings.sources).map(value=>value?.name);for(const data of index){const source=this.#getSourceFromDocument(data);(!source&&this.sourcesSettings.showEmptySources||sources.has(source)||this.sourcesSettings.showUnknownSources&&source&&!knownSources.includes(source))&&filteredIndex.set(data._id,foundry.utils.deepClone(data))}return filteredIndex}async updateSources(packs){await this.#loadSources(packs);for(const source of this.loadedSources){const slug=sluggify(source);this.sourcesSettings.sources[slug]===void 0&&(this.sourcesSettings.sources[slug]={load:this.sourcesSettings.showUnknownSources,name:source})}this.sourcesSettings.sources=Object.fromEntries(Object.entries(this.sourcesSettings.sources).sort((a,b)=>a[0].localeCompare(b[0],game.i18n.lang)))}async#loadSources(packs){const localize=localizer("PF2E.ProgressBar"),progress=new Progress({max:packs.length}),loadedSources=new Set,indexFields=["system.publication.title","system.source.value"],knownDocumentTypes=["Actor","Item"];for(const packId of packs){const pack=game.packs.get(packId);if(!pack||!knownDocumentTypes.includes(pack.documentName)){progress.advance();continue}progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})});const index=await pack.getIndex({fields:indexFields});for(const element of index){const source=this.#getSourceFromDocument(element);source&&source!==""&&loadedSources.add(source)}}progress.close({label:localize("LoadingComplete")});const loadedSourcesArray=Array.from(loadedSources).sort();this.loadedSources=loadedSourcesArray}#getSourceFromDocument(document2){const{system}=document2;return isObject$1(system)?system.publication?.title??system.details?.publication?.title??system.source?.value??system.details?.source?.value??"":""}reset(){this.loadedSources=[]}async hardReset(packs){this.reset(),this.sourcesSettings={ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},await this.updateSources(packs)}}class CompendiumBrowserTab{static{__name(this,"CompendiumBrowserTab")}static{__name2(this,"CompendiumBrowserTab")}browser;indexData=[];currentIndex=[];isInitialized=!1;totalItemCount=0;scrollLimit=100;#domParser=new DOMParser;searchFields=[];storeFields=[];constructor(browser){this.browser=browser}async init(){await this.loadData(),this.searchEngine=new MiniSearch({fields:this.searchFields,idField:"uuid",processTerm:t=>t.length>1&&!CompendiumDirectoryPF2e.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,storeFields:this.storeFields,searchOptions:{combineWith:"AND",prefix:!0}}),this.searchEngine.addAll(this.indexData),this.defaultFilterData=foundry.utils.deepClone(this.filterData),this.isInitialized=!0}async open(filter2){if(filter2){if(!this.isInitialized)throw ErrorPF2e(`Tried to pass an initial filter to uninitialized tab "${this.tabName}"`);this.filterData=filter2}return this.browser.loadTab(this.tabName)}getIndexData(start){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);return this.currentIndex=(()=>{const searchText=this.filterData.search.text;if(searchText){const searchResult=this.searchEngine.search(searchText);return this.sortResult(searchResult.filter(this.filterIndexData.bind(this)))}return this.sortResult(this.indexData.filter(this.filterIndexData.bind(this)))})(),this.totalItemCount=this.currentIndex.length,this.currentIndex.slice(start,this.scrollLimit)}async getFilterData(){return this.isInitialized||await this.init(),foundry.utils.deepClone(this.defaultFilterData)}resetFilters(){this.filterData=foundry.utils.deepClone(this.defaultFilterData)}isOfType(...types){return types.some(t=>this.tabName===t)}filterTraits(traits,selected,condition){const selectedTraits=selected.filter(s=>!s.not).map(s=>s.value),notTraits=selected.filter(t=>t.not).map(s=>s.value);return!((selectedTraits.length||notTraits.length)&&(notTraits.some(t=>traits.includes(t))||!(condition==="and"?selectedTraits.every(t=>traits.includes(t)):selectedTraits.some(t=>traits.includes(t)))))}async renderResults(start){if(!this.templatePath)throw ErrorPF2e(`Tab "${this.tabName}" has no valid template path.`);const indexData=this.getIndexData(start),liElements=[];for(const entry of indexData){const htmlString=await renderTemplate(this.templatePath,{entry,filterData:this.filterData}),html=this.#domParser.parseFromString(htmlString,"text/html");liElements.push(html.body.firstElementChild)}return liElements}sortResult(result){const{order}=this.filterData,lang=game.i18n.lang,sorted=result.sort((entryA,entryB)=>{switch(order.by){case"name":return entryA.name.localeCompare(entryB.name,lang);case"level":return entryA.level-entryB.level||entryA.name.localeCompare(entryB.name,lang);case"price":return entryA.priceInCopper-entryB.priceInCopper||entryA.name.localeCompare(entryB.name,lang);case"rank":return entryA.rank-entryB.rank||entryA.name.localeCompare(entryB.name,lang);default:return 0}});return order.direction==="asc"?sorted:sorted.reverse()}parseRangeFilterInput(_name,lower,upper){return{min:Number(lower)||0,max:Number(upper)||0,inputMin:lower,inputMax:upper}}arrayIncludes(array,other){return other.some(value=>array.includes(value))}generateCheckboxOptions(configData,sort=!0){const localized=Object.entries(configData).reduce((result,[key,label])=>({...result,[key]:game.i18n.localize(label)}),{});return Object.entries(sort?this.sortedConfig(localized):localized).reduce((result,[key,label])=>({...result,[key]:{label,selected:!1}}),{})}generateMultiselectOptions(optionsRecord,sort=!0){const options=Object.entries(optionsRecord).map(([value,label])=>({value,label:game.i18n.localize(label)}));return sort&&options.sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),options}generateSourceCheckboxOptions(sources){return[...sources].sort().reduce((result,source)=>({...result,[sluggify(source)]:{label:source,selected:!1}}),{})}sortedConfig(obj){return Object.fromEntries([...Object.entries(obj)].sort((entryA,entryB)=>entryA[1].localeCompare(entryB[1],game.i18n.lang)))}hasAllIndexFields(data,indexFields){for(const field of indexFields)if(foundry.utils.getProperty(data,field)===void 0&&!/\.(?:source|publication)/.test(field))return!1;return!0}#getRollTableResults({initial=0,weight=1}){return this.currentIndex.flatMap((e,i)=>{const data=fromUuidSync(e.uuid);if(!data?.pack||!data._id||!("name"in data))return[];const rangeMinMax=initial+i+1;return{text:data.name,type:CONST.TABLE_RESULT_TYPES.COMPENDIUM,collection:data.pack,resultId:data._id,img:e.img,weight,range:[rangeMinMax,rangeMinMax],drawn:!1}})}async createRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length});Dialog.confirm({content,title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.CreateLabel"),yes:async $html=>{const html=$html[0],name2=htmlQuery(html,"input[name=name]")?.value||game.i18n.localize("PF2E.CompendiumBrowser.Title"),weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,results=this.#getRollTableResults({weight});(await RollTable.create({name:name2,results,formula:`1d${results.length}`}))?.sheet.render(!0)}})}async addToRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length,rollTables:game.tables.contents});Dialog.confirm({title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.SelectTableTitle"),content,yes:async $html=>{const html=$html[0],option=htmlQuery(html,"select[name=roll-table]")?.selectedOptions[0];if(!option)return;const weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,table=game.tables.get(option.value,{strict:!0});await table.createEmbeddedDocuments("TableResult",this.#getRollTableResults({initial:table.results.size,weight})),table?.sheet.render(!0)}})}}class CompendiumBrowserActionTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserActionTab")}static{__name2(this,"CompendiumBrowserActionTab")}tabName="action";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/action.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","traits","source","category","actionType"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading actions");const actions=[],indexFields=["img","system.actionType.value","system.category","system.traits.value","system.actionType.value","system.publication","system.source"],publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("action"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loading`);for(const actionData of index)if(actionData.type==="action"){if(!this.hasAllIndexFields(actionData,indexFields)){console.warn(`Action '${actionData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}actionData.system.actionType.value==="passive"&&(actionData.img=getActionIcon("passive"));const{system}=actionData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),actions.push({type:actionData.type,name:actionData.name,img:actionData.img,uuid:`Compendium.${pack.collection}.${actionData._id}`,traits:actionData.system.traits.value.map(t=>t.replace(/^hb_/,"")),actionType:actionData.system.actionType.value,category:actionData.system.category,source:sourceSlug})}}this.indexData=actions,this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.actionTraits),this.filterData.checkboxes.types.options=this.generateCheckboxOptions(CONFIG.PF2E.actionTypes),this.filterData.checkboxes.category.options=this.generateCheckboxOptions(pick(CONFIG.PF2E.actionCategories,["familiar"])),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading actions")}filterIndexData(entry){const{checkboxes,multiselects}=this.filterData;return!(checkboxes.types.selected.length&&!checkboxes.types.selected.includes(entry.actionType)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source))}prepareFilterData(){return{checkboxes:{types:{isExpanded:!0,label:"PF2E.ActionActionTypeLabel",options:{},selected:[]},category:{isExpanded:!0,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"name",direction:"asc",options:{name:"Name"}},search:{text:""}}}}class CompendiumBrowserBestiaryTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserBestiaryTab")}static{__name2(this,"CompendiumBrowserBestiaryTab")}tabName="bestiary";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/bestiary.hbs";index=["img","system.details.level.value","system.details.publication.title","system.details.source.value","system.traits"];searchFields=["name"];storeFields=["type","name","img","uuid","level","actorSize","traits","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){const bestiaryActors=[],publications=new Set,indexFields=[...this.index];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("bestiary"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="npc")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Actor '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),bestiaryActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,actorSize:actorData.system.traits.size.value,traits:actorData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=bestiaryActors,this.filterData.checkboxes.sizes.options=this.generateCheckboxOptions(CONFIG.PF2E.actorSizes),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.creatureTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Bestiary actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.sizes.selected.length&&!checkboxes.sizes.selected.includes(entry.actorSize)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{sizes:{isExpanded:!0,label:"PF2E.BrowserFilterSizes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserCampaignFeaturesTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserCampaignFeaturesTab")}static{__name2(this,"CompendiumBrowserCampaignFeaturesTab")}tabName="campaignFeature";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","traits","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("campaignFeature"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index.filter(i=>i.type==="campaignFeature")){featData.filters={};const{system}=featData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.${featData._id}`,level:featData.system.level?.value,category:featData.system.category,traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(KINGMAKER_CATEGORIES),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.kingmakerTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData,entryLevel=entry.level??0;return!(!(entryLevel>=sliders.level.values.min&&entryLevel<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserEquipmentTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserEquipmentTab")}static{__name2(this,"CompendiumBrowserEquipmentTab")}tabName="equipment";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/equipment.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","group","price","priceInCopper","traits","rarity","source"];#localizeCoins=localizer("PF2E.CurrencyAbbreviations");constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading inventory items");const inventoryItems=[],itemTypes=["weapon","shield","armor","equipment","consumable","treasure","backpack","kit"],baseFields=["img","system.price","system.traits","system.publication","system.source"],physicalItemFields=[...baseFields,"system.level.value"],runedItemFields=[...physicalItemFields,"system.runes"],armorAndWeaponFields=[...runedItemFields,"system.category","system.group"],indexFields=uniq([...armorAndWeaponFields]).sort(),publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("equipment"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const itemData of index)if(!(itemData.type==="treasure"&&itemData.system.stackGroup==="coins")&&itemTypes.includes(itemData.type)){if((()=>{switch(itemData.type){case"armor":case"weapon":return!this.hasAllIndexFields(itemData,armorAndWeaponFields);case"kit":return!this.hasAllIndexFields(itemData,baseFields);case"shield":return!this.hasAllIndexFields(itemData,runedItemFields);default:return!this.hasAllIndexFields(itemData,physicalItemFields)}})()){console.warn(`Item '${itemData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const priceValue=itemData.system.price.value,priceCoins=typeof priceValue=="string"?CoinsPF2e.fromString(priceValue):new CoinsPF2e(priceValue),coinValue=priceCoins.copperValue,{system}=itemData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource);const traits=itemData.system.traits.value??[],runes=itemData.system.runes,traditionTraits=MAGIC_TRADITIONS;!traits.some(t=>traditionTraits.has(t))&&["armor","shield","weapon"].includes(itemData.type)&&(runes.potency||runes.reinforcing||runes.resilient||runes.striking)&&traits.push("magical"),inventoryItems.push({type:itemData.type,name:itemData.name,img:itemData.img,uuid:`Compendium.${pack.collection}.${itemData._id}`,level:itemData.system.level?.value??0,category:itemData.system.category??"",group:itemData.system.group??"",price:priceCoins,priceInCopper:coinValue,traits:uniq(itemData.system.traits.value),rarity:itemData.system.traits.rarity,source:sourceSlug})}}this.indexData=inventoryItems,this.filterData.checkboxes.armorTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.armorCategories),foundry.utils.mergeObject(this.filterData.checkboxes.armorTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.armorGroups)),this.filterData.checkboxes.weaponTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.weaponCategories),foundry.utils.mergeObject(this.filterData.checkboxes.weaponTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.weaponGroups)),this.filterData.multiselects.traits.options=this.generateMultiselectOptions({...CONFIG.PF2E.armorTraits,...CONFIG.PF2E.consumableTraits,...CONFIG.PF2E.equipmentTraits,...CONFIG.PF2E.shieldTraits,...CONFIG.PF2E.weaponTraits}),this.filterData.checkboxes.itemTypes.options=this.generateCheckboxOptions({weapon:"TYPES.Item.weapon",shield:"TYPES.Item.shield",armor:"TYPES.Item.armor",equipment:"TYPES.Item.equipment",consumable:"TYPES.Item.consumable",treasure:"TYPES.Item.treasure",backpack:"TYPES.Item.backpack",kit:"TYPES.Item.kit"}),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading inventory items")}filterIndexData(entry){const{checkboxes,multiselects,ranges,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||!(entry.priceInCopper>=ranges.price.values.min&&entry.priceInCopper<=ranges.price.values.max)||checkboxes.itemTypes.selected.length>0&&!checkboxes.itemTypes.selected.includes(entry.type)||checkboxes.armorTypes.selected.length>0&&!this.arrayIncludes(checkboxes.armorTypes.selected,[entry.category,entry.group])||checkboxes.weaponTypes.selected.length>0&&!this.arrayIncludes(checkboxes.weaponTypes.selected,[entry.category,entry.group])||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(entry.rarity))}parseRangeFilterInput(name2,lower,upper){if(name2==="price"){const coins={cp:this.#localizeCoins("cp"),sp:this.#localizeCoins("sp"),gp:this.#localizeCoins("gp"),pp:this.#localizeCoins("pp")};for(const[english,translated]of Object.entries(coins))lower=lower.replaceAll(translated,english),upper=upper.replaceAll(translated,english);return{min:CoinsPF2e.fromString(lower).copperValue,max:CoinsPF2e.fromString(upper).copperValue,inputMin:lower,inputMax:upper}}return super.parseRangeFilterInput(name2,lower,upper)}prepareFilterData(){return{checkboxes:{itemTypes:{isExpanded:!0,label:"PF2E.BrowserFilterInventoryTypes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},armorTypes:{isExpanded:!1,label:"PF2E.BrowserFilterArmorFilters",options:{},selected:[]},weaponTypes:{isExpanded:!1,label:"PF2E.BrowserFilterWeaponFilters",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel",price:"PF2E.PriceLabel"}},ranges:{price:{changed:!1,isExpanded:!1,label:"PF2E.PriceLabel",values:{min:0,max:2e7,inputMin:`0${this.#localizeCoins("cp")}`,inputMax:`200,000${this.#localizeCoins("gp")}`}}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:30,min:0,max:30,step:1}}},search:{text:""}}}}class CompendiumBrowserFeatTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserFeatTab")}static{__name2(this,"CompendiumBrowserFeatTab")}tabName="feat";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","skills","traits","rarity","source"];#creatureTraits=CONFIG.PF2E.creatureTraits;constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"],translatedSkills=Object.entries(CONFIG.PF2E.skillList).reduce((result,[key,value])=>({...result,[key]:game.i18n.localize(value).toLocaleLowerCase(game.i18n.lang)}),{}),skillList=Object.entries(translatedSkills);for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("feat"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index)if(featData.type==="feat"){featData.filters={};const categoryPaths=["system.category","system.featType.value"],nonCategoryPaths=indexFields.filter(f=>!categoryPaths.includes(f)),categoryPathFound=categoryPaths.some(p=>foundry.utils.hasProperty(featData,p));if(!this.hasAllIndexFields(featData,nonCategoryPaths)||!categoryPathFound){console.warn(`Feat "${featData.name}" does not have all required data fields.`,`Consider unselecting pack "${pack.metadata.label}" in the compendium browser settings.`);continue}const featType=featData.system.featType;isObject(featType)&&"value"in featType&&typeof featType.value=="string"&&(featData.system.category=featType.value,delete featData.system.featType);const prerequisitesArr=featData.system.prerequisites.value.map(prerequisite=>prerequisite?.value?prerequisite.value.toLowerCase():""),skills=new Set;for(const prereq of prerequisitesArr)for(const[key,value]of skillList)(prereq.includes(key)||prereq.includes(value))&&skills.add(key);const pubSource=featData.system.publication?.title??featData.system.source?.value??"",sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.Item.${featData._id}`,level:featData.system.level.value,category:featData.system.category,skills:[...skills],traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(CONFIG.PF2E.featCategories),this.filterData.checkboxes.skills.options=this.generateCheckboxOptions(CONFIG.PF2E.skillList),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.featTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterTraits(traits,selected,condition){if(this.filterData.checkboxes.category.selected.includes("ancestry")&&!traits.some(t=>t in this.#creatureTraits)){const withoutAncestryTraits=selected.filter(t=>!(t.value in this.#creatureTraits));return super.filterTraits(traits,withoutAncestryTraits,condition)}return super.filterTraits(traits,selected,condition)}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||checkboxes.skills.selected.length&&!this.arrayIncludes(checkboxes.skills.selected,entry.skills)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},skills:{isExpanded:!1,label:"PF2E.BrowserFilterSkills",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserHazardTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserHazardTab")}static{__name2(this,"CompendiumBrowserHazardTab")}tabName="hazard";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/hazard.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","complexity","traits","rarity","source"];index=["img","system.details.level.value","system.details.isComplex","system.traits"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading Hazard actors");const hazardActors=[],publications=new Set,indexFields=[...this.index,"system.details.alignment.value","system.details.publication","system.details.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("hazard"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="hazard")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Hazard '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),hazardActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,complexity:actorData.system.details.isComplex?"complex":"simple",traits:actorData.system.traits.value,rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=hazardActors,this.filterData.checkboxes.complexity.options=this.generateCheckboxOptions({simple:"PF2E.Actor.Hazard.Simple",complex:"PF2E.TraitComplex"},!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.hazardTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Hazard actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.complexity.selected.length&&!checkboxes.complexity.selected.includes(entry.complexity)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{complexity:{isExpanded:!0,label:"PF2E.BrowserFilterComplexity",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserSpellTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserSpellTab")}static{__name2(this,"CompendiumBrowserSpellTab")}tabName="spell";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/spell.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","rank","time","traditions","traits","categories","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading spells");const spells=[],times=new Set,publications=new Set,indexFields=["img","system.level.value","system.time","system.traits","system.publication","system.ritual","system.source"],data=this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("spell"),indexFields);for await(const{pack,index}of data){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const spellData of index)if(spellData.filters={},spellData.type==="spell"){if("system"in spellData&&isObject$1(spellData.system)&&(spellData.system.ritual??=null),!this.hasAllIndexFields(spellData,indexFields)){console.warn(`Item '${spellData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const isCantrip=spellData.system.traits.value.includes("cantrip"),isFocusSpell=spellData.system.traits.value.includes("focus"),isRitual=!!spellData.system.ritual,categories=compact([!isCantrip&&!isFocusSpell&&!isRitual?"spell":null,isCantrip?"cantrip":null,isFocusSpell?"focus":null,isRitual?"ritual":null]),time=spellData.system.time.value;if(time&&typeof time=="string"){const normalizedTime=time.toLocaleLowerCase("en").includes("reaction")?"reaction":sluggify(time);times.add(normalizedTime),spellData.system.time.value=normalizedTime}const actionGlyph=getActionGlyph(spellData.system.time.value),{system}=spellData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),spells.push({type:spellData.type,name:spellData.name,img:spellData.img,uuid:`Compendium.${pack.collection}.${spellData._id}`,rank:spellData.system.level.value,categories,time:spellData.system.time,actionGlyph,traditions:spellData.system.traits.traditions,traits:spellData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:spellData.system.traits.rarity,source:sourceSlug})}}this.indexData=spells,this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let rank=1;rank<=10;rank++)this.filterData.checkboxes.rank.options[rank]={label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),selected:!1};this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(omit(CONFIG.PF2E.spellTraits,Array.from(MAGIC_TRADITIONS))),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.checkboxes.category.options=this.generateCheckboxOptions({spell:"TYPES.Item.spell",cantrip:"PF2E.TraitCantrip",focus:"PF2E.TraitFocus",ritual:"PF2E.Item.Spell.Ritual.Label"},!1),this.filterData.selects.timefilter.options=[...times].sort().reduce((result,time)=>({...result,[sluggify(time)]:time}),{}),console.debug("PF2e System | Compendium Browser | Finished loading spells")}filterIndexData(indexData){const{checkboxes,multiselects,selects}=this.filterData;return!(checkboxes.rank.selected.length>0&&!checkboxes.rank.selected.map(r=>Number(r)).includes(indexData.rank)||checkboxes.category.selected.length>0&&!equals(checkboxes.category.selected.sort(),indexData.categories.sort())||selects.timefilter.selected&&selects.timefilter.selected!==indexData.time.value||checkboxes.traditions.selected.length>0&&intersection(checkboxes.traditions.selected,indexData.traditions).length===0||!this.filterTraits(indexData.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(indexData.rarity)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(indexData.source))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!0,label:"PF2E.BrowserFilterSpellCategories",options:{},selected:[]},traditions:{isExpanded:!0,label:"PF2E.BrowserFilterTraditions",options:{},selected:[]},rank:{isExpanded:!0,label:"PF2E.Item.Spell.Rank.Plural",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},selects:{timefilter:{label:"PF2E.BrowserFilterCastingTime",options:{},selected:""}},order:{by:"rank",direction:"asc",options:{name:"Name",rank:"PF2E.Item.Spell.Rank.Label"}},search:{text:""}}}}class CompendiumBrowser extends Application{static{__name(this,"CompendiumBrowser")}static{__name2(this,"CompendiumBrowser")}settings;dataTabsList=["action","bestiary","campaignFeature","equipment","feat","hazard","spell"];navigationTab;tabs;packLoader=new PackLoader;constructor(options={}){super(options),this.settings=game.settings.get("pf2e","compendiumBrowserPacks"),this.navigationTab=this.hookTab(),this.tabs={action:new CompendiumBrowserActionTab(this),bestiary:new CompendiumBrowserBestiaryTab(this),campaignFeature:new CompendiumBrowserCampaignFeaturesTab(this),equipment:new CompendiumBrowserEquipmentTab(this),feat:new CompendiumBrowserFeatTab(this),hazard:new CompendiumBrowserHazardTab(this),spell:new CompendiumBrowserSpellTab(this)},this.initCompendiumList()}get title(){return game.i18n.localize("PF2E.CompendiumBrowser.Title")}static get defaultOptions(){return{...super.defaultOptions,id:"compendium-browser",classes:[],template:"systems/pf2e/templates/compendium-browser/compendium-browser.hbs",width:800,height:700,resizable:!0,dragDrop:[{dragSelector:"ul.item-list > li.item"}],tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"},{navSelector:"nav[data-group=settings]",contentSelector:".settings-container",initial:"packs"}],scrollY:[".control-area",".item-list",".settings-container"]}}async close(options){for(const tab of Object.values(this.tabs))tab.filterData.search.text="";await super.close(options)}hookTab(){const navigationTab=this._tabs[0],tabCallback=navigationTab.callback;return navigationTab.callback=async(event2,tabs,active)=>{tabCallback?.(event2,tabs,active),await this.loadTab(active)},navigationTab}initCompendiumList(){const settings={action:{},bestiary:{},campaignFeature:{},hazard:{},equipment:{},feat:{},spell:{}},loadDefault={bestiary:!0,hazard:!0,"pf2e.actionspf2e":!0,"pf2e.familiar-abilities":!0,"pf2e.equipment-srd":!0,"pf2e.ancestryfeatures":!0,"pf2e.classfeatures":!0,"pf2e.feats-srd":!0,"pf2e.spells-srd":!0,"pf2e.kingmaker-features":!0},browsableTypes=new Set(["action","campaignFeature","feat","kit","hazard","npc","spell",...PHYSICAL_ITEM_TYPES]),typeToTab=new Map([["action","action"],["campaignFeature","campaignFeature"],["feat","feat"],["kit","equipment"],["hazard","hazard"],["npc","bestiary"],["spell","spell"],...Array.from(PHYSICAL_ITEM_TYPES).map(t=>[t,"equipment"])]);for(const pack of game.packs){const tabNames=uniq(uniq(pack.index.map(entry=>entry.type)).filter(t=>setHasElement(browsableTypes,t)).flatMap(t=>typeToTab.get(t)??[]));for(const tabName of tabNames){const load=this.settings[tabName]?.[pack.collection]?.load??loadDefault[tabName]??!!loadDefault[pack.collection];settings[tabName][pack.collection]={load,name:pack.metadata.label,package:pack.metadata.packageName}}}for(const tab of this.dataTabsList)settings[tab]=Object.fromEntries(Object.entries(settings[tab]).sort(([_collectionA,dataA],[_collectionB,dataB])=>(dataA?.name??"")>(dataB?.name??"")?1:-1));this.settings=settings}async openTab(tabName,filter2){return this.activeTab=tabName,tabName!=="settings"&&filter2?this.tabs[tabName].open(filter2):this.loadTab(tabName)}async openActionTab(options){const actionTab=this.tabs.action,filter2=await actionTab.getFilterData(),{types}=filter2.checkboxes,{traits}=filter2.multiselects;types.selected=[];for(const type in types.options)options.types?.includes(type)&&(types.options[type].selected=!0,types.selected.push(type));const traitFilters=options.traits??[];if(traits.selected=traitFilters.length?traits.options.filter(trait=>traitFilters.includes(trait.value)):[],options.categories?.length){const optionsToSwitch=pick(filter2.checkboxes.category.options,options.categories);Object.values(optionsToSwitch).forEach(o=>o.selected=!0),filter2.checkboxes.category.selected=Object.keys(optionsToSwitch)}actionTab.open(filter2)}async openSpellTab(entry,maxRank=10,category=null){const spellTab=this.tabs.spell,filter2=await spellTab.getFilterData(),{traditions}=filter2.checkboxes;if(category&&filter2.checkboxes.category.options[category]&&(filter2.checkboxes.category.options[category].selected=!0,filter2.checkboxes.category.selected.push(category)),(entry.isRitual||entry.isFocusPool)&&(filter2.checkboxes.category.options[entry.category].selected=!0,filter2.checkboxes.category.selected.push(entry.category)),maxRank){const ranks=Array.from(Array(maxRank).keys()).map(l=>String(l+1));for(const rank of ranks)filter2.checkboxes.rank.options[rank].selected=!0,filter2.checkboxes.rank.selected.push(rank);(entry.isPrepared||entry.isSpontaneous||entry.isInnate)&&!category&&(filter2.checkboxes.category.options.spell.selected=!0,filter2.checkboxes.category.selected.push("spell"))}entry.tradition&&!entry.isFocusPool&&!entry.isRitual&&(traditions.options[entry.tradition].selected=!0,traditions.selected.push(entry.tradition)),spellTab.open(filter2)}async loadTab(tabName){if(this.activeTab=tabName,tabName==="settings"){await this.packLoader.updateSources(this.loadedPacksAll()),await this.render(!0);return}if(!this.dataTabsList.includes(tabName))throw ErrorPF2e(`Unknown tab "${tabName}"`);const currentTab=this.tabs[tabName];currentTab.isInitialized||await currentTab.init(),await this.render(!0,{focus:!0})}loadedPacks(tab){return tab==="settings"?[]:Object.entries(this.settings[tab]??[]).flatMap(([collection,info])=>info?.load?[collection]:[])}loadedPacksAll(){return uniq(this.dataTabsList.flatMap(t=>this.loadedPacks(t))).sort()}activateListeners($html){super.activateListeners($html);const html=$html[0],activeTabName=this.activeTab;if(this.navigationTab.active!==activeTabName&&this.navigationTab.activate(activeTabName),activeTabName==="settings"){const settings=htmlQuery(html,".compendium-browser-settings"),form=settings?.querySelector("form");if(!form)return;htmlQuery(settings,"button[data-action=save-settings]")?.addEventListener("click",async()=>{const formData=new FormData(form);for(const[t,packs]of Object.entries(this.settings))for(const[key,pack]of Object.entries(packs))pack.load=formData.has(`${t}-${key}`);await game.settings.set("pf2e","compendiumBrowserPacks",this.settings);for(const[key,source]of Object.entries(this.packLoader.sourcesSettings.sources)){if(!source?.name){delete this.packLoader.sourcesSettings.sources[key];continue}source.load=formData.has(`source-${key}`)}this.packLoader.sourcesSettings.showEmptySources=formData.has("show-empty-sources"),this.packLoader.sourcesSettings.showUnknownSources=formData.has("show-unknown-sources"),this.packLoader.sourcesSettings.ignoreAsGM=formData.has("ignore-as-gm"),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await this.#resetInitializedTabs(),this.render(!0),ui.notifications.info("PF2E.BrowserSettingsSaved",{localize:!0})});const sourceSearch=htmlQuery(form,"input[data-element=setting-sources-search]"),sourceToggle=htmlQuery(form,"input[data-action=setting-sources-toggle-visible]"),sourceSettings=htmlQueryAll(form,"label[data-element=setting-source]");sourceSearch?.addEventListener("input",()=>{const value=sourceSearch.value?.trim().toLocaleLowerCase(game.i18n.lang);for(const element of sourceSettings){const name2=element.dataset.name?.toLocaleLowerCase(game.i18n.lang),shouldBeHidden=!!value&&!!name2&&!name2.includes(value);element.classList.toggle("hidden",shouldBeHidden)}sourceToggle&&(sourceToggle.checked=!1)}),sourceToggle?.addEventListener("click",()=>{for(const element of sourceSettings){const checkbox=htmlQuery(element,"input[type=checkbox]");!element.classList.contains("hidden")&&checkbox&&(checkbox.checked=sourceToggle.checked)}}),htmlQuery(form,"button[data-action=settings-sources-delete]")?.addEventListener("click",async()=>{const localize=localizer("PF2E.SETTINGS.CompendiumBrowserSources");await Dialog.confirm({title:localize("DeleteAllTitle"),content:`
|
|
<p>
|
|
${localize("DeleteAllQuestion")}
|
|
</p>
|
|
<p>
|
|
${localize("DeleteAllInfo")}
|
|
</p>
|
|
`})&&(await this.packLoader.hardReset(this.loadedPacksAll()),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await this.#resetInitializedTabs(),this.render(!0))});return}const currentTab=this.tabs[activeTabName],controlArea=html.querySelector("div.control-area");if(!controlArea)return;const search=controlArea.querySelector("input[name=textFilter]");search&&search.addEventListener("input",()=>{currentTab.filterData.search.text=search.value,this.#clearScrollLimit(),this.#renderResultList({replace:!0})});const sortContainer=controlArea.querySelector("div.sortcontainer");if(sortContainer){const order=sortContainer.querySelector("select.order");order&&order.addEventListener("change",()=>{currentTab.filterData.order.by=order.value??"name",this.#clearScrollLimit(!0)});const directionAnchor=sortContainer.querySelector("a.direction");directionAnchor&&directionAnchor.addEventListener("click",()=>{const direction=directionAnchor.dataset.direction??"asc";currentTab.filterData.order.direction=direction==="asc"?"desc":"asc",this.#clearScrollLimit(!0)})}if(activeTabName==="spell"){const timeFilter=controlArea.querySelector("select[name=timefilter]");timeFilter&&timeFilter.addEventListener("change",()=>{if(!currentTab.isOfType("spell"))return;const filterData=currentTab.filterData;filterData.selects?.timefilter&&(filterData.selects.timefilter.selected=timeFilter.value,this.#clearScrollLimit(!0))})}controlArea.querySelector("button.clear-filters")?.addEventListener("click",()=>{this.#resetFilters(),this.#clearScrollLimit(!0)}),htmlQuery(html,"[data-action=create-roll-table]")?.addEventListener("click",()=>currentTab.createRollTable()),htmlQuery(html,"[data-action=add-to-roll-table]")?.addEventListener("click",async()=>{game.tables.contents.length&¤tTab.addToRollTable()});const filterContainers=controlArea.querySelectorAll("div.filtercontainer");for(const container of Array.from(filterContainers)){const{filterType,filterName}=container.dataset;container.querySelector("button[data-action=clear-filter]")?.addEventListener("click",event2=>{switch(event2.stopImmediatePropagation(),filterType){case"checkboxes":{const checkboxes=currentTab.filterData.checkboxes;if(objectHasKey(checkboxes,filterName)){for(const option of Object.values(checkboxes[filterName].options))option.selected=!1;checkboxes[filterName].selected=[],this.render(!0)}break}case"ranges":if(currentTab.isOfType("equipment")){const ranges=currentTab.filterData.ranges;objectHasKey(ranges,filterName)&&(ranges[filterName].values=currentTab.defaultFilterData.ranges[filterName].values,ranges[filterName].changed=!1,this.render(!0))}}});const title=container.querySelector("div.title");if(title?.addEventListener("click",()=>{const toggleFilter=__name2(filter2=>{filter2.isExpanded=!filter2.isExpanded;const contentElement=title.nextElementSibling;contentElement instanceof HTMLElement&&(filter2.isExpanded?contentElement.style.display="":contentElement.style.display="none")},"toggleFilter");switch(filterType){case"checkboxes":{objectHasKey(currentTab.filterData.checkboxes,filterName)&&toggleFilter(currentTab.filterData.checkboxes[filterName]);break}case"ranges":{if(!currentTab.isOfType("equipment"))return;objectHasKey(currentTab.filterData.ranges,filterName)&&toggleFilter(currentTab.filterData.ranges[filterName]);break}case"sliders":{if(!currentTab.isOfType("bestiary","equipment","feat","campaignFeature","hazard"))return;objectHasKey(currentTab.filterData.sliders,filterName)&&toggleFilter(currentTab.filterData.sliders[filterName]);break}}}),filterType==="checkboxes"&&container.querySelectorAll("input[type=checkbox]").forEach(checkboxElement=>{checkboxElement.addEventListener("click",()=>{if(objectHasKey(currentTab.filterData.checkboxes,filterName)){const optionName=checkboxElement.name,checkbox=currentTab.filterData.checkboxes[filterName],option=checkbox.options[optionName];option.selected=!option.selected,option.selected?checkbox.selected.push(optionName):checkbox.selected=checkbox.selected.filter(name2=>name2!==optionName),this.#clearScrollLimit(!0)}})}),filterType==="ranges"&&container.querySelectorAll("input[name*=Bound]").forEach(range2=>{range2.addEventListener("keyup",event2=>{if(!currentTab.isOfType("equipment")||event2.key!=="Enter")return;const ranges=currentTab.filterData.ranges;if(ranges&&objectHasKey(ranges,filterName)){const range22=ranges[filterName],lowerBound=container.querySelector("input[name*=lowerBound]")?.value??"",upperBound=container.querySelector("input[name*=upperBound]")?.value??"",values=currentTab.parseRangeFilterInput(filterName,lowerBound,upperBound);range22.values=values,range22.changed=!0,this.#clearScrollLimit(!0)}})}),filterType==="multiselects"){const multiselects=currentTab.filterData.multiselects;if(!multiselects)continue;if(objectHasKey(multiselects,filterName)){const multiselect=container.querySelector(`input[name=${filterName}][data-tagify-select]`);if(!multiselect)continue;const data=multiselects[filterName],tagify2=new Tagify(multiselect,{enforceWhitelist:!0,keepInvalidTags:!1,editTags:!1,tagTextProp:"label",dropdown:{enabled:0,fuzzySearch:!1,mapValueTo:"label",maxItems:data.options.length,searchKeys:["label"]},whitelist:data.options,transformTag(tagData){data.selected.find(s=>s.value===tagData.value)?.not&&(tagData.class="conjunction-not")}});tagify2.on("click",event2=>{const target=event2.detail.event.target;if(!target)return;if(htmlClosest(target,"[data-action]")?.dataset?.action==="toggle-not"){const value=event2.detail.data.value,selected=data.selected.find(s=>s.value===value);selected&&(selected.not=!selected.not,this.render())}}),tagify2.on("change",event2=>{const selections=JSON.parse(event2.detail.value||"[]");Array.isArray(selections)&&selections.every(s=>isObject(s)&&typeof s.value=="string")&&(data.selected=selections,this.render())});for(const element of htmlQueryAll(container,`input[name=${filterName}-filter-conjunction]`))element.addEventListener("change",()=>{const value=element.value;(value==="and"||value==="or")&&(data.conjunction=value,this.render())});for(const tag of htmlQueryAll(container,"tag")){const icon=fontAwesomeIcon("ban",{style:"solid"});icon.classList.add("fa-2xs");const notButton=createHTMLElement("a",{classes:["conjunction-not-button"],children:[icon],dataset:{action:"toggle-not"}});tag.appendChild(notButton)}}}if(filterType==="sliders"){if(!currentTab.isOfType("bestiary","campaignFeature","equipment","feat","hazard"))continue;const sliders=currentTab.filterData.sliders;if(!sliders)continue;if(objectHasKey(sliders,filterName)){const sliderElement=container.querySelector(`div.slider-${filterName}`);if(!sliderElement)continue;const data=sliders[filterName];noUiSlider.create(sliderElement,{range:{min:data.values.lowerLimit,max:data.values.upperLimit},start:[data.values.min,data.values.max],tooltips:{to(value){return Math.floor(value).toString()}},connect:[!1,!0,!1],behaviour:"snap",step:data.values.step}).on("change",values=>{const[min,max]=values.map(value=>Number(value));data.values.min=min,data.values.max=max;const $minLabel=$html.find(`label.${name}-min-label`),$maxLabel=$html.find(`label.${name}-max-label`);$minLabel.text(min),$maxLabel.text(max),this.#clearScrollLimit(!0)}),sliderElement.querySelectorAll(".noUi-handle").forEach(element=>{element.classList.add("handle")}),sliderElement.querySelectorAll(".noUi-connect").forEach(element=>{element.classList.add("range_selected")})}}}const list=html.querySelector(".tab.active ul.item-list");list&&(list.addEventListener("scroll",()=>{if(list.scrollTop+list.clientHeight>=list.scrollHeight-5){const currentValue=currentTab.scrollLimit,maxValue=currentTab.totalItemCount??0;currentValue<maxValue&&(currentTab.scrollLimit=Math.clamped(currentValue+100,100,maxValue),this.#renderResultList({list,start:currentValue}))}}),this.#renderResultList({list}))}async#resetInitializedTabs(){for(const tab of Object.values(this.tabs))tab.isInitialized&&(await tab.init(),tab.scrollLimit=100)}async#renderResultList({list,start=0,replace=!1}){const currentTab=this.activeTab!=="settings"?this.tabs[this.activeTab]:null,html=this.element[0];if(!currentTab)return;if(!list){const listElement=html.querySelector(".tab.active ul.item-list");if(!listElement)return;list=listElement}const newResults=await currentTab.renderResults(start);this.#activateResultListeners(newResults);const fragment=document.createDocumentFragment();fragment.append(...newResults),replace?list.replaceChildren(fragment):list.append(fragment);for(const dragDropHandler of this._dragDrop)dragDropHandler.bind(html)}#activateResultListeners(liElements=[]){for(const liElement of liElements){const{entryUuid}=liElement.dataset;if(!entryUuid)continue;const nameAnchor=liElement.querySelector("div.name > a");nameAnchor&&nameAnchor.addEventListener("click",async()=>{const document2=await fromUuid(entryUuid);document2?.sheet&&document2.sheet.render(!0)}),this.activeTab==="equipment"&&(liElement.querySelector("a[data-action=take-item]")?.addEventListener("click",()=>{this.#takePhysicalItem(entryUuid)}),liElement.querySelector("a[data-action=buy-item]")?.addEventListener("click",()=>{this.#buyPhysicalItem(entryUuid)}))}}async#takePhysicalItem(uuid){const actors=getSelectedOrOwnActors(["character","loot","npc"]),item=await this.#getPhysicalItem(uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}for(const actor of actors)await actor.inventory.add(item,{stack:!0});actors.length===1&&game.user.character&&actors[0]===game.user.character?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItemToCharacter",{item:item.name,character:game.user.character.name})):ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItem",{item:item.name}))}async#buyPhysicalItem(uuid){const actors=getSelectedOrOwnActors(["character","loot","npc"]),item=await this.#getPhysicalItem(uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}let purchasesSucceeded=0;for(const actor of actors)await actor.inventory.removeCoins(item.price.value)&&(purchasesSucceeded=purchasesSucceeded+1,await actor.inventory.add(item,{stack:!0}));actors.length===1?purchasesSucceeded===1?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithCharacter",{item:item.name,character:actors[0].name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithCharacter",{item:item.name,character:actors[0].name})):purchasesSucceeded===actors.length?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithAllCharacters",{item:item.name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithSomeCharacters",{item:item.name}))}async#getPhysicalItem(uuid){const item=await fromUuid(uuid);if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))throw ErrorPF2e("Unexpected failure retrieving compendium item");return item}_canDragStart(){return!0}_canDragDrop(){return!0}_onDragStart(event2){this.element.animate({opacity:.125},250);const item=$(event2.currentTarget)[0];event2.dataTransfer.setData("text/plain",JSON.stringify({type:item.dataset.type,uuid:item.dataset.entryUuid})),event2.dataTransfer.setData("from-browser","true"),item.addEventListener("dragend",()=>{window.setTimeout(()=>{this.element.animate({opacity:1},250,()=>{this.element.css({pointerEvents:""})})},500)},{once:!0})}_onDragOver(event2){super._onDragOver(event2),event2.dataTransfer.types.includes("from-browser")&&this.element.css({pointerEvents:"none"})}getData(){const activeTab=this.activeTab,tab=objectHasKey(this.tabs,activeTab)?this.tabs[activeTab]:null,settings={settings:this.settings,sources:this.packLoader.sourcesSettings};return{user:game.user,[activeTab]:activeTab==="settings"?settings:{filterData:tab?.filterData},scrollLimit:tab?.scrollLimit,showCampaign:game.settings.get("pf2e","campaignType")!=="none"}}#resetFilters(){const activeTab=this.activeTab;activeTab!=="settings"&&this.tabs[activeTab].resetFilters()}#clearScrollLimit(render=!1){const tab=this.activeTab;if(tab==="settings")return;const list=htmlQuery(this.element[0],".tab.active ul.item-list");list&&(list.scrollTop=0,this.tabs[tab].scrollLimit=100,render&&this.render())}}class EffectsPanel extends Application{static{__name(this,"EffectsPanel")}static{__name2(this,"EffectsPanel")}get token(){return canvas.tokens.controlled.at(0)?.document??null}get actor(){return this.token?.actor??game.user?.character??null}refresh=foundry.utils.debounce(this.render,100);static get defaultOptions(){return{...super.defaultOptions,id:"pf2e-effects-panel",popOut:!1,template:"systems/pf2e/templates/system/effects-panel.hbs"}}async getData(options){const{actor}=this;if(!actor||!game.user.settings.showEffectPanel)return{afflictions:[],conditions:[],effects:[],descriptions:{afflictions:[],conditions:[],effects:[]},actor:null,user:{isGM:!1}};const effects=actor.itemTypes.effect.map(effect=>{const duration=effect.totalDuration,{system}=effect;if(duration===1/0)system.duration.unit==="encounter"?system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):game.i18n.localize("PF2E.EffectPanel.UntilEncounterEnds"):system.remaining=game.i18n.localize("PF2E.EffectPanel.UnlimitedDuration");else{const duration2=effect.remainingDuration;system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):this.#getRemainingDurationLabel(duration2.remaining,system.start.initiative??0,system.duration.expiry)}return effect})??[],conditions=actor.conditions.active,afflictions=actor.itemTypes.affliction,descriptions={afflictions:await this.#getEnrichedDescriptions(afflictions),conditions:await this.#getEnrichedDescriptions(conditions),effects:await this.#getEnrichedDescriptions(effects)};return{...await super.getData(options),afflictions,conditions,descriptions,effects,actor,user:{isGM:game.user.isGM}}}activateListeners($html){super.activateListeners($html);const html=$html[0];InlineRollLinks.listen(html,this.actor);for(const effectEl of htmlQueryAll(html,".effect-item[data-item-id]")){const{actor}=this,itemId=effectEl.dataset.itemId??"",effect=actor?.conditions.get(itemId)??actor?.items.get(itemId);if(!actor||!effect)continue;const iconElem=effectEl.querySelector(":scope > .icon");iconElem?.addEventListener("click",async()=>{actor&&effect.isOfType("condition")&&effect.slug==="persistent-damage"?await effect.onEndTurn({token:this.token}):effect instanceof AbstractEffectPF2e&&await effect.increase()}),iconElem?.addEventListener("contextmenu",async()=>{effect instanceof AbstractEffectPF2e?await effect.decrease():this.refresh()}),effectEl.querySelector("[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.rollRecovery()}),effectEl.querySelector("[data-action=edit]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.slug==="persistent-damage"?new PersistentDamageDialog(actor,{editing:effect.id}).render(!0):effect.sheet.render(!0)}),effectEl.querySelector("[data-action=send-to-chat]")?.addEventListener("click",()=>{effect.toMessage()});const valueContainer=htmlQuery(iconElem,".value"),textElement=htmlQuery(valueContainer,"strong");if(valueContainer&&textElement){const parentWidth=valueContainer.clientWidth,scale=textElement.clientWidth?Math.clamped(parentWidth/textElement.clientWidth,.75,1):1;scale<1&&(valueContainer.style.transformOrigin="left",valueContainer.style.transform=`scaleX(${scale})`,valueContainer.style.width=`${1/scale*100+1}%`),textElement.style.display="inline"}}}#getRemainingDurationLabel(remaining,initiative,expiry){if(remaining>=63072e3)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleYears",{years:Math.floor(remaining/31536e3)});if(remaining>=31536e3)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleYear");if(remaining>=1209600)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleWeeks",{weeks:Math.floor(remaining/604800)});if(remaining>604800)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleWeek");if(remaining>=172800)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleDays",{days:Math.floor(remaining/86400)});if(remaining>7200)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleHours",{hours:Math.floor(remaining/3600)});if(remaining>120)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleMinutes",{minutes:Math.floor(remaining/60)});if(remaining>=12)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleRounds",{rounds:Math.floor(remaining/6)});if(remaining>=6)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleRound");if(remaining>=2)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleSeconds",{seconds:remaining});if(remaining===1)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleSecond");{const key=expiry==="turn-end"?"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnEnd":"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnStart";return game.i18n.format(key,{initiative})}}async#getEnrichedDescriptions(effects){return await Promise.all(effects.map(async effect=>{const rollData={actor:"actor"in effect?effect.actor:null,item:effect};return await TextEditor.enrichHTML(effect.description,{async:!0,rollData})}))}}class LicenseViewer extends Application{static{__name(this,"LicenseViewer")}static{__name2(this,"LicenseViewer")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"license-viewer",title:game.i18n.localize("PF2E.LicenseViewer.Label"),template:"systems/pf2e/templates/packs/license-viewer.hbs",width:500,height:600,resizable:!0,tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"}]})}}const debouncedRender=foundry.utils.debounce(()=>{canvas.tokens.hud.render()},20);class StatusEffects{static{__name(this,"StatusEffects")}static{__name2(this,"StatusEffects")}static#lastCombatantToken=null;static#ICON_THEME_DIRS={default:"systems/pf2e/icons/conditions/",blackWhite:"systems/pf2e/icons/conditions-2/"};static#conditionSummaries=null;static initialize(){const iconTheme=game.settings.get("pf2e","statusEffectType");CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),CONFIG.PF2E.statusEffects.lastIconTheme=iconTheme,CONFIG.PF2E.statusEffects.iconDir=this.#ICON_THEME_DIRS[iconTheme],this.#updateStatusIcons()}static reset(){CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),this.#updateStatusIcons(),this.refresh()}static get conditions(){return this.#conditionSummaries??=mapToObj(Array.from(CONDITION_SLUGS),s=>[s,{name:game.i18n.localize(`PF2E.condition.${s}.name`),rules:game.i18n.localize(`PF2E.condition.${s}.rules`),summary:game.i18n.localize(`PF2E.condition.${s}.summary`)}])}static async migrateStatusEffectUrls(chosenSetting){console.debug("PF2e System | Changing status effect icon types");const iconDir=this.#ICON_THEME_DIRS[chosenSetting];if(CONFIG.PF2E.statusEffects.iconDir=iconDir,CONFIG.PF2E.statusEffects.lastIconTheme=chosenSetting,this.#updateStatusIcons(),await resetActors(),canvas.ready)for(const token of canvas.tokens.placeables)token.drawEffects()}static#activateListeners(html){for(const control of htmlQueryAll(html,".effect-control"))control.addEventListener("click",event2=>{this.#setStatusValue(control,event2)}),control.addEventListener("contextmenu",event2=>{this.#setStatusValue(control,event2)}),control.addEventListener("mouseover",()=>{this.#showStatusLabel(control)}),control.addEventListener("mouseout",()=>{this.#showStatusLabel(control)})}static#updateStatusIcons(){const directory=game.settings.get("pf2e","statusEffectType")==="default"?"conditions":"conditions-2";CONFIG.statusEffects=Object.entries(CONFIG.PF2E.statusEffects.conditions).map(([id,label])=>({id,label,icon:`systems/pf2e/icons/${directory}/${id}.webp`})),CONFIG.statusEffects.push({id:"dead",label:"PF2E.Actor.Dead",icon:CONFIG.controlIcons.defeated})}static async onRenderTokenHUD(html,tokenData){const token=canvas.tokens.get(tokenData._id??"");if(!token)return;const iconGrid=html.querySelector(".status-effects");if(!iconGrid)throw ErrorPF2e("Unexpected error retrieving status effects grid");const affectingConditions=token.actor?.conditions.active.filter(c=>c.isInHUD)??[],titleBar=document.createElement("div");titleBar.className="title-bar",iconGrid.append(titleBar);const statusIcons=iconGrid.querySelectorAll(".effect-control");for(const icon of statusIcons){const picture=document.createElement("picture");picture.classList.add("effect-control"),picture.dataset.statusId=icon.dataset.statusId,picture.title=icon.title;const iconSrc=icon.getAttribute("src");picture.setAttribute("src",iconSrc);const newIcon=document.createElement("img");newIcon.src=iconSrc,picture.append(newIcon),icon.replaceWith(picture);const slug=picture.dataset.statusId??"",actorType=token.actor?.type??"";(slug==="hidden"&&["loot","vehicle"].includes(actorType)||slug==="broken"&&!["loot","vehicle"].includes(actorType))&&(picture.style.display="none");const affecting=affectingConditions.filter(c=>c.slug===slug);if((affecting.length>0||iconSrc===token.document.overlayEffect)&&picture.classList.add("active"),affecting.length>0){const isOverridden=affecting.every(c=>c.system.references.overriddenBy.length>0),isLocked=affecting.every(c=>c.isLocked),hasValue=affecting.some(c=>c.value);if(isOverridden){picture.classList.add("overridden");const badge=fontAwesomeIcon("angle-double-down");badge.classList.add("badge"),picture.append(badge)}else if(isLocked){picture.classList.add("locked");const badge=fontAwesomeIcon("lock");badge.classList.add("badge"),picture.append(badge)}else if(hasValue){picture.classList.add("valued");const badge=document.createElement("i");badge.classList.add("badge");const value=Math.max(...affecting.map(c=>c.value??1));badge.innerText=value.toString(),picture.append(badge)}}}this.#activateListeners(iconGrid)}static onUpdateEncounter(encounter){if(!(game.user.isGM&&game.settings.get("pf2e","statusEffectShowCombatMessage")))return;if(!encounter.started){this.#lastCombatantToken=null;return}const{combatant}=encounter,token=combatant?.token;combatant&&token&&token.id!==this.#lastCombatantToken&&typeof combatant.initiative=="number"&&!combatant.defeated&&(this.#lastCombatantToken=token.id,this.#createChatMessage(token,combatant.hidden))}static#showStatusLabel(control){const titleBar=control.closest(".status-effects")?.querySelector(".title-bar");titleBar&&control.title&&(titleBar.innerText=control.title,titleBar.classList.toggle("active"))}static async#setStatusValue(control,event2){event2.preventDefault(),event2.stopPropagation();const slug=control.dataset.statusId;if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const tokensAndActors=uniqBy(compact(canvas.tokens.controlled.map(t=>t.actor?[t,t.actor]:null)),([,a])=>a);for(const[token,actor]of tokensAndActors){if(slug==="persistent-damage"){await new PersistentDamageDialog(actor).render(!0);continue}const condition=actor.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>c.isInHUD&&!c.system.references.parent);if(event2.type==="click")typeof condition?.value=="number"?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value+1):objectHasKey(CONFIG.PF2E.conditionTypes,slug)?actor.increaseCondition(slug):this.#toggleStatus(token,control,event2);else if(event2.type==="contextmenu")if(event2.ctrlKey&&slug!=="dead"){const conditionIds=actor.conditions.bySlug(slug,{temporary:!1}).map(c=>c.id);actor.deleteEmbeddedDocuments("Item",conditionIds)}else condition?.value?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value-1):this.#toggleStatus(token,control,event2)}}static async#toggleStatus(token,control,event2){const{actor}=token;if(!actor)return;const slug=control.dataset.statusId??"";if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const iconSrc=control.querySelector("img")?.getAttribute("src"),affecting=actor?.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>!c.system.references.parent),conditionIds=[];if(event2.type==="click"&&!affecting)if(objectHasKey(CONFIG.PF2E.conditionTypes,slug)){const newCondition=game.pf2e.ConditionManager.getCondition(slug).toObject();await token.actor?.createEmbeddedDocuments("Item",[newCondition])}else iconSrc&&(event2.shiftKey||control.dataset.statusId==="dead")&&await token.toggleEffect(iconSrc,{overlay:!0,active:!0});else event2.type==="contextmenu"&&(affecting&&conditionIds.push(affecting.id),conditionIds.length>0?await token.actor?.deleteEmbeddedDocuments("Item",conditionIds):token.document.overlayEffect===iconSrc&&await token.document.update({overlayEffect:""}))}static async#createChatMessage(token,whisper=!1){if(!token?.actor)return null;const conditions=await Promise.all(token.actor.conditions.active.map(async c=>({...pick(c,["name","img"]),description:await TextEditor.enrichHTML(c.description,{async:!0})})));if(conditions.length===0)return null;const content=await renderTemplate("systems/pf2e/templates/chat/participant-conditions.hbs",{conditions}),messageSource={user:game.user.id,speaker:{...ChatMessagePF2e.getSpeaker({token,actor:token.actor}),alias:game.i18n.format("PF2E.StatusEffects",{name:token.name})},content,type:CONST.CHAT_MESSAGE_TYPES.OTHER};return(!token.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition")||whisper)&&(messageSource.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),ChatMessagePF2e.create(messageSource)}static refresh(){canvas.ready&&canvas.tokens.hud.rendered&&debouncedRender()}}async function remigrate(versionRange){if(!game.ready){ui.notifications.warn("PF2E.Migrations.WorldNotReady",{localize:!0});return}if(game.user.role!==CONST.USER_ROLES.GAMEMASTER){ui.notifications.error("PF2E.Migrations.OnlyGMCanUse",{localize:!0});return}const migrations=MigrationList.constructRange(versionRange.from,versionRange.to);if(migrations.length===0||versionRange.from<MigrationRunner.RECOMMENDED_SAFE_VERSION){ui.notifications.error(game.i18n.format("PF2E.Migrations.OutsideSchemaRange",{minimum:MigrationRunner.RECOMMENDED_SAFE_VERSION,maximum:MigrationRunner.LATEST_SCHEMA_VERSION}));return}return new MigrationRunner(migrations).runMigration(!0)}__name(remigrate,"remigrate"),__name2(remigrate,"remigrate");class BaseActionVariant{static{__name(this,"BaseActionVariant")}static{__name2(this,"BaseActionVariant")}#action;#cost;#description;name;#slug;#traits;constructor(action2,data){this.#action=action2,data&&(this.#cost=data.cost,this.#description=data.description,this.name=data.name?.trim(),this.#slug=data.slug?.trim(),this.#traits=data.traits)}get cost(){return this.#cost??this.#action.cost}get description(){return this.#description?.trim()||this.#action.description}get glyph(){return getActionGlyph(this.cost??null)}get slug(){return this.#slug||sluggify(this.name??"")||this.#action.slug}get traits(){return this.#traits??this.#action.traits}async toMessage(options){const description=this.description||this.#action.description,name2=this.name?`${game.i18n.localize(this.#action.name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(this.#action.name),traitLabels=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traits=this.traits.map(trait=>({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),content=await renderTemplate("/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs",{description,glyph:this.glyph,name:name2,traits});return ChatMessagePF2e.create({blind:options?.blind,content,whisper:options?.whisper})}}class BaseAction{static{__name(this,"BaseAction")}static{__name2(this,"BaseAction")}cost;description;img;name;slug;traits;#variants;constructor(data){this.cost=data.cost,this.description=data.description,this.img=data.img,this.name=data.name.trim(),this.slug=data.slug?.trim()||sluggify(this.name),this.traits=data.traits??[],this.#variants=Array.isArray(data.variants)?data.variants.map(this.toActionVariant.bind(this)):data.variants?[this.toActionVariant(data.variants)]:[]}get glyph(){if(this.#variants.length===1)return this.#variants[0].glyph;const numbers=this.#variants.filter(variant=>typeof variant.cost=="number").sort();if(this.#variants.length===numbers.length&&numbers.length>1){const first=numbers.shift()?.cost,last=numbers.pop()?.cost,key=first===last?String(first):first===2||last===2?`${first} or ${last}`:`${first} to ${last}`;return getActionGlyph(key)}return getActionGlyph(this.cost??"")}get variants(){const variants=this.#variants.map(variant=>[variant.slug,variant]);return new Collection(variants)}async getDefaultVariant(options){const variants=this.variants;if(options?.variant&&!variants.size){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.None",{action:this.name,variant:options.variant});return Promise.reject(reason)}if(!options?.variant&&variants.size>1){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Multiple",{action:this.name});return Promise.reject(reason)}const variant=variants.get(options?.variant??"");if(options?.variant&&!variant){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Nonexisting",{action:this.name,variant:options.variant});return Promise.reject(reason)}return variant??this.toActionVariant()}async toMessage(options){return((options?.variant?await this.getDefaultVariant(options):void 0)??this.toActionVariant()).toMessage(options)}async use(options){return(await this.getDefaultVariant(options)??this.toActionVariant()).use(options)}}async function toEffectItem(effect){return typeof effect=="string"?await fromUuid(effect):effect}__name(toEffectItem,"toEffectItem"),__name2(toEffectItem,"toEffectItem");class SimpleActionVariant extends BaseActionVariant{static{__name(this,"SimpleActionVariant")}static{__name2(this,"SimpleActionVariant")}#action;#effect;constructor(action2,data){super(action2,data),this.#action=action2,this.#effect=data?.effect??action2.effect}get effect(){return this.#effect??this.#action.effect}async use(options={}){const actors=[];if(Array.isArray(options.actors)?actors.push(...options.actors):options.actors?actors.push(options.actors):actors.push(...getSelectedOrOwnActors()),actors.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const traitLabels=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traits=this.traits.concat(options.traits??[]).map(trait=>({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),effect=options?.effect===!1?void 0:await toEffectItem(options?.effect??this.effect),name2=this.name?`${game.i18n.localize(this.#action.name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(this.#action.name),flavor=await renderTemplate("systems/pf2e/templates/actors/actions/simple/chat-message-flavor.hbs",{effect,glyph:this.glyph,name:name2,traits}),results=[];for(const actor of actors){const message=await ChatMessage.create({flavor,speaker:ChatMessage.getSpeaker({actor})}),item=effect&&actor.isOwner?(await actor.createEmbeddedDocuments("Item",[effect.toObject()]))[0]:void 0;results.push({actor,effect:item,message})}return results}}class SimpleAction extends BaseAction{static{__name(this,"SimpleAction")}static{__name2(this,"SimpleAction")}effect;constructor(data){super(data),this.effect=data.effect}toActionVariant(data){return new SimpleActionVariant(this,data)}}function toRollNoteSource(data){return data.selector??="",data}__name(toRollNoteSource,"toRollNoteSource"),__name2(toRollNoteSource,"toRollNoteSource");class SingleCheckActionVariant extends BaseActionVariant{static{__name(this,"SingleCheckActionVariant")}static{__name2(this,"SingleCheckActionVariant")}#action;#difficultyClass;#modifiers;#notes;#rollOptions;#statistic;constructor(action2,data){super(action2,data),this.#action=action2,data&&(this.#difficultyClass=data.difficultyClass,this.#modifiers=data?.modifiers,this.#notes=data.notes?data.notes.map(toRollNoteSource):void 0,this.#rollOptions=data.rollOptions,this.#statistic=data.statistic)}get difficultyClass(){return this.#difficultyClass??this.#action.difficultyClass}get modifiers(){return this.#modifiers??this.#action.modifiers}get notes(){return this.#notes??this.#action.notes}get rollOptions(){return this.#rollOptions??this.#action.rollOptions}get statistic(){return this.#statistic??this.#action.statistic}async use(options={}){const modifiers=this.modifiers.map(raw=>new ModifierPF2e(raw)).concat(options.modifiers??[]);if(options.multipleAttackPenalty){const map2=options.multipleAttackPenalty,modifier=map2>0?Math.min(2,map2)*-5:map2;modifiers.push(new ModifierPF2e({label:"PF2E.MultipleAttackPenalty",modifier}))}const notes=this.notes.concat(options.notes??[]).map(toRollNoteSource).map(note=>new RollNotePF2e(note)),rollOptions=this.rollOptions.concat(options.rollOptions??[]),slug=options.statistic?.trim()||this.statistic,title=this.name?`${game.i18n.localize(this.#action.name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(this.#action.name),results=[],difficultyClass=setHasElement(DC_SLUGS,options.difficultyClass)||isObject(options.difficultyClass)&&typeof options.difficultyClass.value=="number"?options.difficultyClass:this.difficultyClass;return await ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,title,actionGlyph:getActionGlyph(this.cost??null),callback:result=>results.push(result),checkContext:opts=>this.checkContext(opts,{modifiers,rollOptions,slug}),difficultyClass,event:options.event,extraNotes:selector=>notes.map(note=>(note.selector||=selector,note)),traits:this.traits.concat(options?.traits??[])}),results}checkContext(opts,data){return ActionMacroHelpers.defaultCheckContext(opts,data)}}class SingleCheckAction extends BaseAction{static{__name(this,"SingleCheckAction")}static{__name2(this,"SingleCheckAction")}difficultyClass;modifiers;notes;rollOptions;statistic;constructor(data){super(data),this.difficultyClass=data.difficultyClass,this.modifiers=data.modifiers??[],this.notes=(data.notes??[]).map(toRollNoteSource),this.rollOptions=data.rollOptions??[],this.statistic=data.statistic}toActionVariant(data){return new SingleCheckActionVariant(this,data)}}const PREFIX$l="PF2E.Actions.Balance";function balance(options){const slug=options?.skill??"acrobatics",rollOptions=["action:balance"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$l}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(balance,"balance"),__name2(balance,"balance");const action$y=new SingleCheckAction({cost:1,description:`${PREFIX$l}.Description`,name:`${PREFIX$l}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$l}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$l}.Notes.success`},{outcome:["failure"],text:`${PREFIX$l}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$l}.Notes.criticalFailure`}],rollOptions:["action:balance"],slug:"balance",statistic:"acrobatics",traits:["move"]}),PREFIX$k="PF2E.Actions.ManeuverInFlight";async function maneuverInFlight(options){const slug=options?.skill??"acrobatics",rollOptions=["action:maneuver-in-flight"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$k}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$k}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$k,"failure"),ActionMacroHelpers.note(selector,PREFIX$k,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(maneuverInFlight,"maneuverInFlight"),__name2(maneuverInFlight,"maneuverInFlight");const action$x=new SingleCheckAction({cost:1,description:`${PREFIX$k}.Description`,name:`${PREFIX$k}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$k}.Notes.success`},{outcome:["failure"],text:`${PREFIX$k}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$k}.Notes.criticalFailure`}],rollOptions:["action:maneuver-in-flight"],slug:"maneuver-in-flight",statistic:"acrobatics",traits:["move"]}),PREFIX$j="PF2E.Actions.Squeeze";function squeeze(options){const slug=options?.skill??"acrobatics",rollOptions=["action:squeeze"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$j}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(squeeze,"squeeze"),__name2(squeeze,"squeeze");const action$w=new SingleCheckAction({description:`${PREFIX$j}.Description`,name:`${PREFIX$j}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$j}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$j}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$j}.Notes.criticalFailure`}],rollOptions:["action:squeeze"],slug:"squeeze",statistic:"acrobatics",traits:["exploration","move"]}),PREFIX$i="PF2E.Actions.TumbleThrough";function tumbleThrough(options){const slug=options?.skill??"acrobatics",rollOptions=["action:tumble-through"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$i}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$i}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$i}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tumbleThrough,"tumbleThrough"),__name2(tumbleThrough,"tumbleThrough");const action$v=new SingleCheckAction({cost:1,description:`${PREFIX$i}.Description`,difficultyClass:"reflex",name:`${PREFIX$i}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$i}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$i}.Notes.failure`}],rollOptions:["action:tumble-through"],slug:"tumble-through",statistic:"acrobatics",traits:["move"]});function arcaneSlam(options){const{actor:target,token}=ActionMacroHelpers.target(),slug=options?.skill??"acrobatics",rollOptions=["action:arcane-slam"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.ArcaneSlam.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const attackerSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeDifference=attackerSize.difference(targetSize),sizeModifier=new ModifierPF2e("PF2E.Actions.ArcaneSlam.Modifier.SizeDifference",Math.clamped(2*sizeDifference,-4,4),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["automaton"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>{const notes=[ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalFailure")];if(!target){const translated=game.i18n.localize("PF2E.Actions.ArcaneSlam.Notes.NoTarget");notes.unshift(new RollNotePF2e({selector,text:`<p class="compact-text">${translated}</p>`,predicate:new PredicatePF2e,outcome:[]}))}return notes},target:()=>target&&token?{actor:target,token}:null}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(arcaneSlam,"arcaneSlam"),__name2(arcaneSlam,"arcaneSlam");const PREFIX$h="PF2E.Actions.Climb";function climb(options){const slug=options?.skill??"athletics",rollOptions=["action:climb"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$h}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$h,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$h,"success"),ActionMacroHelpers.note(selector,PREFIX$h,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(climb,"climb"),__name2(climb,"climb");const action$u=new SingleCheckAction({cost:1,description:`${PREFIX$h}.Description`,name:`${PREFIX$h}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$h}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$h}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$h}.Notes.criticalFailure`}],rollOptions:["action:climb"],slug:"climb",statistic:"athletics",traits:["move"]});function disarm(options){const slug=options?.skill??"athletics",rollOptions=["action:disarm"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Disarm.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"disarm")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.slug!=="basic-unarmed"){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disarm,"disarm"),__name2(disarm,"disarm");const PREFIX$g="PF2E.Actions.ForceOpen";function forceOpen(options){const slug=options?.skill??"athletics",rollOptions=["action:force-open"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$g}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(forceOpen,"forceOpen"),__name2(forceOpen,"forceOpen");const action$t=new SingleCheckAction({cost:1,description:`${PREFIX$g}.Description`,name:`${PREFIX$g}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$g}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$g}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$g}.Notes.criticalFailure`}],rollOptions:["action:force-open"],slug:"force-open",statistic:"athletics",traits:["attack"]});function grapple(options){const slug=options?.skill??"athletics",rollOptions=["action:grapple"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Grapple.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"grapple")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("grapple")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(grapple,"grapple"),__name2(grapple,"grapple");const PREFIX$f="PF2E.Actions.HighJump";function highJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:high-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:`${PREFIX$f}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??{value:30},extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$f,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$f,"success"),ActionMacroHelpers.note(selector,PREFIX$f,"failure"),ActionMacroHelpers.note(selector,PREFIX$f,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(highJump,"highJump"),__name2(highJump,"highJump");const action$s=new SingleCheckAction({cost:2,description:`${PREFIX$f}.Description`,difficultyClass:{value:30},name:`${PREFIX$f}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$f}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$f}.Notes.success`},{outcome:["failure"],text:`${PREFIX$f}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$f}.Notes.criticalFailure`}],rollOptions:["action:stride","action:leap","action:high-jump"],slug:"high-jump",statistic:"athletics",traits:["move"]}),PREFIX$e="PF2E.Actions.LongJump";function longJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:long-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:`${PREFIX$e}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??{value:15},extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$e}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$e,"failure"),ActionMacroHelpers.note(selector,PREFIX$e,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(longJump,"longJump"),__name2(longJump,"longJump");const action$r=new SingleCheckAction({cost:2,description:`${PREFIX$e}.Description`,difficultyClass:{value:15},name:`${PREFIX$e}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$e}.Notes.success`},{outcome:["failure"],text:`${PREFIX$e}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$e}.Notes.criticalFailure`}],rollOptions:["action:stride","action:leap","action:long-jump"],slug:"long-jump",statistic:"athletics",traits:["move"]}),PREFIX$d="PF2E.Actions.Reposition";function reposition(options){const slug=options?.skill??"athletics",modifiers=options?.modifiers,rollOptions=["action:reposition"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$d}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$d,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$d,"success"),ActionMacroHelpers.note(selector,PREFIX$d,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(reposition,"reposition"),__name2(reposition,"reposition");const action$q=new SingleCheckAction({cost:1,description:`${PREFIX$d}.Description`,difficultyClass:"fortitude",name:`${PREFIX$d}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$d}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$d}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$d}.Notes.criticalFailure`}],rollOptions:["action:reposition"],slug:"reposition",statistic:"athletics",traits:["attack"]});function shove(options){const slug=options?.skill??"athletics",rollOptions=["action:shove"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Shove.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"shove")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("shove")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(shove,"shove"),__name2(shove,"shove");const PREFIX$c="PF2E.Actions.Swim";function swim(options){const slug=options?.skill??"athletics",rollOptions=["action:swim"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$c}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$c,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$c,"success"),ActionMacroHelpers.note(selector,PREFIX$c,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(swim,"swim"),__name2(swim,"swim");const action$p=new SingleCheckAction({cost:1,description:`${PREFIX$c}.Description`,name:`${PREFIX$c}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$c}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$c}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$c}.Notes.criticalFailure`}],rollOptions:["action:swim"],slug:"swim",statistic:"athletics",traits:["move"]});function tripCheckContext(opts,data){const item=[...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"trip")??[],...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"ranged-trip")??[]].shift(),context=ActionMacroHelpers.defaultCheckContext(opts,{item:data.item,modifiers:data.modifiers,rollOptions:data.rollOptions,slug:data.slug});if(item&&context){const modifiers=context.modifiers?.length?[...context.modifiers]:[];if(item.traits.has("trip")||item.traits.has("ranged-trip")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,data.slug);modifier&&modifiers.push(modifier)}item.traits.has("ranged-trip")&&modifiers.push(new ModifierPF2e({slug:"ranged-trip",adjustments:extractModifierAdjustments(opts.actor.synthetics.modifierAdjustments,context.rollOptions,"ranged-trip"),type:"circumstance",label:CONFIG.PF2E.weaponTraits["ranged-trip"],modifier:-2})),context.modifiers=modifiers}return context}__name(tripCheckContext,"tripCheckContext"),__name2(tripCheckContext,"tripCheckContext");function trip(options){const slug=options?.skill??"athletics",modifiers=options?.modifiers,rollOptions=["action:trip"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Trip.Title",checkContext:opts=>tripCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(trip,"trip"),__name2(trip,"trip");class TripActionVariant extends SingleCheckActionVariant{static{__name(this,"TripActionVariant")}static{__name2(this,"TripActionVariant")}checkContext(opts,data){return tripCheckContext(opts,data)}}class TripAction extends SingleCheckAction{static{__name(this,"TripAction")}static{__name2(this,"TripAction")}constructor(){super({cost:1,description:"PF2E.Actions.Trip.Description",difficultyClass:"reflex",name:"PF2E.Actions.Trip.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Trip.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Trip.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Trip.Notes.criticalFailure"}],rollOptions:["action:trip"],slug:"trip",statistic:"athletics",traits:["attack"]})}toActionVariant(data){return new TripActionVariant(this,data)}}const action$o=new TripAction;function determineSizeBonus(actorSize,targetSize){const sizeDifference=actorSize.difference(targetSize);return Math.clamped(2*sizeDifference,-4,4)}__name(determineSizeBonus,"determineSizeBonus"),__name2(determineSizeBonus,"determineSizeBonus");function whirlingThrow(options){const slug=options?.skill??"athletics",rollOptions=["action:whirling-throw"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.WhirlingThrow.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const actorSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeModifier=new ModifierPF2e("Size Modifier",determineSizeBonus(actorSize,targetSize),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["monk"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(whirlingThrow,"whirlingThrow"),__name2(whirlingThrow,"whirlingThrow");class AidActionVariant extends SingleCheckActionVariant{static{__name(this,"AidActionVariant")}static{__name2(this,"AidActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Aid.Warning.NoStatistic"));const rollOption=`action:aid:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class AidAction extends SingleCheckAction{static{__name(this,"AidAction")}static{__name2(this,"AidAction")}constructor(){super({cost:"reaction",description:"PF2E.Actions.Aid.Description",difficultyClass:{value:15},name:"PF2E.Actions.Aid.Title",notes:[{outcome:["criticalFailure"],text:"PF2E.Actions.Aid.Notes.criticalFailure",title:"PF2E.Check.Result.Degree.Check.criticalFailure"},{outcome:["criticalSuccess"],text:"PF2E.Actions.Aid.Notes.criticalSuccess",title:"PF2E.Check.Result.Degree.Check.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Aid.Notes.success",title:"PF2E.Check.Result.Degree.Check.success"}],rollOptions:["action:aid"],slug:"aid",statistic:""})}toActionVariant(data){return new AidActionVariant(this,data)}}const aid=new AidAction,crawl=new SimpleAction({cost:1,description:"PF2E.Actions.Crawl.Description",name:"PF2E.Actions.Crawl.Title",slug:"crawl",traits:["move"]}),delay=new SimpleAction({cost:"free",description:"PF2E.Actions.Delay.Description",name:"PF2E.Actions.Delay.Title",slug:"delay"});class DropProneActionVariant extends SimpleActionVariant{static{__name(this,"DropProneActionVariant")}static{__name2(this,"DropProneActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")||await result.actor.toggleCondition("prone");return results})}}class DropProneAction extends SimpleAction{static{__name(this,"DropProneAction")}static{__name2(this,"DropProneAction")}constructor(){super({cost:1,description:"PF2E.Actions.DropProne.Description",name:"PF2E.Actions.DropProne.Title",slug:"drop-prone",traits:["move"]})}toActionVariant(data){return new DropProneActionVariant(this,data)}}const dropProne=new DropProneAction,toHighestModifier=__name2((highest,current)=>current.totalModifier>(highest?.totalModifier??0)?current:highest,"toHighestModifier");function unarmedStrikeWithHighestModifier(opts,data){const actionRollOptions=["action:escape","action:escape:unarmed"],{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),{actor}=opts,statistic=(()=>actor instanceof CharacterPF2e?actor.system.actions.filter(strike=>strike.weaponTraits.map(trait=>trait.name).includes("unarmed")):actor instanceof NPCPF2e?actor.system.actions.filter(strike=>strike.item.category==="unarmed"):[])().map(strike=>{const modifiers=(strike.modifiers??[]).concat(data.modifiers??[]);return new StatisticModifier("unarmed",modifiers,rollOptions)}).reduce(toHighestModifier,null);return statistic?{actor,rollOptions,statistic}:null}__name(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier"),__name2(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier");function escapeCheckContext(opts,data){const unarmed=data.slug&&data.slug!=="unarmed"?null:unarmedStrikeWithHighestModifier(opts,data),highest=(data.slug?[data.slug]:["acrobatics","athletics"]).filter(slug=>slug!=="unarmed").map(slug=>{const actionRollOptions=["action:escape",`action:escape:${slug}`],{property}=ActionMacroHelpers.resolveStat(slug),{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),statistic=foundry.utils.getProperty(opts.actor,property);return{actor:opts.actor,rollOptions,statistic:new StatisticModifier(statistic.slug,statistic.modifiers.concat(data.modifiers??[]),rollOptions)}}).reduce((highest2,current)=>!highest2||current.statistic.totalModifier>(highest2?.statistic.totalModifier??0)?current:highest2,unarmed);if(highest){const{checkType,stat:slug,subtitle}=ActionMacroHelpers.resolveStat(highest.statistic.slug);return{modifiers:data.modifiers,rollOptions:highest.rollOptions,slug,statistic:highest.statistic,subtitle,type:checkType}}throw new CheckContextError("No applicable statistic to roll for Escape check.",opts.actor,"null")}__name(escapeCheckContext,"escapeCheckContext"),__name2(escapeCheckContext,"escapeCheckContext");function escape(options){const slug=options?.skill??"",modifiers=options?.modifiers,rollOptions=["action:escape"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,checkContext:opts=>escapeCheckContext(opts,{modifiers,rollOptions,slug}),actionGlyph:options.glyph??"A",title:"PF2E.Actions.Escape.Title",traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"athletics",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(escape,"escape"),__name2(escape,"escape");class EscapeActionVariant extends SingleCheckActionVariant{static{__name(this,"EscapeActionVariant")}static{__name2(this,"EscapeActionVariant")}get statistic(){return""}checkContext(opts,data){return escapeCheckContext(opts,data)}}class EscapeAction extends SingleCheckAction{static{__name(this,"EscapeAction")}static{__name2(this,"EscapeAction")}constructor(){super({cost:1,description:"PF2E.Actions.Escape.Description",difficultyClass:"athletics",name:"PF2E.Actions.Escape.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Escape.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Escape.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Escape.Notes.criticalFailure"}],rollOptions:["action:escape"],slug:"escape",statistic:"unarmed",traits:["attack"]})}toActionVariant(data){return new EscapeActionVariant(this,data)}}const action$n=new EscapeAction,interact=new SimpleAction({cost:1,description:"PF2E.Actions.Interact.Description",name:"PF2E.Actions.Interact.Title",slug:"interact",traits:["manipulate"]}),leap=new SimpleAction({cost:1,description:"PF2E.Actions.Leap.Description",name:"PF2E.Actions.Leap.Title",slug:"leap",traits:["move"]}),ready=new SimpleAction({cost:2,description:"PF2E.Actions.Ready.Description",name:"PF2E.Actions.Ready.Title",slug:"ready",traits:["concentrate"]}),release=new SimpleAction({cost:"free",description:"PF2E.Actions.Release.Description",name:"PF2E.Actions.Release.Title",slug:"release",traits:["manipulate"]});function seek(options){const slug=options?.skill??"perception",rollOptions=["action:seek"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Seek.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(seek,"seek"),__name2(seek,"seek");const action$m=new SingleCheckAction({cost:1,description:"PF2E.Actions.Seek.Description",name:"PF2E.Actions.Seek.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Seek.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Seek.Notes.success"}],rollOptions:["action:seek"],slug:"seek",statistic:"perception",traits:["concentrate","secret"]});function senseMotive(options){const slug=options?.skill??"perception",rollOptions=["action:sense-motive"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.SenseMotive.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"deception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseMotive,"senseMotive"),__name2(senseMotive,"senseMotive");const action$l=new SingleCheckAction({cost:1,description:"PF2E.Actions.SenseMotive.Description",difficultyClass:"deception",name:"PF2E.Actions.SenseMotive.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseMotive.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseMotive.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.SenseMotive.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.SenseMotive.Notes.criticalFailure"}],rollOptions:["action:sense-motive"],slug:"sense-motive",statistic:"perception",traits:["concentrate","secret"]});class StandActionVariant extends SimpleActionVariant{static{__name(this,"StandActionVariant")}static{__name2(this,"StandActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")&&await result.actor.toggleCondition("prone");return results})}}class StandAction extends SimpleAction{static{__name(this,"StandAction")}static{__name2(this,"StandAction")}constructor(){super({cost:1,description:"PF2E.Actions.Stand.Description",name:"PF2E.Actions.Stand.Title",slug:"stand",traits:["move"]})}toActionVariant(data){return new StandActionVariant(this,data)}}const stand=new StandAction,step=new SimpleAction({cost:1,description:"PF2E.Actions.Step.Description",name:"PF2E.Actions.Step.Title",slug:"step",traits:["move"]}),stride=new SimpleAction({cost:1,description:"PF2E.Actions.Stride.Description",name:"PF2E.Actions.Stride.Title",slug:"stride",traits:["move"]}),takeCover=new SimpleAction({cost:1,description:"PF2E.Actions.TakeCover.Description",effect:"Compendium.pf2e.other-effects.I9lfZUiCwMiGogVi",img:"systems/pf2e/icons/conditions-2/status_acup.webp",name:"PF2E.Actions.TakeCover.Title",slug:"take-cover"});function tamper(options){const slug=options?.skill??"crafting",rollOptions=["action:tamper"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Tamper.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["inventor","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tamper,"tamper"),__name2(tamper,"tamper");const PREFIX$b="PF2E.Actions.CreateADiversion",CREATE_A_DIVERSION_VARIANTS=["distracting-words","gesture","trick"];function createADiversion(options){const{title,traits,variant}=(()=>{switch(options?.variant){case"distracting-words":return{title:`${PREFIX$b}.DistractingWords.Title`,traits:["auditory","linguistic","mental"],variant:options.variant};case"gesture":return{title:`${PREFIX$b}.Gesture.Title`,traits:["manipulate","mental"],variant:options.variant};case"trick":return{title:`${PREFIX$b}.Trick.Title`,traits:["manipulate","mental"],variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=CREATE_A_DIVERSION_VARIANTS.map(v=>`'${v}'`).join(", ");throw ui.notifications.error(game.i18n.format(`${PREFIX$b}.Warning.UnknownVariant`,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Create a Diversion, use one of ${variants}.`)}}})(),slug=options?.skill??"deception",rollOptions=["action:create-a-diversion",`action:create-a-diversion:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits,event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$b}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$b}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createADiversion,"createADiversion"),__name2(createADiversion,"createADiversion");function feint(options){const slug=options?.skill??"deception",rollOptions=["action:feint"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Feint.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(feint,"feint"),__name2(feint,"feint");const PREFIX$a="PF2E.Actions.Impersonate";function impersonate(options){const slug=options?.skill??"deception",rollOptions=["action:impersonate"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$a}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$a}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$a,"failure"),ActionMacroHelpers.note(selector,PREFIX$a,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(impersonate,"impersonate"),__name2(impersonate,"impersonate");const PREFIX$9="PF2E.Actions.Lie";function lie(options){const slug=options?.skill??"deception",rollOptions=["action:lie"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$9}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$9}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$9}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(lie,"lie"),__name2(lie,"lie");const action$k=new SingleCheckAction({description:`${PREFIX$9}.Description`,difficultyClass:"perception",name:`${PREFIX$9}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$9}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$9}.Notes.failure`}],rollOptions:["action:lie"],slug:"lie",statistic:"deception",traits:["auditory","concentrate","linguistic","mental","secret"]});function bonMot(options){const slug=options?.skill??"diplomacy",rollOptions=["action:bon-mot"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.BonMot.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(bonMot,"bonMot"),__name2(bonMot,"bonMot");const PREFIX$8="PF2E.Actions.GatherInformation";function gatherInformation(options){const slug=options?.skill??"diplomacy",rollOptions=["action:gather-information"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$8}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$8}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$8,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(gatherInformation,"gatherInformation"),__name2(gatherInformation,"gatherInformation");function makeAnImpression(options){const slug=options?.skill??"diplomacy",rollOptions=["action:make-an-impression"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.MakeAnImpression.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(makeAnImpression,"makeAnImpression"),__name2(makeAnImpression,"makeAnImpression");const PREFIX$7="PF2E.Actions.Request";function request(options){const slug=options?.skill??"diplomacy",rollOptions=["action:request"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$7}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(request,"request"),__name2(request,"request");const action$j=new SingleCheckAction({cost:1,description:`${PREFIX$7}.Description`,name:`${PREFIX$7}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$7}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$7}.Notes.success`},{outcome:["failure"],text:`${PREFIX$7}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$7}.Notes.criticalFailure`}],rollOptions:["action:request"],slug:"request",statistic:"diplomacy",traits:["auditory","concentrate","linguistic","mental"]});function avoidNotice(options){const slug=options?.skill??"stealth",rollOptions=["action:avoid-notice"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.AvoidNotice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(avoidNotice,"avoidNotice"),__name2(avoidNotice,"avoidNotice");const action$i=new SingleCheckAction({description:"PF2E.Actions.AvoidNotice.Description",name:"PF2E.Actions.AvoidNotice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.AvoidNotice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.AvoidNotice.Notes.success"}],rollOptions:["action:avoid-notice"],slug:"avoid-notice",statistic:"stealth",traits:["exploration"]});function senseDirection(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"})].concat(options?.modifiers??[]),slug=options?.skill??"survival",rollOptions=["action:sense-direction"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.SenseDirection.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseDirection,"senseDirection"),__name2(senseDirection,"senseDirection");const action$h=new SingleCheckAction({description:"PF2E.Actions.SenseDirection.Description",modifiers:[{label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"}],name:"PF2E.Actions.SenseDirection.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseDirection.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseDirection.Notes.success"}],rollOptions:["action:sense-direction"],slug:"sense-direction",statistic:"survival",traits:["exploration","secret"]});function track(options){const slug=options?.skill??"survival",rollOptions=["action:track"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Track.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Track","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(track,"track"),__name2(track,"track");const action$g=new SingleCheckAction({description:"PF2E.Actions.Track.Description",name:"PF2E.Actions.Track.Title",notes:[{outcome:["success","criticalSuccess"],text:"PF2E.Actions.Track.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Track.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Track.Notes.criticalFailure"}],rollOptions:["action:track"],slug:"track",statistic:"survival",traits:["concentrate","exploration","move"]});function decipherWriting(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));return}const{skill:slug}=options,rollOptions=["action:decipher-writing",`action:decipher-writing:${slug}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.DecipherWriting.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(decipherWriting,"decipherWriting"),__name2(decipherWriting,"decipherWriting");class DecipherWritingActionVariant extends SingleCheckActionVariant{static{__name(this,"DecipherWritingActionVariant")}static{__name2(this,"DecipherWritingActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));const rollOption=`action:decipher-writing:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class DecipherWritingAction extends SingleCheckAction{static{__name(this,"DecipherWritingAction")}static{__name2(this,"DecipherWritingAction")}constructor(){super({description:"PF2E.Actions.DecipherWriting.Description",name:"PF2E.Actions.DecipherWriting.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DecipherWriting.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DecipherWriting.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.DecipherWriting.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.DecipherWriting.Notes.criticalFailure"}],rollOptions:["action:decipher-writing"],slug:"decipher-writing",statistic:"",traits:["concentrate","exploration","secret"]})}toActionVariant(data){return new DecipherWritingActionVariant(this,data)}}const action$f=new DecipherWritingAction;function subsist(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));return}const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]})].concat(options?.modifiers??[]),{skill:slug}=options,rollOptions=["action:subsist",`action:subsist:${slug}`];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Subsist.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(subsist,"subsist"),__name2(subsist,"subsist");class SubsistActionVariant extends SingleCheckActionVariant{static{__name(this,"SubsistActionVariant")}static{__name2(this,"SubsistActionVariant")}async use(options={}){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));const rollOption=`action:subsist:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class SubsistAction extends SingleCheckAction{static{__name(this,"SubsistAction")}static{__name2(this,"SubsistAction")}constructor(){super({description:"PF2E.Actions.Subsist.Description",modifiers:[{label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]}],name:"PF2E.Actions.Subsist.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Subsist.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Subsist.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Subsist.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Subsist.Notes.criticalFailure"}],rollOptions:["action:subsist"],slug:"subsist",statistic:"",traits:["downtime"]})}toActionVariant(data){return new SubsistActionVariant(this,data)}}const action$e=new SubsistAction;function coerce(options){const slug=options?.skill??"intimidation",rollOptions=["action:coerce"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Coerce.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(coerce,"coerce"),__name2(coerce,"coerce");const action$d=new SingleCheckAction({description:"PF2E.Actions.Coerce.Description",difficultyClass:"will",name:"PF2E.Actions.Coerce.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Coerce.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Coerce.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Coerce.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Coerce.Notes.criticalFailure"}],rollOptions:["action:coerce"],slug:"coerce",statistic:"intimidation",traits:["auditory","concentrate","emotion","exploration","linguistic","mental"]});function demoralize(options){const slug=options?.skill??"intimidation",rollOptions=["action:demoralize"],modifiers=[new ModifierPF2e({label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"})].concat(options?.modifiers??[]);ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Demoralize.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","fear","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(demoralize,"demoralize"),__name2(demoralize,"demoralize");const action$c=new SingleCheckAction({description:"PF2E.Actions.Demoralize.Description",difficultyClass:"will",modifiers:[{label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"}],name:"PF2E.Actions.Demoralize.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Demoralize.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Demoralize.Notes.success"}],rollOptions:["action:demoralize"],slug:"demoralize",statistic:"intimidation",traits:["auditory","concentrate","emotion","fear","mental"]}),PREFIX$6="PF2E.Actions.AdministerFirstAid",ADMINISTER_FIRST_AID_VARIANTS=["stabilize","stop-bleeding"];function stabilizeDifficultyClass(target){if(!target?.isOfType("creature"))return null;const{dying}=target.attributes;if(!dying?.value)throw new Error(game.i18n.localize(`${PREFIX$6}.Warning.TargetNotDying`));const dcModifier=new ModifierPF2e({slug:"dying-recovery",label:"PF2E.ModifierTitle",modifier:5+dying.recoveryDC+dying.value-10});return new Statistic(target,{slug:"administer-first-aid",label:`${PREFIX$6}.Stabilize.Title`,dc:{label:`${PREFIX$6}.Stabilize.DifficultyClass.Label`,modifiers:[dcModifier]}}).dc}__name(stabilizeDifficultyClass,"stabilizeDifficultyClass"),__name2(stabilizeDifficultyClass,"stabilizeDifficultyClass");function administerFirstAid(options){const{notes,title,variant}=(()=>{const mainTitle=game.i18n.localize(`${PREFIX$6}.Title`);switch(options?.variant){case"stabilize":return{notes:{criticalFailure:`${PREFIX$6}.Stabilize.Notes.criticalFailure`,success:`${PREFIX$6}.Stabilize.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.Stabilize.Title`),variant:options.variant};case"stop-bleeding":return{notes:{criticalFailure:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`,success:`${PREFIX$6}.StopBleeding.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.StopBleeding.Title`),variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=ADMINISTER_FIRST_AID_VARIANTS.map(v=>`'${v}'`).join(", "),error=`${PREFIX$6}.Warning.UnknownVariant`;throw ui.notifications.error(game.i18n.format(error,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Administer First Aid, use one of ${variants}.`)}}})(),slug=options?.skill??"medicine",rollOptions=["action:administer-first-aid",`action:administer-first-aid:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??(target=>{if(variant==="stabilize"&&target)try{return stabilizeDifficultyClass(target)}catch(error){if(error instanceof Error)ui.notifications.warn(error.message);else throw error}return null}),extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,notes.success,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,notes.criticalFailure,["criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(administerFirstAid,"administerFirstAid"),__name2(administerFirstAid,"administerFirstAid");class AdministerFirstAidAction extends SingleCheckAction{static{__name(this,"AdministerFirstAidAction")}static{__name2(this,"AdministerFirstAidAction")}constructor(){super({cost:2,description:`${PREFIX$6}.Description`,name:`${PREFIX$6}.Title`,slug:"administer-first-aid",statistic:"medicine",traits:["manipulate"],variants:[{description:`${PREFIX$6}.Stabilize.Description`,name:`${PREFIX$6}.Stabilize.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.Stabilize.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.Stabilize.Notes.criticalFailure`}],slug:"stabilize"},{description:`${PREFIX$6}.StopBleeding.Description`,name:`${PREFIX$6}.StopBleeding.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.StopBleeding.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`}],slug:"stop-bleeding"}]})}}const action$b=new AdministerFirstAidAction;function treatDisease(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-disease"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.TreatDisease.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatDisease,"treatDisease"),__name2(treatDisease,"treatDisease");const action$a=new SingleCheckAction({description:"PF2E.Actions.TreatDisease.Description",name:"PF2E.Actions.TreatDisease.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatDisease.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatDisease.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatDisease.Notes.criticalFailure"}],rollOptions:["action:treat-disease"],slug:"treat-disease",statistic:"medicine",traits:["downtime","manipulate"]});function treatPoison(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-poison"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.TreatPoison.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatPoison,"treatPoison"),__name2(treatPoison,"treatPoison");const action$9=new SingleCheckAction({cost:1,description:"PF2E.Actions.TreatPoison.Description",name:"PF2E.Actions.TreatPoison.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatPoison.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatPoison.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatPoison.Notes.criticalFailure"}],rollOptions:["action:treat-poison"],slug:"treat-poison",statistic:"medicine",traits:["manipulate"]}),PREFIX$5="PF2E.Actions.CommandAnAnimal";function commandAnAnimal(options){const slug=options?.skill??"nature",rollOptions=["action:command-an-animal"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$5}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$5}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$5,"failure"),ActionMacroHelpers.note(selector,PREFIX$5,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(commandAnAnimal,"commandAnAnimal"),__name2(commandAnAnimal,"commandAnAnimal");const action$8=new SingleCheckAction({cost:1,description:`${PREFIX$5}.Description`,difficultyClass:"will",name:`${PREFIX$5}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$5}.Notes.success`},{outcome:["failure"],text:`${PREFIX$5}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$5}.Notes.criticalFailure`}],rollOptions:["action:command-an-animal"],slug:"command-an-animal",statistic:"nature",traits:["auditory","concentrate"]}),PERFORM_VARIANT_TRAITS={acting:["auditory","linguistic","visual"],comedy:["auditory","linguistic","visual"],dance:["move","visual"],keyboards:["auditory","manipulate"],oratory:["auditory","linguistic"],percussion:["auditory","manipulate"],singing:["auditory","linguistic"],strings:["auditory","manipulate"],winds:["auditory","manipulate"]};function perform(options){const traits=PERFORM_VARIANT_TRAITS[options?.variant??""];if(!traits){const msg=game.i18n.format("PF2E.Actions.Perform.Warning.UnknownVariant",{variant:options.variant});ui.notifications.warn(msg);return}const slug=options?.skill??"performance",rollOptions=["action:perform",`action:perform:${options.variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"1",title:`PF2E.Actions.Perform.${options.variant.charAt(0).toUpperCase()}${options.variant.slice(1)}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate",...traits].sort(),event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(perform,"perform"),__name2(perform,"perform");async function createForgeryCallback(result,callback){const societyDC=(()=>{if(result.actor instanceof CreaturePF2e){const systemFlags=result.message?.flags.pf2e,modifiers=systemFlags.modifiers.filter(modifier=>modifier.enabled).map(modifier=>({...modifier,predicate:[]})).map(modifier=>new ModifierPF2e(modifier));return result.actor.skills.society.extend({slug:result.actor.skills.society.slug,modifiers}).withRollOptions({extraRollOptions:systemFlags.context.options,origin:result.actor}).dc}return null})(),gmNotes=(()=>["criticalSuccess","success"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.SuccessGmNote",{societyDC:societyDC?.value??null}):["criticalFailure","failure"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.FailureGmNote",{failure:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.failure"),success:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.success"),total:result.roll.total}):"")();await Item.create({img:"systems/pf2e/icons/equipment/adventuring-gear/scroll-case.webp",name:game.i18n.localize("PF2E.Actions.CreateForgery.ForgedDocument.Name"),type:"equipment",system:{description:{gm:gmNotes,value:game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.Description",{societyDC:societyDC?.value??null})}}},{parent:result.actor});const notification=game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocumentCreatedNotification",{name:result.actor.name});ui.notifications.info(notification),callback?.(result)}__name(createForgeryCallback,"createForgeryCallback"),__name2(createForgeryCallback,"createForgeryCallback");function createForgery(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"})].concat(options?.modifiers??[]),slug=options?.skill??"society",rollOptions=["action:create-forgery"];return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.CreateForgery.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","secret"],event:options.event,callback:async result=>createForgeryCallback(result,options?.callback),difficultyClass:options.difficultyClass??{value:20},extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createForgery,"createForgery"),__name2(createForgery,"createForgery");class CreateForgeryActionVariant extends SingleCheckActionVariant{static{__name(this,"CreateForgeryActionVariant")}static{__name2(this,"CreateForgeryActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)await createForgeryCallback(result);return results})}}class CreateForgeryAction extends SingleCheckAction{static{__name(this,"CreateForgeryAction")}static{__name2(this,"CreateForgeryAction")}constructor(){super({description:"PF2E.Actions.CreateForgery.Description",difficultyClass:{value:20},modifiers:[{label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"}],name:"PF2E.Actions.CreateForgery.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.CreateForgery.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.CreateForgery.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.CreateForgery.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.CreateForgery.Notes.criticalFailure"}],rollOptions:["action:create-forgery"],slug:"create-forgery",statistic:"society",traits:["downtime","secret"]})}toActionVariant(data){return new CreateForgeryActionVariant(this,data)}}const action$7=new CreateForgeryAction,PREFIX$4="PF2E.Actions.ConcealAnObject";function concealAnObject(options){const slug=options?.skill??"stealth",rollOptions=["action:conceal-an-object"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$4}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(concealAnObject,"concealAnObject"),__name2(concealAnObject,"concealAnObject");const action$6=new SingleCheckAction({cost:1,description:`${PREFIX$4}.Description`,difficultyClass:"perception",name:`${PREFIX$4}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$4}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$4}.Notes.failure`}],rollOptions:["action:conceal-an-object"],slug:"conceal-an-object",statistic:"stealth",traits:["manipulate","secret"]}),PREFIX$3="PF2E.Actions.Hide";function hide(options){const slug=options?.skill??"stealth",rollOptions=["action:hide"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$3}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$3}.Notes.success`,["success","criticalSuccess"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(hide,"hide"),__name2(hide,"hide");const action$5=new SingleCheckAction({cost:1,description:`${PREFIX$3}.Description`,difficultyClass:"perception",name:`${PREFIX$3}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$3}.Notes.success`}],rollOptions:["action:hide"],slug:"hide",statistic:"stealth",traits:["secret"]}),PREFIX$2="PF2E.Actions.Sneak";function sneak(options){const slug=options?.skill??"stealth",rollOptions=["action:sneak"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$2}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$2}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$2,"failure"),ActionMacroHelpers.note(selector,PREFIX$2,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(sneak,"sneak"),__name2(sneak,"sneak");const action$4=new SingleCheckAction({cost:1,description:`${PREFIX$2}.Description`,difficultyClass:"perception",name:`${PREFIX$2}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$2}.Notes.success`},{outcome:["failure"],text:`${PREFIX$2}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$2}.Notes.criticalFailure`}],rollOptions:["action:sneak"],slug:"sneak",statistic:"stealth",traits:["move","secret"]}),PREFIX$1="PF2E.Actions.PalmAnObject";function palmAnObject(options){const slug=options?.skill??"thievery",rollOptions=["action:palm-an-object"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$1}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(palmAnObject,"palmAnObject"),__name2(palmAnObject,"palmAnObject");const action$3=new SingleCheckAction({cost:1,description:`${PREFIX$1}.Description`,difficultyClass:"perception",name:`${PREFIX$1}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$1}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$1}.Notes.failure`}],rollOptions:["action:palm-an-object"],slug:"palm-an-object",statistic:"thievery",traits:["manipulate"]});function disableDevice(options){const slug=options?.skill??"thievery",rollOptions=["action:disable-a-device","action:disable-device"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options?.actors,actionGlyph:options?.glyph??"D",title:"PF2E.Actions.DisableDevice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options?.event,callback:options?.callback,difficultyClass:options?.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disableDevice,"disableDevice"),__name2(disableDevice,"disableDevice");const action$2=new SingleCheckAction({cost:2,description:"PF2E.Actions.DisableDevice.Description",name:"PF2E.Actions.DisableDevice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DisableDevice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DisableDevice.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.DisableDevice.Notes.criticalFailure"}],rollOptions:["action:disable-a-device","action:disable-device"],slug:"disable-device",statistic:"thievery",traits:["manipulate"]});function pickALock(options){const slug=options?.skill??"thievery",rollOptions=["action:pick-a-lock"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.PickALock.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(pickALock,"pickALock"),__name2(pickALock,"pickALock");const action$1=new SingleCheckAction({cost:2,description:"PF2E.Actions.PickALock.Description",name:"PF2E.Actions.PickALock.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.PickALock.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.PickALock.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.PickALock.Notes.criticalFailure"}],rollOptions:["action:pick-a-lock"],slug:"pick-a-lock",statistic:"thievery",traits:["manipulate"]}),PREFIX="PF2E.Actions.Steal";function steal(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]})].concat(options?.modifiers??[]),slug=options?.skill??"thievery",rollOptions=["action:steal"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(steal,"steal"),__name2(steal,"steal");const action=new SingleCheckAction({cost:1,description:`${PREFIX}.Description`,difficultyClass:"perception",modifiers:[{label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]}],name:`${PREFIX}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX}.Notes.failure`}],rollOptions:["action:steal"],slug:"steal",statistic:"thievery",traits:["manipulate"]}),ActionMacros={escape,seek,senseMotive,arcaneSlam,tamper,avoidNotice,senseDirection,track,balance,maneuverInFlight,squeeze,tumbleThrough,climb,disarm,forceOpen,grapple,highJump,longJump,reposition,shove,swim,trip,whirlingThrow,craft,repair,createADiversion,feint,impersonate,lie,bonMot,gatherInformation,makeAnImpression,request,decipherWriting,subsist,coerce,demoralize,administerFirstAid,treatDisease,treatPoison,commandAnAnimal,perform,createForgery,concealAnObject,hide,sneak,palmAnObject,disableDevice,pickALock,steal},SystemActions=[action$b,aid,action$i,action$y,action$u,action$d,action$8,action$6,crawl,action$7,action$f,delay,action$c,action$2,dropProne,action$n,action$t,action$5,action$s,interact,leap,action$k,action$r,action$x,action$3,action$1,ready,release,action$q,action$j,action$m,action$h,action$l,action$4,action$w,stand,action,step,stride,action$e,action$p,takeCover,action$g,action$a,action$9,action$o,action$v];class EffectTracker{static{__name(this,"EffectTracker")}static{__name2(this,"EffectTracker")}effects=[];auraEffects=new Collection;#insert(effect,duration){if(this.effects.length===0)this.effects.push(effect);else{for(let index=0;index<this.effects.length;index++){const other=this.effects[index],remaining=other.remainingDuration.remaining;if(!(duration.remaining>remaining)){if(remaining>duration.remaining){this.effects.splice(index,0,effect);return}else if(!((effect.system.start.initiative??0)>(other.system.start.initiative??0))){if((other.system.start.initiative??0)>(effect.system.start.initiative??0)){this.effects.splice(index,0,effect);return}else if(other.system.duration.expiry==="turn-start"&&effect.system.duration.expiry==="turn-end"){this.effects.splice(index,0,effect);return}}}}this.effects.push(effect)}}register(effect){effect.fromAura&&(canvas.ready||!effect.actor.isToken)&&effect.id&&this.auraEffects.set(effect.uuid,effect);const index=this.effects.findIndex(e=>e.id===effect.id),systemData=effect.system,duration=systemData.duration.unit;switch(duration){case"unlimited":case"encounter":{duration==="unlimited"&&(systemData.expired=!1),index>=0&&index<this.effects.length&&this.effects.splice(index,1);return}default:{const duration2=effect.remainingDuration;if(effect.system.expired=duration2.expired,this.effects.length===0||index<0)this.#insert(effect,duration2);else{const existing=this.effects[index];duration2.remaining!==existing.remainingDuration.remaining&&(this.effects.splice(index,1),this.#insert(effect,duration2))}}}}unregister(toRemove){this.effects=this.effects.filter(e=>e!==toRemove),this.auraEffects.delete(toRemove.uuid)}async refresh(options={}){if(options.resetItemData){const actors=new Set(this.effects.flatMap(e=>e.actor??[]));for(const actor of actors)actor.reset();game.pf2e.effectPanel.refresh()}const actorsToUpdate=new Set(this.effects.filter(e=>e.isExpired).map(e=>e.actor));if(game.settings.get("pf2e","automation.removeExpiredEffects"))for(const actor of actorsToUpdate)await this.#removeExpired(actor);else game.settings.get("pf2e","automation.effectExpiration")&&resetActors(actorsToUpdate)}async#removeExpired(actor){actor.primaryUpdater===game.user&&await actor.deleteEmbeddedDocuments("Item",actor.itemTypes.effect.filter(e=>e.isExpired).map(e=>e.id))}async onEncounterEnd(encounter){const autoRemoveExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),autoExpireEffects=!autoRemoveExpired&&game.settings.get("pf2e","automation.effectExpiration");if(!(autoExpireEffects||autoRemoveExpired))return;const actors=encounter.combatants.contents.flatMap(c=>c.actor??[]).filter(a=>game.user===a.primaryUpdater);for(const actor of actors){const expiresNow=actor.itemTypes.effect.filter(e=>e.system.duration.unit==="encounter");if(expiresNow.length!==0){if(autoExpireEffects){const updates=expiresNow.map(e=>({_id:e.id,"system.expired":!0}));await actor.updateEmbeddedDocuments("Item",updates)}else{const deletes=expiresNow.map(e=>e.id);await actor.deleteEmbeddedDocuments("Item",deletes)}for(const effect of expiresNow)this.unregister(effect)}}}}class ModuleArt{static{__name(this,"ModuleArt")}static{__name2(this,"ModuleArt")}map=new Map;async refresh(){this.map.clear();const activeModules=[...game.modules.entries()].filter(([_key,m])=>m.active);for(const[moduleKey,foundryModule]of activeModules){const moduleArt=await this.#getArtMap(foundryModule.flags?.[moduleKey]?.["pf2e-art"]);if(moduleArt)for(const[packName,art]of Object.entries(moduleArt)){const pack=game.packs.get(`pf2e.${packName}`);if(!pack){console.warn(`PF2e System | Failed pack lookup from module art registration (${moduleKey}): ${packName}`);continue}const index=pack.indexed?pack.index:await pack.getIndex();for(const[actorId,paths]of Object.entries(art)){const record=index.get(actorId);if(!record)continue;record.img=paths.actor;const actorArtPartial={img:paths.actor,prototypeToken:{texture:{src:typeof paths.token=="string"?paths.token:paths.token.img}}};typeof paths.token!="string"&&(typeof paths.token.scale=="number"&&(actorArtPartial.prototypeToken.texture.scaleX=paths.token.scale,actorArtPartial.prototypeToken.texture.scaleY=paths.token.scale,actorArtPartial.prototypeToken.flags={pf2e:{autoscale:!1}}),typeof paths.token.randomImg=="boolean"&&(actorArtPartial.prototypeToken.randomImg=paths.token.randomImg)),this.map.set(`Compendium.pf2e.${packName}.${actorId}`,actorArtPartial)}}}const apps=Object.values(ui.windows).filter(w=>w instanceof Compendium);for(const compendium of apps)compendium.render()}async#getArtMap(art){if(art){if(this.#isModuleArt(art))return art;if(typeof art=="string")try{const response=await fetch(art);if(!response.ok)return console.warn(`PF2e System | Failed loading art mapping file at ${art}`),null;const map2=await response.json();return this.#isModuleArt(map2)?map2:null}catch(error){error instanceof Error&&console.warn(`PF2e System | ${error.message}`)}}else return null;return null}#isModuleArt(record){return isObject(record)&&Object.values(record).every(packToArt=>isObject(packToArt)&&Object.values(packToArt).every(art=>isObject(art)&&"actor"in art&&typeof isImageFilePath(art.actor)&&"token"in art&&(isImageOrVideoPath(art.token)||isObject(art.token)&&"img"in art.token&&isImageOrVideoPath(art.token.img)&&(!("scale"in art.token)||typeof art.token.scale=="number"&&art.token.scale>0)&&(!("randomImg"in art.token)||typeof art.token.randomImg=="boolean"))))}}const SetGamePF2e={onInit:()=>{const actions=new Map(SystemActions.map(action2=>[action2.slug,action2]));for(const[name2,action2]of Object.entries({encouragingWords,raiseAShield,restForTheNight,earnIncome:showEarnIncomePopup,steelYourResolve,takeABreather,treatWounds,...ActionMacros}))actions[name2]=action2;const initSafe={Check:CheckPF2e,CheckModifier,Coins:CoinsPF2e,ConditionManager,Dice:DicePF2e,Modifier:ModifierPF2e,ModifierType:{ABILITY:"ability",PROFICIENCY:"proficiency",CIRCUMSTANCE:"circumstance",ITEM:"item",POTENCY:"potency",STATUS:"status",UNTYPED:"untyped"},RuleElement:RuleElementPF2e,RuleElements,StatisticModifier,StatusEffects,TextEditor:TextEditorPF2e,ElementalBlast,actions,effectPanel:new EffectsPanel,effectTracker:new EffectTracker,gm:{calculateXP,checkPrompt,editPersistent,launchTravelSheet,perceptionForSelected,stealthForSelected,xpFromEncounter},licenseViewer:new LicenseViewer,rollActionMacro,rollItemMacro,system:{generateItemName,moduleArt:new ModuleArt,remigrate,sluggify},variantRules:{AutomaticBonusProgression}};game.pf2e=foundry.utils.mergeObject(game.pf2e??{},initSafe),game.pf2e.ConditionManager.initialize(),game.pf2e.settings={campaign:{enabled:game.settings.get("pf2e","campaignFeats"),sections:game.settings.get("pf2e","campaignFeatSections")},encumbrance:game.settings.get("pf2e","automation.encumbrance"),iwr:game.settings.get("pf2e","automation.iwr"),rbv:game.settings.get("pf2e","automation.rulesBasedVision"),tokens:{autoscale:game.settings.get("pf2e","tokens.autoscale"),nameVisibility:game.settings.get("pf2e","metagame_tokenSetsNameVisibility"),nathMode:game.settings.get("pf2e","nathMode")},totm:game.settings.get("pf2e","totmToggles"),variants:{abp:game.settings.get("pf2e","automaticBonusVariant"),fa:game.settings.get("pf2e","freeArchetypeVariant"),gab:game.settings.get("pf2e","gradualBoostsVariant"),pwol:{enabled:game.settings.get("pf2e","proficiencyVariant"),modifiers:[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")]},stamina:game.settings.get("pf2e","staminaVariant")}}},onSetup:()=>{},onReady:()=>{game.pf2e.compendiumBrowser=new CompendiumBrowser,game.pf2e.worldClock=new WorldClock}};class AutomationSettings extends SettingsMenuPF2e{static{__name(this,"AutomationSettings")}static{__name2(this,"AutomationSettings")}static namespace="automation";static SETTINGS=["rulesBasedVision","iwr","effectExpiration","removeExpiredEffects","flankingDetection","encumbrance","lootableNPCs"];static get settings(){return{rulesBasedVision:{name:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.name,hint:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.hint,default:!0,type:Boolean,requiresReload:!0,onChange:value=>{game.pf2e.settings.rbv=!!value}},iwr:{name:CONFIG.PF2E.SETTINGS.automation.iwr.name,hint:CONFIG.PF2E.SETTINGS.automation.iwr.hint,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.iwr=!!value}},effectExpiration:{name:CONFIG.PF2E.SETTINGS.automation.effectExpiration.name,hint:CONFIG.PF2E.SETTINGS.automation.effectExpiration.hint,default:!0,type:Boolean,onChange:()=>{for(const actor of game.actors){actor.reset(),actor.sheet.render(!1);for(const token of actor.getActiveTokens())token.drawEffects()}}},removeExpiredEffects:{name:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.name,hint:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.hint,default:!1,type:Boolean},flankingDetection:{name:CONFIG.PF2E.SETTINGS.automation.flankingDetection.name,hint:CONFIG.PF2E.SETTINGS.automation.flankingDetection.hint,default:!0,type:Boolean},encumbrance:{name:"PF2E.SETTINGS.Automation.Encumbrance.Name",hint:"PF2E.SETTINGS.Automation.Encumbrance.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.encumbrance=!!value}},lootableNPCs:{name:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.name,hint:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.hint,default:!0,type:Boolean}}}}const MetagameSettingsConfig={showDC:{name:"PF2E.SETTINGS.Metagame.ShowDC.Name",hint:"PF2E.SETTINGS.Metagame.ShowDC.Hint",default:!1,type:Boolean},showResults:{name:"PF2E.SETTINGS.Metagame.ShowResults.Name",hint:"PF2E.SETTINGS.Metagame.ShowResults.Hint",default:!0,type:Boolean},tokenSetsNameVisibility:{name:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Name",hint:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Hint",default:!1,type:Boolean,onChange:async value=>{game.pf2e.settings.tokens.nameVisibility=!!value,await ui.combat.render();const renderedMessages=document.querySelectorAll("#chat-log > li");for(const rendered of Array.from(renderedMessages)){const message=game.messages.get(rendered?.dataset.messageId??"");message&&await ui.chat.updateMessage(message)}}},secretDamage:{name:"PF2E.SETTINGS.Metagame.SecretDamage.Name",hint:"PF2E.SETTINGS.Metagame.SecretDamage.Hint",default:!1,type:Boolean},secretCondition:{name:"PF2E.SETTINGS.Metagame.SecretCondition.Name",hint:"PF2E.SETTINGS.Metagame.SecretCondition.Hint",default:!1,type:Boolean},showPartyStats:{name:"PF2E.SETTINGS.Metagame.ShowPartyStats.Name",hint:"PF2E.SETTINGS.Metagame.ShowPartyStats.Hint",default:!0,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.isOfType("party")))}},partyVision:{name:"PF2E.SETTINGS.Metagame.PartyVision.Name",hint:"PF2E.SETTINGS.Metagame.PartyVision.Hint",default:!1,type:Boolean,onChange:()=>{canvas.ready&&canvas.scene&&canvas.perception.update({initializeVision:!0,refreshLighting:!0},!0)}}};class MetagameSettings extends SettingsMenuPF2e{static{__name(this,"MetagameSettings")}static{__name2(this,"MetagameSettings")}static namespace="metagame";static get settings(){return MetagameSettingsConfig}static get SETTINGS(){return Object.keys(this.settings)}static get prefix(){return`${this.namespace}_`}}const SETTINGS={gradualBoostsVariant:{name:"PF2E.SETTINGS.Variant.GradualBoosts.Name",hint:"PF2E.SETTINGS.Variant.GradualBoosts.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.gab=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},staminaVariant:{name:"PF2E.SETTINGS.Variant.Stamina.Name",hint:"PF2E.SETTINGS.Variant.Stamina.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.stamina=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},freeArchetypeVariant:{name:"PF2E.SETTINGS.Variant.FreeArchetype.Name",hint:"PF2E.SETTINGS.Variant.FreeArchetype.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.fa=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},automaticBonusVariant:{name:"PF2E.SETTINGS.Variant.AutomaticBonus.Name",hint:"PF2E.SETTINGS.Variant.AutomaticBonus.Hint",default:"noABP",type:String,choices:{noABP:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.noABP",ABPFundamentalPotency:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPFundamentalPotency",ABPRulesAsWritten:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPRulesAsWritten"},onChange:value=>{const choices=["noABP","ABPFundamentalPotency","ABPRulesAsWritten"];game.pf2e.settings.variants.abp=tupleHasValue(choices,value)?value:game.pf2e.settings.variants.abp,resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyVariant:{name:"PF2E.SETTINGS.Variant.Proficiency.Name",hint:"PF2E.SETTINGS.Variant.Proficiency.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.pwol.enabled=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyUntrainedModifier:{name:"PF2E.SETTINGS.Variant.UntrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.UntrainedModifier.Hint",default:-2,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[0]=Number(value)||0}},proficiencyTrainedModifier:{name:"PF2E.SETTINGS.Variant.TrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.TrainedModifier.Hint",default:2,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[1]=Number(value)||0}},proficiencyExpertModifier:{name:"PF2E.SETTINGS.Variant.ExpertModifier.Name",hint:"PF2E.SETTINGS.Variant.ExpertModifier.Hint",default:4,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[2]=Number(value)||0}},proficiencyMasterModifier:{name:"PF2E.SETTINGS.Variant.MasterModifier.Name",hint:"PF2E.SETTINGS.Variant.MasterModifier.Hint",default:6,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[3]=Number(value)||0}},proficiencyLegendaryModifier:{name:"PF2E.SETTINGS.Variant.LegendaryModifier.Name",hint:"PF2E.SETTINGS.Variant.LegendaryModifier.Hint",default:8,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[4]=Number(value)||0}}};class VariantRulesSettings extends FormApplication{static{__name(this,"VariantRulesSettings")}static{__name2(this,"VariantRulesSettings")}static get defaultOptions(){return{...super.defaultOptions,title:"PF2E.SETTINGS.Variant.Title",id:"variant-rules-settings",template:"systems/pf2e/templates/system/settings/variant-rules.hbs",width:550,height:"auto",closeOnSubmit:!0}}async getData(){return Object.entries(SETTINGS).reduce((data,[key,setting])=>({...data,[key]:{value:game.settings.get("pf2e",key),setting}}),{})}static registerSettings(){for(const[key,value]of Object.entries(SETTINGS))value.config=!1,value.scope="world",game.settings.register("pf2e",key,value)}activateListeners($html){super.activateListeners($html),htmlQuery($html[0],"button[name=reset]")?.addEventListener("click",async event2=>{event2.preventDefault();for(const[key,value]of Object.entries(SETTINGS))await game.settings.set("pf2e",key,value?.default);return this.render()})}async _updateObject(_event,data){for(const key of Object.keys(SETTINGS))game.settings.set("pf2e",key,data[key])}}class WorldClockSettings extends FormApplication{static{__name(this,"WorldClockSettings")}static{__name2(this,"WorldClockSettings")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{title:CONFIG.PF2E.SETTINGS.worldClock.name,id:"world-clock-settings",template:"systems/pf2e/templates/system/settings/world-clock/index.hbs",width:550,height:"auto",closeOnSubmit:!0})}async getData(){const worldDefault=game.settings.get("pf2e","worldClock.syncDarkness")?game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled):game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled),sceneSetting=["syncDarknessScene",{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.hint,default:"default",type:String,choices:{enabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled,disabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled,default:game.i18n.format(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.default,{worldDefault})}}],settings=[...Object.entries(WorldClockSettings.settings).filter(([key])=>key!=="worldCreatedOn"),sceneSetting].map(([key,setting])=>{const value=(()=>{if(key==="syncDarknessScene")return canvas.scene?.flags.pf2e.syncDarkness;const rawValue=game.settings.get("pf2e",`worldClock.${key}`);return key==="worldCreatedOn"&&typeof rawValue=="string"?DateTime.fromISO(rawValue).toFormat("yyyy-MM-dd'T'HH:mm"):rawValue})();return{...setting,key,value,isSelect:"choices"in setting,isCheckbox:setting.type===Boolean,isDateTime:setting.type===String&&!("choices"in setting)}});return foundry.utils.mergeObject(await super.getData(),{settings})}static registerSettings(){game.settings.register("pf2e","worldClock.dateTheme",this.settings.dateTheme),game.settings.register("pf2e","worldClock.timeConvention",this.settings.timeConvention),game.settings.register("pf2e","worldClock.playersCanView",this.settings.playersCanView),game.settings.register("pf2e","worldClock.syncDarkness",this.settings.syncDarkness),game.settings.register("pf2e","worldClock.worldCreatedOn",this.settings.worldCreatedOn),game.settings.register("pf2e","worldClock.showClockButton",this.settings.showClockButton)}activateListeners($html){super.activateListeners($html);const localize=localizer("PF2E.SETTINGS.WorldClock"),title=localize("ResetWorldTime.Name");$html.find("button.reset-world-time").on("click",async()=>{const template=await renderTemplate("systems/pf2e/templates/system/settings/world-clock/confirm-reset.hbs");Dialog.confirm({title,content:template,yes:()=>{game.time.advance(-1*game.time.worldTime),this.close()},defaultYes:!1})}),$html.find('input[name="syncDarkness"]').on("change",event2=>{const worldDefault=$(event2.currentTarget)[0].checked?localize("SyncDarknessScene.Enabled"):localize("SyncDarknessScene.Disabled"),optionSelector='select[name="syncDarknessScene"] > option[value="default"]';$html.find(optionSelector).text(localize("SyncDarknessScene.Default",{worldDefault}))})}async _updateObject(_event,data){const keys2=["dateTheme","timeConvention","playersCanView","syncDarkness","showClockButton"];for(const key of keys2){const settingKey=`worldClock.${key}`,newValue=key==="worldCreatedOn"?DateTime.fromISO(data[key]).toUTC():data[key];await game.settings.set("pf2e",settingKey,newValue)}await canvas.scene?.setFlag("pf2e","syncDarkness",data.syncDarknessScene??"default"),delete data.syncDarknessScene,game.pf2e.worldClock.render(!1)}static get settings(){return{dateTheme:{name:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.name,hint:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.hint,scope:"world",config:!1,default:"AR",type:String,choices:{AR:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AR,AD:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AD,CE:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.CE}},timeConvention:{name:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.name,hint:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.hint,scope:"world",config:!1,default:24,type:Number,choices:{24:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twentyFour,12:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twelve}},showClockButton:{name:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.name,hint:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.hint,scope:"world",config:!1,default:!0,type:Boolean,onChange:()=>{game.settings.set("pf2e","worldClock.playersCanView",game.settings.get("pf2e","worldClock.showClockButton"))}},playersCanView:{name:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.name,hint:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.hint,scope:"world",config:!1,default:!1,type:Boolean},syncDarkness:{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.hint,scope:"world",config:!1,default:!1,type:Boolean},worldCreatedOn:{name:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.name,hint:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.hint,scope:"world",config:!1,default:DateTime.utc().toISO(),type:String}}}}function registerSettings(){game.settings.register("pf2e","tokens.autoscale",{name:"PF2E.SETTINGS.Tokens.Autoscale.Name",hint:"PF2E.SETTINGS.Tokens.Autoscale.Hint",scope:"world",config:!0,default:!0,type:Boolean,onChange:value=>{game.pf2e.settings.tokens.autoscale=!!value}}),game.settings.register("pf2e","identifyMagicNotMatchingTraditionModifier",{name:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Name",hint:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Hint",choices:{0:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.0",2:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.2",5:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.5",10:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.10"},type:Number,default:5,scope:"world",config:!0}),game.settings.register("pf2e","critRule",{name:"PF2E.SETTINGS.CritRule.Name",hint:"PF2E.SETTINGS.CritRule.Hint",scope:"world",config:!0,default:"doubledamage",type:String,choices:{doubledamage:"PF2E.SETTINGS.CritRule.Choices.Doubledamage",doubledice:"PF2E.SETTINGS.CritRule.Choices.Doubledice"},onChange:()=>{for(const sheet of Object.values(ui.windows).filter(w=>w instanceof ActorSheetPF2e))sheet.render()}}),game.settings.register("pf2e","compendiumBrowserPacks",{name:"PF2E.SETTINGS.CompendiumBrowserPacks.Name",hint:"PF2E.SETTINGS.CompendiumBrowserPacks.Hint",default:{},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","compendiumBrowserSources",{name:"PF2E.SETTINGS.compendiumBrowserSources.Name",hint:"PF2E.SETTINGS.compendiumBrowserSources.Hint",default:{ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.packLoader.reset(),game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","enabledRulesUI",{name:"PF2E.SETTINGS.EnabledRulesUI.Name",hint:"PF2E.SETTINGS.EnabledRulesUI.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:()=>{const itemSheets=Object.values(ui.windows).filter(w=>w instanceof ItemSheetPF2e);for(const sheet of itemSheets)sheet.render()}}),game.settings.register("pf2e","critFumbleButtons",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0}),game.settings.register("pf2e","drawCritFumble",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0});const iconChoices={blackWhite:"PF2E.SETTINGS.statusEffectType.blackWhite",default:"PF2E.SETTINGS.statusEffectType.default"};game.settings.register("pf2e","statusEffectType",{name:"PF2E.SETTINGS.statusEffectType.name",hint:"PF2E.SETTINGS.statusEffectType.hint",scope:"world",config:!0,default:"default",type:String,choices:iconChoices,onChange:iconType=>{StatusEffects.migrateStatusEffectUrls(iconType)}}),game.settings.register("pf2e","totmToggles",{name:"PF2E.SETTINGS.TOTMToggles.Name",hint:"PF2E.SETTINGS.TOTMToggles.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.totm=!!value,resetActors()}}),game.settings.register("pf2e","deathIcon",{name:"PF2E.SETTINGS.DeathIcon.Name",hint:"PF2E.SETTINGS.DeathIcon.Hint",scope:"world",config:!1,default:"icons/svg/skull.svg",type:String,onChange:choice=>{isImageOrVideoPath(choice)?StatusEffects.reset():choice||game.settings.set("pf2e","deathIcon","icons/svg/skull.svg")}}),game.settings.register("pf2e","nathMode",{name:"PF2E.SETTINGS.NathMode.Name",hint:"PF2E.SETTINGS.NathMode.Hint",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","statusEffectShowCombatMessage",{name:"PF2E.SETTINGS.statusEffectShowCombatMessage.name",hint:"PF2E.SETTINGS.statusEffectShowCombatMessage.hint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.registerMenu("pf2e","automation",{name:"PF2E.SETTINGS.Automation.Name",label:"PF2E.SETTINGS.Automation.Label",hint:"PF2E.SETTINGS.Automation.Hint",icon:"fa-solid fa-robot",type:AutomationSettings,restricted:!0}),game.settings.register("pf2e","automation.actorsDeadAtZero",{name:CONFIG.PF2E.SETTINGS.automation.actorsDeadAtZero.name,scope:"world",config:!1,choices:{neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},default:"both",type:String}),AutomationSettings.registerSettings(),game.settings.registerMenu("pf2e","metagame",{name:"PF2E.SETTINGS.Metagame.Name",label:"PF2E.SETTINGS.Metagame.Label",hint:"PF2E.SETTINGS.Metagame.Hint",icon:"fa-solid fa-brain",type:MetagameSettings,restricted:!0}),MetagameSettings.registerSettings(),game.settings.registerMenu("pf2e","variantRules",{name:"PF2E.SETTINGS.Variant.Name",label:"PF2E.SETTINGS.Variant.Label",hint:"PF2E.SETTINGS.Variant.Hint",icon:"fa-solid fa-book",type:VariantRulesSettings,restricted:!0}),VariantRulesSettings.registerSettings(),game.settings.registerMenu("pf2e","homebrew",{name:"PF2E.SETTINGS.Homebrew.Name",label:"PF2E.SETTINGS.Homebrew.Label",hint:"PF2E.SETTINGS.Homebrew.Hint",icon:"fa-solid fa-beer",type:HomebrewElements,restricted:!0}),HomebrewElements.registerSettings(),game.settings.registerMenu("pf2e","worldClock",{name:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.name),label:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.label),hint:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.hint),icon:"fa-regular fa-clock",type:WorldClockSettings,restricted:!0}),WorldClockSettings.registerSettings(),game.settings.register("pf2e","campaignType",{name:"PF2E.SETTINGS.CampaignType.Name",hint:"PF2E.SETTINGS.CampaignType.Hint",scope:"world",config:!1,default:"none",choices:mapToObj(["none","kingmaker"],key=>[key,`PF2E.SETTINGS.CampaignType.Choices.${key}`]),type:String,onChange:async()=>{await resetActors(game.actors.filter(a=>a.isOfType("party"))),ui.sidebar.render()}}),game.settings.register("pf2e","campaignFeats",{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.campaign.enabled=!!value,resetActors(game.actors.filter(a=>a.isOfType("character")))}}),game.settings.register("pf2e","campaignFeatSections",{name:"Campaign Feat Sections",scope:"world",config:!1,default:[],type:Array,onChange:value=>{game.pf2e.settings.campaign.sections=Array.isArray(value)?value:game.pf2e.settings.campaign.sections,resetActors(game.actors.filter(a=>a.isOfType("character")))}}),game.settings.register("pf2e","RAI.TreatWoundsAltSkills",{name:"Treat Wounds Macro Compat",scope:"world",config:!1,default:!0,type:Boolean}),game.settings.register("pf2e","gmVision",{name:"PF2E.SETTINGS.GMVision",scope:"client",config:!1,default:!1,type:Boolean,onChange:value=>{const color=value?CONFIG.PF2E.Canvas.darkness.gmVision:CONFIG.PF2E.Canvas.darkness.default;CONFIG.Canvas.darknessColor=color,canvas.colorManager.initialize()}}),game.settings.register("pf2e","seenLastStopMessage",{name:"Seen Last Stop Before Remaster Message",scope:"world",config:!1,type:Boolean,default:!1}),registerTrackingSettings(),registerWorldSchemaVersion()}__name(registerSettings,"registerSettings"),__name2(registerSettings,"registerSettings");function registerTrackingSettings(){game.settings.register("pf2e","createdFirstParty",{name:"Created First Party",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","activeParty",{name:"Active Party",scope:"world",config:!1,type:String,default:"",onChange:()=>{ui.actors.render(!0)}}),game.settings.register("pf2e","activePartyFolderState",{name:"Active Party Opened or closed",scope:"client",config:!1,type:Boolean,default:!0}),game.settings.register("pf2e","worldSystemVersion",{name:"World System Version",scope:"world",config:!1,default:game.system.version,type:String}),game.settings.register("pf2e","seenRemasterJournalEntry",{name:"Seen Remaster journal entry?",scope:"world",config:!1,default:!1,type:Boolean})}__name(registerTrackingSettings,"registerTrackingSettings"),__name2(registerTrackingSettings,"registerTrackingSettings");function registerWorldSchemaVersion(){game.settings.register("pf2e","worldSchemaVersion",{name:"PF2E.SETTINGS.WorldSchemaVersion.Name",hint:"PF2E.SETTINGS.WorldSchemaVersion.Hint",scope:"world",config:!0,default:MigrationRunner.LATEST_SCHEMA_VERSION,type:Number,requiresReload:!0})}__name(registerWorldSchemaVersion,"registerWorldSchemaVersion"),__name2(registerWorldSchemaVersion,"registerWorldSchemaVersion");const Init={listen:()=>{Hooks.once("init",()=>{if(console.log("PF2e System | Initializing Pathfinder 2nd Edition System"),CONFIG.PF2E=PF2ECONFIG,CONFIG.debug.ruleElement??=!1,CONFIG.AmbientLight.layerClass=LightingLayerPF2e,CONFIG.AmbientLight.objectClass=AmbientLightPF2e,CONFIG.MeasuredTemplate.objectClass=MeasuredTemplatePF2e,CONFIG.MeasuredTemplate.layerClass=TemplateLayerPF2e,CONFIG.MeasuredTemplate.defaults.angle=90,CONFIG.MeasuredTemplate.defaults.width=1,CONFIG.Token.objectClass=TokenPF2e,CONFIG.Token.layerClass=TokenLayerPF2e,CONFIG.Canvas.groups.effects.groupClass=EffectsCanvasGroupPF2e,CONFIG.Canvas.layers.lighting.layerClass=LightingLayerPF2e,CONFIG.Canvas.layers.templates.layerClass=TemplateLayerPF2e,CONFIG.Canvas.layers.tokens.layerClass=TokenLayerPF2e,setPerceptionModes(),CONFIG.time.roundTime=6,CONFIG.Combat.initiative.decimals=0,CONFIG.ui.actors=ActorDirectoryPF2e,CONFIG.ui.items=ItemDirectoryPF2e,CONFIG.ui.combat=EncounterTrackerPF2e,CONFIG.ui.chat=ChatLogPF2e,CONFIG.ui.compendium=CompendiumDirectoryPF2e,CONFIG.ui.hotbar=HotbarPF2e,CONFIG.specialStatusEffects.BLIND="blinded",document.querySelector("#ui-top")!==null){const uiTop=document.querySelector("#ui-top"),template=document.createElement("template");template.setAttribute("id","pf2e-effects-panel"),uiTop?.insertAdjacentElement("afterend",template)}CONFIG.TinyMCE.extended_valid_elements="pf2-action[action|glyph]",CONFIG.TinyMCE.content_css.push("systems/pf2e/styles/pf2e.css"),CONFIG.TinyMCE.style_formats=(CONFIG.TinyMCE.style_formats??[]).concat({title:"PF2E",items:[{title:"Icons 1 2 3 F R",inline:"span",classes:["action-glyph"],wrapper:!0},{title:"Inline Header",block:"h4",classes:"inline-header"},{title:"Info Block",block:"section",classes:"info",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Stat Block",block:"section",classes:"statblock",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Trait",block:"section",classes:"traits",wrapper:!0},{title:"Written Note",block:"p",classes:"message"},{title:"GM Text Block",block:"div",wrapper:!0,attributes:{"data-visibility":"gm"}},{title:"GM Text Inline",inline:"span",attributes:{"data-visibility":"gm"}}]}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Check|Localize|Template)\[([^\]]+)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Damage)\[((?:[^[\]]*|\[[^[\]]*\])*)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),registerFonts(),registerHandlebarsHelpers(),registerKeybindings(),registerSettings(),registerTemplates(),MystifiedTraits.compile(),SetGamePF2e.onInit();for(const element of htmlQueryAll(document.head,"link[rel=stylesheet]")){const href=element.getAttribute("href");href?.startsWith("modules/")&&href.endsWith("tagify.css")&&element.setAttribute("disabled","")}game.pf2e.StatusEffects.initialize()})}},LightingRefresh={listen:()=>{Hooks.on("lightingRefresh",()=>{SceneDarknessAdjuster.instance.onLightingRefresh(canvas.darknessLevel)})}};class ActiveEffectPF2e extends ActiveEffect{static{__name(this,"ActiveEffectPF2e")}static{__name2(this,"ActiveEffectPF2e")}constructor(data,context){data.disabled=!0,data.transfer=!1,super(data,context)}static async createDocuments(){return[]}}class ActorsPF2e extends Actors{static{__name(this,"ActorsPF2e")}static{__name2(this,"ActorsPF2e")}get party(){const activePartyId=game.settings.get("pf2e","activeParty"),actor=this.get(activePartyId);return actor?.isOfType("party")?actor:this.find(a=>a.isOfType("party"))??null}_getVisibleTreeContents(){return super._getVisibleTreeContents().filter(a=>a.isOfType("creature")&&!a.parties.size||!a.isOfType("party","creature"))}}class ActorDeltaPF2e extends ActorDelta{static{__name(this,"ActorDeltaPF2e")}static{__name2(this,"ActorDeltaPF2e")}prepareData(){super.prepareData(),!game.ready&&!this.parent?.isLinked&&this.syntheticActor?.reset()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.traits?.size&&this.parent?.rendered&&this.parent.object?._onUpdate({width:this.parent.width},{...options,parent:this.parent.scene},userId)}_dispatchDescendantDocumentEvents(event2,collection,args,parent){super._dispatchDescendantDocumentEvents(event2,collection,args,parent);const isPostWriteCallback=["onCreate","onUpdate","onDelete"].includes(event2);if(!this.parent||this.parent.isLinked||!this.parent.rendered||!isPostWriteCallback)return;const items=(args[0]??[]).filter(i=>i instanceof ItemPF2e),nameChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenName")),sizeChanged=items.some(i=>i.system.rules.some(r=>r.key==="CreatureSize")),textureChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenImage"))||!!this.syntheticActor?.rules.some(r=>r.key==="TokenImage"),lightChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenLight"));if(nameChanged||sizeChanged||textureChanged||lightChanged){this.parent.reset();const fakeUpdates={};nameChanged&&(fakeUpdates.name=this.parent.name),sizeChanged&&(fakeUpdates.width=this.parent.width),textureChanged&&(fakeUpdates.texture=foundry.utils.deepClone(this.parent._source.texture)),lightChanged&&(fakeUpdates.light=foundry.utils.deepClone(this.parent._source.light)),this.parent.object?._onUpdate(fakeUpdates,{parent:this.parent.scene},game.user.id)}}}function monkeyPatchFoundry(){TextEditor.enrichHTML=TextEditorPF2e.enrichHTML,TextEditor._enrichContentLinks=TextEditorPF2e._enrichContentLinks,TextEditor._createInlineRoll=TextEditorPF2e._createInlineRoll,TextEditor._onClickInlineRoll=TextEditorPF2e._onClickInlineRoll}__name(monkeyPatchFoundry,"monkeyPatchFoundry"),__name2(monkeyPatchFoundry,"monkeyPatchFoundry");class ClientDatabaseBackendPF2e extends ClientDatabaseBackend{static{__name(this,"ClientDatabaseBackendPF2e")}static{__name2(this,"ClientDatabaseBackendPF2e")}async _getDocuments(documentClass,context,user){const type=documentClass.documentName;if(!["Actor","Item"].includes(type)||context.pack?.startsWith("pf2e.")||context.options?.index)return super._getDocuments(documentClass,context,user);const request2={action:"get",type,...pick(context,["query","options","pack"])},response=await SocketInterface.dispatch("modifyDocument",request2);return Promise.all(response.result.map(async data=>{const document2=documentClass.fromSource(data,{pack:context.pack}),migrations=MigrationList.constructFromVersion(document2.schemaVersion);if(migrations.length>0)try{await MigrationRunner.ensureSchemaVersion(document2,migrations)}catch(error){error instanceof Error&&console.error(error.message)}return document2}))}}const Load={listen(){CONFIG.DatabaseBackend=new ClientDatabaseBackendPF2e,CONFIG.ActiveEffect.documentClass=ActiveEffectPF2e,CONFIG.Actor.collection=ActorsPF2e,CONFIG.Actor.documentClass=ActorProxyPF2e,CONFIG.ActorDelta.documentClass=ActorDeltaPF2e,CONFIG.AmbientLight.documentClass=AmbientLightDocumentPF2e,CONFIG.ChatMessage.documentClass=ChatMessagePF2e,CONFIG.Combat.documentClass=EncounterPF2e,CONFIG.Combatant.documentClass=CombatantPF2e,CONFIG.Item.documentClass=ItemProxyPF2e,CONFIG.Macro.documentClass=MacroPF2e,CONFIG.MeasuredTemplate.documentClass=MeasuredTemplateDocumentPF2e,CONFIG.Scene.documentClass=ScenePF2e,CONFIG.Tile.documentClass=TileDocumentPF2e,CONFIG.Token.documentClass=TokenDocumentPF2e,CONFIG.Token.prototypeSheetClass=TokenConfigPF2e,CONFIG.User.documentClass=UserPF2e,CONFIG.Canvas.darknessColor=2960722,CONFIG.Canvas.exploredColor=2500134,CONFIG.Dice.rolls.push(CheckRoll,StrikeAttackRoll,DamageRoll,DamageInstance);for(const TermCls of[ArithmeticExpression,Grouping,InstancePool,IntermediateDie])CONFIG.Dice.termTypes[TermCls.name]=TermCls;Math.eq=(a,b)=>a===b,Math.gt=(a,b)=>a>b,Math.gte=(a,b)=>a>=b,Math.lt=(a,b)=>a<b,Math.lte=(a,b)=>a<=b,Math.ne=(a,b)=>a!==b,Math.ternary=(condition,ifTrue,ifFalse)=>condition?ifTrue:ifFalse,Actor.DEFAULT_ICON="systems/pf2e/icons/default-icons/mystery-man.svg",CONFIG.Actor.typeIcons={familiar:"fa-solid fa-cat",hazard:"fa-solid fa-hill-rockslide",loot:"fa-solid fa-treasure-chest"},CONFIG.Item.typeIcons={action:"fa-solid fa-person-running-fast",affliction:"fa-solid fa-biohazard",armor:"fa-solid fa-shirt-long-sleeve",backpack:"fa-solid fa-sack",book:"fa-solid fa-book",condition:"fa-solid fa-face-zany",consumable:"fa-solid fa-flask-round-potion",deity:"fa-solid fa-hamsa",effect:"fa-solid fa-person-rays",equipment:"fa-solid fa-hat-cowboy",feat:"fa-solid fa-medal",shield:"fa-solid fa-shield-halved",spell:"fa-solid fa-sparkles",treasure:"fa-solid fa-gem",weapon:"fa-solid fa-sword"},window.AutomaticBonusProgression=AutomaticBonusProgression,monkeyPatchFoundry(),document.addEventListener("mouseup",()=>{const element=document.activeElement;element instanceof HTMLButtonElement&&!element.classList.contains("pm-dropdown")&&element.blur()})}};async function createFirstParty(){game.user!==game.users.activeGM||game.settings.get("pf2e","createdFirstParty")||(game.actors.some(a=>a.isOfType("party"))||(await ActorPF2e.create({_id:CONFIG.PF2E.defaultPartyId,type:"party",name:game.i18n.localize("PF2E.Actor.Party.DefaultName")},{keepId:!0}),await game.settings.set("pf2e","activeParty",CONFIG.PF2E.defaultPartyId)),await game.settings.set("pf2e","createdFirstParty",!0))}__name(createFirstParty,"createFirstParty"),__name2(createFirstParty,"createFirstParty");class MigrationSummary extends Application{static{__name(this,"MigrationSummary")}static{__name2(this,"MigrationSummary")}#isRemigrating=!1;constructor(options={}){super(options),this.options.troubleshoot??=!1,this.options.title=options.troubleshoot?game.i18n.localize("PF2E.Migrations.Summary.Troubleshoot.Title"):game.i18n.localize("PF2E.Migrations.Summary.Title");const existing=Object.values(ui.windows).find(app=>app instanceof MigrationSummary);if(existing)return existing.options=foundry.utils.mergeObject(existing.options,options),existing}static get defaultOptions(){return{...super.defaultOptions,id:"migration-summary",width:400,height:"auto",template:"systems/pf2e/templates/system/migration-summary.hbs"}}async getData(){const latestSchemaVersion=MigrationRunner.LATEST_SCHEMA_VERSION,actors={successful:game.actors.filter(actor=>actor.schemaVersion===latestSchemaVersion).length,total:game.actors.size},items={successful:game.items.filter(item=>item.schemaVersion===latestSchemaVersion).length,total:game.items.size},canRemigrate=this.options.troubleshoot||actors.successful<actors.total||items.successful<items.total,helpResourcesText=await TextEditor.enrichHTML(game.i18n.localize("PF2E.Migrations.Summary.HelpResources"),{async:!0});return{options:this.options,systemVersion:game.system.version,latestSchemaVersion,actors,items,canRemigrate,helpResources:canRemigrate&&this.#isRemigrating,helpResourcesText}}activateListeners($html){super.activateListeners($html);const html=$html[0],remigrateButton=html.querySelector("button[data-action=remigrate]");remigrateButton?.addEventListener("click",async()=>{const{LATEST_SCHEMA_VERSION,RECOMMENDED_SAFE_VERSION}=MigrationRunner,lowestVersions={actor:game.actors.size>0?Math.min(...game.actors.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION,item:game.items.size>0?Math.min(...game.items.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION},lowestSchemaVersion=Math.max(Math.min(lowestVersions.actor,lowestVersions.item),RECOMMENDED_SAFE_VERSION),result=html.querySelector(".docs-successful");result&&(result.textContent="...");try{this.#isRemigrating=!0,this.options.troubleshoot=!1,remigrateButton.disabled=!0,await game.pf2e.system.remigrate({from:lowestSchemaVersion}),this.options.troubleshoot=!1,this.render(!1)}catch{return}}),html.querySelector("button[data-action=close]")?.addEventListener("click",()=>{this.close()})}}function activateSocketListener(){game.socket.on("system.pf2e",async(...[message,userId])=>{const sender=game.users.get(userId,{strict:!0});switch(message.request){case"itemTransfer":if(game.user.isGM){console.debug(`PF2e System | Received item-transfer request from ${sender.name}`);const{data}=message;new ItemTransfer(data.source,data.target,data.quantity,data.containerId).enact(sender)}break;case"refreshSceneControls":!game.user.isGM&&message.data.layer===ui.controls.control?.layer&&(console.debug("PF2e System | Refreshing Scene Controls"),ui.controls.initialize({layer:message.data.layer}));break;case"showSheet":{const document2=await fromUuid(message.document);if(!sender.isGM||!document2)return;const{tab,campaign}=message.options??{};if(campaign){if(!(document2 instanceof PartyPF2e))return;const type=campaign===!0?null:campaign;return document2.campaign?.renderSheet?.({tab,type})}document2.sheet.render(!0,{tab});break}default:throw ErrorPF2e(`Received unrecognized socket emission: ${message.request}`)}})}__name(activateSocketListener,"activateSocketListener"),__name2(activateSocketListener,"activateSocketListener");async function storeInitialWorldVersions(){if(!game.user.hasRole(CONST.USER_ROLES.GAMEMASTER))return;if(game.settings.storage.get("world").getItem("pf2e.worldSystemVersion")||await game.settings.set("pf2e","worldSystemVersion",game.system.version),!game.settings.storage.get("world").getItem("pf2e.worldSchemaVersion")){const minimumVersion=MigrationRunner.RECOMMENDED_SAFE_VERSION,currentVersion=game.actors.size===0?game.settings.get("pf2e","worldSchemaVersion"):Math.max(Math.min(...new Set(game.actors.map(actor=>actor.schemaVersion??minimumVersion))),minimumVersion);await game.settings.set("pf2e","worldSchemaVersion",currentVersion)}}__name(storeInitialWorldVersions,"storeInitialWorldVersions"),__name2(storeInitialWorldVersions,"storeInitialWorldVersions");function extendDragData(){document.body.addEventListener("dragstart",event2=>{const{dataTransfer,target}=event2;if(dataTransfer&&target instanceof HTMLAnchorElement){if(target.classList.contains("content-link")){const data=JSON.parse(dataTransfer.getData("text/plain"));if(data.type!=="Item")return;const match=target.innerText.trim().match(/[0-9]+/);match&&(data.value=Number(match[0]));const containerElement=htmlClosest(target,"[data-cast-level]"),castLevel=Number(containerElement?.dataset.castLevel);castLevel>0&&(data.level=castLevel);const messageId=htmlClosest(target,"li.chat-message")?.dataset.messageId,message=game.messages.get(messageId??""),originItem=message?.item;if(message?.actor){const{actor,token,target:target2}=message,roll=message.rolls.at(-1),spellcasting=originItem?.isOfType("spell")&&originItem.spellcasting?{attribute:{type:originItem.attribute,mod:originItem.spellcasting.statistic?.attributeModifier?.value??0},tradition:originItem.spellcasting.tradition}:null;data.context={origin:{actor:actor.uuid,token:token?.uuid??null,item:originItem?.uuid??null,spellcasting},target:target2?{actor:target2.actor.uuid,token:target2.token.uuid}:null,roll:roll?{total:roll.total,degreeOfSuccess:roll instanceof CheckRoll?roll.degreeOfSuccess??null:null}:null}}dataTransfer.setData("text/plain",JSON.stringify(data))}else if("persistent"in target.dataset&&target.dataset.formula){const data={type:"PersistentDamage",formula:target.dataset.formula};dataTransfer.setData("text/plain",JSON.stringify(data))}}})}__name(extendDragData,"extendDragData"),__name2(extendDragData,"extendDragData");const Ready={listen:()=>{Hooks.once("ready",()=>{console.log("PF2e System | Starting Pathfinder 2nd Edition System"),console.debug("PF2e System | Build mode: production"),SetGamePF2e.onReady(),game.scenes.apps.push(SceneDarknessAdjuster.instance);const currentVersion=game.settings.get("pf2e","worldSchemaVersion");storeInitialWorldVersions().then(async()=>{if(game.user!==game.users.activeGM)return;await createFirstParty();const migrationRunner=new MigrationRunner(MigrationList.constructFromVersion(currentVersion));migrationRunner.needsMigration()&&(currentVersion&¤tVersion<MigrationRunner.MINIMUM_SAFE_VERSION&&ui.notifications.error("Your PF2E system data is from too old a Foundry version and cannot be reliably migrated to the latest version. The process will be attempted, but errors may occur.",{permanent:!0}),await migrationRunner.runMigration(),new MigrationSummary().render(!0));const previous=game.settings.get("pf2e","worldSystemVersion"),current=game.system.version;foundry.utils.isNewerVersion(current,previous)&&await game.settings.set("pf2e","worldSystemVersion",current);const abandonedModules=new Set([]),subV10Modules=game.modules.filter(m=>m.active&&(m.esmodules.size>0||m.scripts.size>0)&&!!m.compatibility.verified&&(abandonedModules.has(m.id)||!foundry.utils.isNewerVersion(m.compatibility.verified,"10.312")));for(const badModule of subV10Modules){const message=game.i18n.format("PF2E.ErrorMessage.SubV9Module",{module:badModule.title});ui.notifications.warn(message),console.warn(message)}});for(const li of htmlQueryAll(document.body,"#chat-log > li.message"))SetAsInitiative.listen(li);activateSocketListener(),extendDragData(),canvas.ready&&game.user.isGM&&!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.settings.get("pf2e","gmVision")&&(CONFIG.Canvas.darknessColor=CONFIG.PF2E.Canvas.darkness.gmVision,canvas.colorManager.initialize()),game.system.documentTypes.Item.sort((typeA,typeB)=>game.i18n.localize(CONFIG.Item.typeLabels[typeA]??"").localeCompare(game.i18n.localize(CONFIG.Item.typeLabels[typeB]??""))),game.pf2e.system.moduleArt.refresh().then(()=>{ui.compendium.compileSearchIndex()});const actorsToReprepare=compact([...game.combats.contents.flatMap(e=>e.combatants.contents).map(c=>c.actor),...game.actors.filter(a=>a.isOfType("party")).flatMap(p=>p.members).filter(a=>!a.isOfType("familiar")),...game.actors.filter(a=>a.type==="familiar")]);if(resetActors(new Set(actorsToReprepare)),game.user.isGM&&!game.settings.get("pf2e","seenRemasterJournalEntry")&&(fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)}),game.settings.set("pf2e","seenRemasterJournalEntry",!0)),game.combat){for(const encounter of game.combats)encounter.reset();ui.combat.render()}Hooks.callAll("pf2e.systemReady")})}},RenderChatPopout={listen:()=>{Hooks.on("renderChatPopout",(_app,$html)=>{ui.chat.activateClickListener($html[0])})}},RenderCombatTrackerConfig={listen:()=>{Hooks.on("renderCombatTrackerConfig",async(app,$html)=>{const html=$html[0],appWindow=htmlClosest(html,"#combat-config");appWindow&&(appWindow.style.height="");const template=await(async()=>{const markup=await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/config.hbs",{values:{deathIcon:game.settings.get("pf2e","deathIcon"),actorsDeadAtZero:game.settings.get("pf2e","automation.actorsDeadAtZero")}}),tempElem=document.createElement("div");return tempElem.innerHTML=markup,tempElem.firstElementChild instanceof HTMLTemplateElement?tempElem.firstElementChild:null})();htmlQueryAll(html,".form-group").at(-1)?.after(...template?.content.children??[]),app.activateListeners($html)})}},PC_ITEM_TYPES=new Set(["ancestry","background","class","deity","feat","heritage"]),RenderDialog={listen:()=>{Hooks.on("renderDialog",(_dialog,$html)=>{const html=$html[0];if(InlineRollLinks.listen(html),html.classList.contains("dialog-item-create")){const select=html.querySelector("select[name=type]"),option=select?.querySelector("option");if(select&&option){const localize=localizer("PF2E.Item.CreationDialog.Categories");select.append(extractOptGroup(select,localize("Physical"),[...PHYSICAL_ITEM_TYPES,"kit"])),select.append(extractOptGroup(select,localize("Character"),Array.from(PC_ITEM_TYPES))),select.append(extractOptGroup(select,localize("Other"))),option.selected=!0}}})}};function extractOptGroup(select,label,types){const filtered=[...select.querySelectorAll(":scope > option").values()].filter(option=>!types||types.includes(option.value)),optgroup=document.createElement("optgroup");optgroup.label=label;for(const physicalElement of filtered)optgroup.appendChild(physicalElement);return optgroup}__name(extractOptGroup,"extractOptGroup"),__name2(extractOptGroup,"extractOptGroup");const RenderJournalPageSheet={listen:()=>{Hooks.on("renderJournalPageSheet",(sheet,$html)=>{const pageEl=$html.get(0)?.closest(".journal-entry-page"),parentSheetClass=sheet.object.parent?.sheet.constructor;if(!parentSheetClass||!pageEl)return;const theme=parentSheetClass.theme?String(parentSheetClass.theme):null;theme&&pageEl.classList.add(theme)})}},RenderJournalTextPageSheet={listen:()=>{Hooks.on("renderJournalTextPageSheet",(sheet,$html)=>{const content=$html.filter(".journal-page-content").get(0);content&&(InlineRollLinks.listen(content,sheet.document),UserVisibilityPF2e.process(content,sheet))})}},RenderSettings={listen:()=>{Hooks.on("renderSettings",async(_app,$html)=>{const html=$html[0],systemRow=html.querySelector(".settings-sidebar li.system"),systemInfo=systemRow?.cloneNode(!1);if(!(systemInfo instanceof HTMLLIElement))throw ErrorPF2e("Unexpected error attaching system information to settings sidebar");systemInfo.classList.remove("system"),systemInfo.classList.add("system-links");const links=[{url:"https://github.com/foundryvtt/pf2e/blob/release/CHANGELOG.md",label:"PF2E.SETTINGS.Sidebar.Changelog"},{url:"https://github.com/foundryvtt/pf2e/wiki",label:"PF2E.SETTINGS.Sidebar.Wiki"},{url:"https://discord.gg/SajryVzCyf",label:"PF2E.SETTINGS.Sidebar.Discord"}].map(data=>{const anchor=document.createElement("a");return anchor.href=data.url,anchor.innerText=game.i18n.localize(data.label),anchor.target="_blank",anchor});systemInfo.append(...links),systemRow?.after(systemInfo);const header=createHTMLElement("h2",{children:[game.system.title]}),pf2eSettings=createHTMLElement("div");html.querySelector("#settings-documentation")?.after(header,pf2eSettings);const licenseButton=document.createElement("button");licenseButton.type="button",licenseButton.append(fontAwesomeIcon("balance-scale"),game.i18n.localize("PF2E.LicenseViewer.Label")),licenseButton.addEventListener("click",()=>{game.pf2e.licenseViewer.render(!0)});const remasterButton=document.createElement("button");if(remasterButton.type="button",remasterButton.append(fontAwesomeIcon("rocket"),game.i18n.localize("PF2E.SETTINGS.Sidebar.Remaster")),remasterButton.addEventListener("click",()=>{fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)})}),pf2eSettings.append(licenseButton,remasterButton),game.user.isGM){const shootButton=document.createElement("button");shootButton.type="button",shootButton.append(fontAwesomeIcon("wrench"),game.i18n.localize("PF2E.Migrations.Troubleshooting")),shootButton.addEventListener("click",()=>{new MigrationSummary({troubleshoot:!0}).render(!0)}),pf2eSettings.append(shootButton)}})}};class PartyClownCar{static{__name(this,"PartyClownCar")}static{__name2(this,"PartyClownCar")}party;token;constructor(token){if(this.token=token,!this.token.scene.isOwner)throw ErrorPF2e("Cannot write to scene");const party=token.actor;if(!party?.isOfType("party"))throw ErrorPF2e("Unexpected actor type");this.party=party}get scene(){return this.token.scene}get memberTokens(){return this.party.members.flatMap(m=>m.getActiveTokens(!0,!0))}toggleState(){return this.memberTokens.length>0?this.#retrieve():this.#deposit()}async#retrieve(){const tokens=this.memberTokens,updates=tokens.map(t=>({_id:t.id,...pick(this.token,["x","y"])})),animation={spin:!0};await this.scene.updateEmbeddedDocuments("Token",updates,{animation}),await Promise.all(tokens.map(async token=>(await token.object?._animation,token.delete())))}async#deposit(){const{token}=this;if(!token.object)return;const newTokens=(await Promise.all(this.party.members.map(m=>m.getTokenDocument({x:token.x,y:token.y})))).map(t=>({...t.toObject(),x:token.x,y:token.y})),createdTokens=await this.scene.createEmbeddedDocuments("Token",newTokens),freeSpaces=this.#getDepositSpaces(),placementData=createdTokens.map((t,index)=>({_id:t._id,...pick(freeSpaces.at(index)??token,["x","y"])}));await this.scene.updateEmbeddedDocuments("Token",placementData)}#getDepositSpaces(){const placeable=this.token.object;if(!placeable)return[];const{center}=placeable,diameter=placeable.bounds.width*7,radiusPixels=diameter/2,radius=radiusPixels/(canvas.dimensions?.distance??5),areaBounds=new PIXI.Rectangle(center.x-radiusPixels,center.y-radiusPixels,diameter,diameter),squares=getAreaSquares({bounds:areaBounds,radius,token:placeable}).filter(s=>s.active);return sortBy(squares.filter(s=>!(s.x===placeable.x&&s.y===placeable.y)&&!(s.center.x===center.x&&s.center.y===center.y)&&!placeable.checkCollision(s.center,{type:"move",mode:"any"})).reverse(),s=>canvas.grid.measureDistance(center,s.center))}}class RenderTokenHUD{static{__name(this,"RenderTokenHUD")}static{__name2(this,"RenderTokenHUD")}static listen(){Hooks.on("renderTokenHUD",(_app,$html,data)=>{const html=$html[0];game.pf2e.StatusEffects.onRenderTokenHUD(html,data);const token=canvas.scene?.tokens.get(data._id??"")?.object;this.addClownCarButton(html,token),token?.actor?.isOfType("army")&&htmlQuery(html,".control-icon[data-action=effects]")?.remove()})}static addClownCarButton(html,token){if(!token?.actor?.isOfType("party"))return;const{actor}=token,actionIcon=(()=>{const imgElement=document.createElement("img");imgElement.src="systems/pf2e/icons/other/enter-exit.svg";const willRetrieve=actor.members.some(m=>m.getActiveTokens(!0,!0).length>0);return imgElement.className=willRetrieve?"retrieve":"deposit",imgElement.title=game.i18n.localize(willRetrieve?"PF2E.Actor.Party.ClownCar.Retrieve":"PF2E.Actor.Party.ClownCar.Deposit"),imgElement})(),controlButton=createHTMLElement("div",{classes:["control-icon"],dataset:{action:"clown-car"},children:[actionIcon]});controlButton.addEventListener("click",async()=>{if(!controlButton.dataset.disabled){controlButton.dataset.disabled="true";try{await new PartyClownCar(token.document).toggleState();const switchToDeposit=actionIcon.className==="retrieve";actionIcon.className=switchToDeposit?"deposit":"retrieve",actionIcon.title=game.i18n.localize(switchToDeposit?"PF2E.Actor.Party.ClownCar.Deposit":"PF2E.Actor.Party.ClownCar.Retrieve")}finally{delete controlButton.dataset.disabled}}}),htmlQuery(html,"[data-action=effects]")?.replaceWith(controlButton)}}class ArmySheetPF2e extends ActorSheetPF2e{static{__name(this,"ArmySheetPF2e")}static{__name2(this,"ArmySheetPF2e")}basicWarActions=[];itemRenderer=new ArmyItemRenderer(this);static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"army"],width:750,height:625,template:"systems/pf2e/templates/actors/army/sheet.hbs",scrollY:[".sheet-body"]}}async getData(options){const data=await super.getData(options),actor=this.actor,campaignFeatures=actor.itemTypes.campaignFeature;if(!this.basicWarActions.length){const compendiumFeatures=(await game.packs.get("pf2e.kingmaker-features")?.getDocuments({type:"campaignFeature"})??[]).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature"));this.basicWarActions=compendiumFeatures.filter(d=>d.system.category==="army-war-action"&&d.folder?.id===BASIC_WAR_ACTIONS_FOLDER).map(i=>new ItemProxyPF2e(i.toObject(!0),{parent:this.actor})).filter(i=>i.isOfType("campaignFeature"))}return{...data,ac:{value:actor.armorClass.value,breakdown:actor.armorClass.breakdown,adjustmentClass:getAdjustment(actor.armorClass.value,actor._source.system.ac.value+actor.system.ac.potency)},consumption:getAdjustedValue(actor.system.consumption,actor._source.system.consumption,{better:"lower"}),hitPoints:{value:actor.system.attributes.hp.value,max:getAdjustedValue(actor.system.attributes.hp.max,actor._source.system.attributes.hp.max),routThreshold:getAdjustedValue(actor.system.attributes.hp.routThreshold,actor._source.system.attributes.hp.routThreshold,{better:"lower"})},linked:!!actor.prototypeToken.actorLink&&(!actor.token||actor.token.isLinked),alignments:ALIGNMENTS,armyTypes:pick(kingmakerTraits,ARMY_TYPES),rarityTraits:CONFIG.PF2E.rarityTraits,saves:sortBy(["maneuver","morale"].map(slug=>{const statistic=this.actor[slug];return{slug,label:statistic.label,mod:statistic.mod,breakdown:statistic.check.breakdown,adjustmentClass:getAdjustment(statistic.mod,this.actor._source.system.saves[slug])}}),s=>s.label),basicWarActions:this.basicWarActions,warActions:campaignFeatures.filter(f=>f.category==="army-war-action")}}activateListeners($html){super.activateListeners($html);const html=$html[0],levelInput=htmlQuery(html,".level");levelInput?.addEventListener("change",()=>{const value=levelInput.value;this.actor.updateLevel(Number(value))});for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event2=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event2,{type:"check"}))})}htmlQuery(html,"[data-action=link-actor]")?.addEventListener("click",()=>{this.actor.token?ui.notifications.error("PF2E.Kingmaker.Army.Alliance.LinkError",{localize:!0}):this.actor.update({prototypeToken:{actorLink:!0}})});for(const resourceElement of htmlQueryAll(html,"[data-action=change-resource]")){const resource=resourceElement.dataset.resource;if(!tupleHasValue(["potions","ammunition"],resource))continue;const max=this.actor.system.resources[resource].max;resourceElement.addEventListener("click",()=>{const newValue=Math.clamped(this.actor.system.resources[resource].value+1,0,max);this.actor.update({[`system.resources.${resource}.value`]:newValue})}),resourceElement.addEventListener("contextmenu",event2=>{event2.preventDefault();const newValue=Math.clamped(this.actor.system.resources[resource].value-1,0,max);this.actor.update({[`system.resources.${resource}.value`]:newValue})})}htmlQuery(html,"[data-action=reset-ammo]")?.addEventListener("click",()=>{const max=this.actor.system.resources.ammunition.max;this.actor.update({"system.resources.ammunition.value":max})}),htmlQuery(html,"[data-action=use-potion]")?.addEventListener("click",()=>{this.actor.usePotion()});for(const gearElement of htmlQueryAll(html,"[data-action=change-magic-armor]"))gearElement.addEventListener("click",()=>{const newValue=Math.clamped(this.actor.system.ac.potency+1,0,3);this.actor.update({"system.ac.potency":newValue})}),gearElement.addEventListener("contextmenu",event2=>{event2.preventDefault();const newValue=Math.clamped(this.actor.system.ac.potency-1,0,3);this.actor.update({"system.ac.potency":newValue})});for(const gearElement of htmlQueryAll(html,"[data-action=change-magic-weapon]")){const gear=gearElement.dataset.weapon;if(!tupleHasValue(["melee","ranged"],gear))continue;const data=this.actor.system.weapons[gear];gearElement.addEventListener("click",()=>{if(data){const newValue=Math.clamped(data.potency+1,0,3);this.actor.update({[`system.weapons.${gear}.potency`]:newValue})}else{const newData={name:"",potency:0};this.actor.update({[`system.weapons.${gear}`]:newData})}}),gearElement.addEventListener("contextmenu",event2=>{if(event2.preventDefault(),!!data)if(data.potency===0)this.actor.update({[`system.weapons.${gear}`]:null});else{const newValue=Math.clamped(data.potency-1,0,3);this.actor.update({[`system.weapons.${gear}.potency`]:newValue})}})}const gearData=getArmyGearData();for(const showGear of htmlQueryAll(html,"[data-action=show-gear]")){const rawGearType=showGear.dataset.gear,gearType=tupleHasValue(["melee","ranged"],rawGearType)&&!this.actor.system.weapons[rawGearType]?`additional-${rawGearType}`:rawGearType;if(!objectHasKey(gearData,gearType))continue;const kingmakerTraits2=CONFIG.PF2E.kingmakerTraits,actionTraits2=CONFIG.PF2E.actionTraits,descriptions=CONFIG.PF2E.traitsDescriptions;showGear.addEventListener("click",async()=>{const gear=gearData[gearType];ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor:this.actor}),content:await renderTemplate("systems/pf2e/templates/actors/army/gear-card.hbs",{...gear,level:gear.level??(gear.ranks?.length?`${gear.ranks[0].level}+`:null),traits:gear.traits.map(t=>({label:game.i18n.localize(kingmakerTraits2[t]??actionTraits2[t]??t),description:game.i18n.localize(descriptions[t]??"")}))})})})}htmlQuery(html,"[data-action=edit-description]")?.addEventListener("click",()=>{this.activateEditor("system.details.description")});for(const strikeAttack of htmlQueryAll(html,"[data-action=strike-attack]")){const type=htmlClosest(strikeAttack,"[data-strike]")?.dataset.strike,variant=Number(strikeAttack.dataset.variantIndex);objectHasKey(this.actor.strikes,type)&&strikeAttack.addEventListener("click",event2=>{this.actor.strikes[type]?.variants[variant]?.roll({event:event2})})}for(const strikeDamage of htmlQueryAll(html,"[data-action=strike-damage]")){const type=htmlClosest(strikeDamage,"[data-strike]")?.dataset.strike,outcome=strikeDamage.dataset.outcome==="criticalSuccess"?"critical":"damage";objectHasKey(this.actor.strikes,type)&&strikeDamage.addEventListener("click",event2=>{this.actor.strikes[type]?.[outcome]({event:event2})})}}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers["toggle-basic-war-action-summary"]=async event2=>{const element=htmlClosest(event2.target,"[data-slug]");element&&this.itemRenderer.toggleSummary(element)},handlers["use-basic-war-action"]=async event2=>{const slug=htmlClosest(event2.target,"[data-slug]")?.dataset.slug;this.basicWarActions.find(a=>a.slug===slug)?.toMessage(event2)},handlers}async _onDropItem(event2,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event2,data);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const slotData=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null};return(slotData.groupId==="tactics"?this.actor.tactics:this.actor.bonusTactics).insertFeat(item,slotData.slotId)}return super._onDropItem(event2,data)}async _onSortItem(event2,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const featSlot=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null},group=featSlot.groupId==="tactics"?this.actor.tactics:this.actor.bonusTactics,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return group.insertFeat(item,featSlot.slotId)}return super._onSortItem(event2,itemSource)}#getFeatSlotData(event2){const groupId=event2.target?.closest("[data-group-id]")?.dataset.groupId,slotId=event2.target?.closest("[data-slot-id]")?.dataset.slotId;return typeof groupId=="string"?{slotId,groupId}:null}}class ArmyItemRenderer extends ItemSummaryRenderer{static{__name(this,"ArmyItemRenderer")}static{__name2(this,"ArmyItemRenderer")}async getItemFromElement(element){const slug=element.dataset.slug;return this.sheet.basicWarActions.find(a=>a.slug===slug)??super.getItemFromElement(element)}}class FamiliarSheetPF2e extends CreatureSheetPF2e{static{__name(this,"FamiliarSheetPF2e")}static{__name2(this,"FamiliarSheetPF2e")}actorConfigClass=null;static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"familiar"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"attributes"}]}}get template(){return"systems/pf2e/templates/actors/familiar-sheet.hbs"}async getData(options){const sheetData=await super.getData(options),familiar=this.actor,masters=game.actors.filter(a=>a.type==="character"&&a.testUserPermission(game.user,"OWNER")),abilities2=CONFIG.PF2E.abilities,size=CONFIG.PF2E.actorSizes[familiar.system.traits.size.value]??null,familiarAbilities=this.actor.master?.attributes?.familiarAbilities;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.label=CONFIG.PF2E.saves[key]}const skills=Object.values(sheetData.data.skills).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));return{...sheetData,master:this.actor.master,masters,abilities:abilities2,size,skills,familiarAbilities:{value:familiarAbilities?.value??0,items:sortBy(this.actor.itemTypes.action,a=>a.sort)}}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,".rollable[data-action=perception-check]")?.addEventListener("click",event2=>{this.actor.perception.roll(eventToRollParams(event2,{type:"check"}))}),htmlQuery(html,".rollable[data-attack-roll]")?.addEventListener("click",event2=>{this.actor.attackStatistic.roll(eventToRollParams(event2,{type:"check"}))})}}class HazardSheetPF2e extends ActorSheetPF2e{static{__name(this,"HazardSheetPF2e")}static{__name2(this,"HazardSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return foundry.utils.mergeObject(options,{classes:[...options.classes,"hazard"],scrollY:[".container > section"],width:700,height:680}),options}get template(){return"systems/pf2e/templates/actors/hazard/sheet.hbs"}get title(){return this.editing?game.i18n.format("PF2E.Actor.Hazard.TitleEdit",{name:super.title}):super.title}get editing(){return this.options.editable&&!!this.actor.getFlag("pf2e","editHazard.value")}async getData(options){const sheetData=await super.getData(options);sheetData.actor.flags.editHazard??={value:!1};const systemData=sheetData.data,actor=this.actor,{hasDefenses}=actor,hasImmunities=systemData.attributes.immunities.length>0,hasResistances=systemData.attributes.resistances.length>0,hasWeaknesses=systemData.attributes.weaknesses.length>0,hasIWR=hasDefenses||hasImmunities||hasResistances||hasWeaknesses,stealthMod=actor.system.attributes.stealth.value,stealthDC=typeof stealthMod=="number"?stealthMod+10:null,hasStealthDescription=!!systemData.attributes.stealth?.details,rollData=this.actor.getRollData(),enrich=__name2(async content=>TextEditor.enrichHTML(content??"",{rollData,async:!0}),"enrich");sheetData.enrichedContent=foundry.utils.mergeObject(sheetData.enrichedContent,{stealthDetails:await enrich(systemData.attributes.stealth.details),description:await enrich(systemData.details.description),disable:await enrich(systemData.details.disable),routine:await enrich(systemData.details.routine),reset:await enrich(systemData.details.reset)});const strikesWithDescriptions=systemData.actions,actorRollData=actor.getRollData();for(const attack of strikesWithDescriptions){const itemRollData=attack.item.getRollData();attack.description.length>0&&(attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})),attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}return{...sheetData,actions:this.#prepareActions(),editing:this.editing,actorTraits:systemData.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.hazardTraits)),rarity:CONFIG.PF2E.rarityTraits,rarityLabel:CONFIG.PF2E.rarityTraits[this.actor.rarity],brokenThreshold:systemData.attributes.hp.brokenThreshold,stealthDC,saves:this.#prepareSaves(),hasDefenses,hasHPDetails:!!systemData.attributes.hp.details.trim(),hasSaves:Object.keys(actor.saves??{}).length>0,hasIWR,hasStealth:stealthDC!==null||hasStealthDescription,hasStealthDescription,hasDescription:!!systemData.details.description?.trim(),hasDisable:!!systemData.details.disable?.trim(),hasRoutineDetails:!!systemData.details.routine?.trim(),hasResetDetails:!!systemData.details.reset?.trim()}}#prepareActions(){const actions=this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort);return{reaction:actions.filter(a=>a.actionCost?.type==="reaction"),action:actions.filter(a=>a.actionCost?.type!=="reaction")}}#prepareSaves(){if(!this.actor.saves)return[];const results=[];for(const saveType of SAVE_TYPES){const save=this.actor.saves[saveType];(this.editing||save)&&results.push({label:game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),type:saveType,mod:save?.check.mod})}return results}activateListeners($html){super.activateListeners($html);const html=$html[0],traitsEl=html.querySelector('input[name="system.traits.value"]');if(traitsEl){const tags=tagify(traitsEl,{whitelist:CONFIG.PF2E.hazardTraits}),traitsPrepend=html.querySelector(".traits-extra");traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}$html.find(".edit-mode-button").on("click",()=>{this.actor.setFlag("pf2e","editHazard.value",!this.editing)}),$html.find("input[data-property]").on("focus",event2=>{const $input=$(event2.target),propertyPath=$input.attr("data-property")??"",baseValue=Number(foundry.utils.getProperty(this.actor._source,propertyPath));$input.val(baseValue).attr({name:propertyPath})}),$html.find("input[data-property]").on("blur",event2=>{const $input=$(event2.target);$input.removeAttr("name").removeAttr("style").attr({type:"text"});const propertyPath=$input.attr("data-property")??"",valueAttr=$input.attr("data-value");if(valueAttr)$input.val(valueAttr);else{const preparedValue=Number(foundry.utils.getProperty(this.actor,propertyPath));$input.val(preparedValue!==null&&preparedValue>=0?`+${preparedValue}`:preparedValue)}}),$html.find("[data-action=edit-section]").on("click",event2=>{const name2=$(event2.target).closest(".section-container").find("[data-edit]").attr("data-edit");name2&&this.activateEditor(name2)}),this.options.editable&&$html.find(".isHazardEditable").on("change",event2=>{this.actor.setFlag("pf2e","editHazard",{value:event2.target.checked})})}async _updateObject(event2,formData){const emitsSound=formData["system.attributes.emitsSound"];return emitsSound!=="encounter"&&(formData["system.attributes.emitsSound"]=emitsSound==="true"),super._updateObject(event2,formData)}}class LootNPCsPopup extends FormApplication{static{__name(this,"LootNPCsPopup")}static{__name2(this,"LootNPCsPopup")}static get defaultOptions(){const options=super.defaultOptions;return options.id="loot-NPCs",options.classes=[],options.title="Loot NPCs",options.template="systems/pf2e/templates/actors/loot/loot-npcs-popup.hbs",options.width="auto",options}async getData(){const tokenInfo=(canvas.ready?canvas.tokens.controlled.filter(t=>t.actor&&t.actor.id!==this.object.id):[]).map(t=>({id:t.id,name:t.name,checked:t.actor?.hasPlayerOwner??!1}));return{...await super.getData(),tokenInfo}}async _updateObject(_event,formData){if(!canvas.ready)return;const lootActor=this.object,newItems=[],itemUpdates=new Map,itemsToDelete=new Map,selectionData=Array.isArray(formData.selection)?formData.selection:[formData.selection];for(let i=0;i<selectionData.length;i++){const token=canvas.tokens.placeables.find(token2=>token2.actor&&token2.id===this.form[i]?.id);if(!token)throw ErrorPF2e(`Token ${this.form[i]?.id} not found`);const currentSource=token.actor;if(selectionData[i]&¤tSource){for(const item of currentSource.inventory){const stackableItem=lootActor.inventory.findStackableItem(item);if(stackableItem){const currentQuantity=itemUpdates.get(stackableItem.id)??stackableItem.quantity;itemUpdates.set(stackableItem.id,currentQuantity+item.quantity);continue}newItems.push(item)}itemsToDelete.set(currentSource,currentSource.inventory.map(item=>item.id))}}if(newItems.length>0){const sources=newItems.reduce((result,item)=>{const stackableItem=result.find(i=>i.isStackableWith(item));return stackableItem?(stackableItem.updateSource({system:{quantity:stackableItem.quantity+item.quantity}}),result):(result.push(item),result)},[]).map(i=>i.toObject());await lootActor.createEmbeddedDocuments("Item",sources,{render:itemUpdates.size===0})}if(itemUpdates.size>0){const updates=[...itemUpdates.entries()].map(([id,quantity])=>({_id:id,system:{quantity}}));await lootActor.updateEmbeddedDocuments("Item",updates)}if(itemsToDelete.size>0)for(const[actor,ids]of itemsToDelete)actor.deleteEmbeddedDocuments("Item",ids)}}class DistributeCoinsPopup extends FormApplication{static{__name(this,"DistributeCoinsPopup")}static{__name2(this,"DistributeCoinsPopup")}constructor(actor,options={}){super(actor,options)}static get defaultOptions(){const options=super.defaultOptions;return options.id="distribute-coins",options.classes=[],options.title="Distribute Coins",options.template="systems/pf2e/templates/actors/distribute-coins.hbs",options.width="auto",options}async getData(options){const sheetData=await super.getData(options),playerActors=(options?.recipients??game.actors.contents).filter(a=>a.hasPlayerOwner&&a.isOfType("character")&&!a.isToken&&!a.system.traits.value.some(t=>["minion","eidolon"].includes(t)));return sheetData.actorInfo=playerActors.map(a=>({id:a.id,name:a.name,checked:game.users.players.some(u=>u.active&&u.character?.id===a.id)})),sheetData}async _updateObject(_event,formData){const thisActor=this.object,selectedActors=formData.actorIds.flatMap(actorId=>{const maybeActor=game.actors.get(actorId);return maybeActor?.isOfType("character")?maybeActor:[]}),playerCount=selectedActors.length;if(playerCount===0)return;const coinShare=new CoinsPF2e;if(formData.breakCoins){const thisActorCopperValue=thisActor.inventory.coins.copperValue,copperToDistribute=Math.trunc(thisActorCopperValue/playerCount);if(copperToDistribute===0){ui.notifications.warn("Nothing to distribute");return}thisActor.inventory.removeCoins({cp:copperToDistribute*playerCount}),coinShare.cp=copperToDistribute%10,coinShare.sp=Math.trunc(copperToDistribute/10)%10,coinShare.gp=Math.trunc(copperToDistribute/100)%10,coinShare.pp=Math.trunc(copperToDistribute/1e3)}else{const thisActorCurrency=thisActor.inventory.coins;if(coinShare.pp=Math.trunc(thisActorCurrency.pp/playerCount),coinShare.cp=Math.trunc(thisActorCurrency.cp/playerCount),coinShare.gp=Math.trunc(thisActorCurrency.gp/playerCount),coinShare.sp=Math.trunc(thisActorCurrency.sp/playerCount),coinShare.pp===0&&coinShare.gp===0&&coinShare.sp===0&&coinShare.cp===0){ui.notifications.warn("Nothing to distribute");return}const coinsToRemove=coinShare.scale(playerCount);thisActor.inventory.removeCoins(coinsToRemove,{byValue:!1})}let message="Distributed ";coinShare.pp!==0&&(message+=`${coinShare.pp} pp `),coinShare.gp!==0&&(message+=`${coinShare.gp} gp `),coinShare.sp!==0&&(message+=`${coinShare.sp} sp `),coinShare.cp!==0&&(message+=`${coinShare.cp} cp `);const each=playerCount>1?"each ":"";message+=`${each}from ${thisActor.name} to `;for(const actor of selectedActors){await actor.inventory.addCoins(coinShare);const index=selectedActors.indexOf(actor);index===0?message+=`${actor.name}`:index<playerCount-1?message+=`, ${actor.name}`:message+=` and ${actor.name}.`}ChatMessagePF2e.create({user:game.user.id,type:CONST.CHAT_MESSAGE_TYPES.OTHER,content:message})}async _onSubmit(event2,options={}){const actorIds=Array.from(this.form.elements).flatMap(element=>element instanceof HTMLInputElement&&element.name==="actorIds"&&element.checked?element.value:[]);return options.updateData=foundry.utils.mergeObject(options.updateData??{},{actorIds}),super._onSubmit(event2,options)}}class LootSheetPF2e extends ActorSheetPF2e{static{__name(this,"LootSheetPF2e")}static{__name2(this,"LootSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,editable:!0,classes:[...options.classes,"loot"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"inventory"}]}}get template(){return"systems/pf2e/templates/actors/loot/sheet.hbs"}get isLootSheet(){return!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(){const sheetData=await super.getData(),isLoot=this.actor.system.lootSheetType==="Loot",rollData=this.actor.getRollData();return sheetData.enrichedContent.description=await TextEditor.enrichHTML(sheetData.data.details.description,{rollData,async:!0}),{...sheetData,isLoot}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];htmlQuery(html,"[data-sidebar-buttons]")?.addEventListener("click",event2=>{const button=htmlClosest(event2.target,"button[data-action]");button?.dataset.action==="split-coins"?new DistributeCoinsPopup(this.actor).render(!0):button?.dataset.action==="loot-npcs"&&(canvas.tokens.controlled.some(token=>token.actor?.id!==this.actor.id)?new LootNPCsPopup(this.actor).render(!0):ui.notifications.warn("No tokens selected."))})}async _onDropItem(event2,itemData){return this.actor.id===itemData.actorId&&!this.actor.testUserPermission(game.user,"OWNER")?[]:super._onDropItem(event2,itemData)}}class NPCSkillsEditor extends DocumentSheet{static{__name(this,"NPCSkillsEditor")}static{__name2(this,"NPCSkillsEditor")}get actor(){return this.object}static get defaultOptions(){return{...super.defaultOptions,classes:["pf2e","npc-skills-editor"],template:"systems/pf2e/templates/actors/npc/skills-editor.hbs",height:"auto",scrollY:[".scroll-container"],sheetConfig:!1,submitOnChange:!1,submitOnClose:!1,width:"400"}}get title(){return game.i18n.format("PF2E.Actor.NPC.SkillsEditor.Title",{actor:this.actor.name})}async getData(options){const allSkills=Object.values(this.actor.system.skills);return{...await super.getData(options),actor:this.actor,trainedSkills:allSkills.filter(s=>s.visible).sort((a,b)=>a.label.localeCompare(b.label)),untrainedSkills:allSkills.filter(s=>!s.visible).sort((a,b)=>a.label.localeCompare(b.label))}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=add-skill]")?.addEventListener("click",async event2=>{const slug=htmlQuery(htmlClosest(event2.currentTarget,".skill-selector"),"select")?.value;setHasElement(SKILL_LONG_FORMS,slug)&&await this.actor.createEmbeddedDocuments("Item",[{name:slug.titleCase(),type:"lore"}])}),htmlQuery(html,"button[data-action=add-lore]")?.addEventListener("click",async event2=>{const loreName=htmlQuery(htmlClosest(event2.currentTarget,".lore-skill-creator"),"input")?.value.trim();if(loreName){const data={name:loreName,type:"lore",system:{mod:{value:0}}};await this.actor.createEmbeddedDocuments("Item",[data])}});for(const input of htmlQueryAll(html,"input[data-modifier]"))input.addEventListener("change",async()=>{const modifier=Math.clamped(Math.trunc(Number(input.value)||0),-999,999);if(Number.isInteger(modifier)){const itemId=htmlClosest(input,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).update({"system.mod.value":modifier})}}),input.addEventListener("focus",()=>{input.select()});for(const anchor of htmlQueryAll(html,"a[data-action=edit-skill]"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId,{strict:!0}).sheet.render(!0)});for(const anchor of htmlQueryAll(html,"a[data-action=remove-skill]"))anchor.addEventListener("click",async()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).delete()})}async _render(force,options){const focusedElement=htmlQuery(this.form,"input:focus, select:focus");if(await super._render(force,options),focusedElement){const selector=["input","select"].map(s=>`${s}#${CSS.escape(focusedElement.id)}`).join(","),newInput=htmlQuery(this.form,selector);window.setTimeout(()=>{newInput?.focus()},0)}}}class RecallKnowledgePopup extends Application{static{__name(this,"RecallKnowledgePopup")}static{__name2(this,"RecallKnowledgePopup")}#identificationData;constructor(options,data){super(options),this.#identificationData=data}static get defaultOptions(){return{...super.defaultOptions,id:"recall-knowledge-breakdown",classes:[],title:game.i18n.localize("PF2E.RecallKnowledge.BreakdownTitle"),template:"systems/pf2e/templates/actors/recall-knowledge.hbs",width:630}}async getData(){const identificationData=this.#identificationData;return{standard:{label:localizeList(identificationData.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))),attempts:this.#padAttempts(identificationData.standard.progression)},loreEasy:this.#padAttempts(identificationData.lore[0].progression),loreVeryEasy:this.#padAttempts(identificationData.lore[1].progression)}}#padAttempts(attempts){return padArray(attempts.map(attempt=>attempt.toString()),6,"-")}}class NPCConfig extends CreatureConfig{static{__name(this,"NPCConfig")}static{__name2(this,"NPCConfig")}async getData(options={}){const lootableOptions={default:`PF2E.Actor.NPC.Configure.Lootable.${game.settings.get("pf2e","automation.lootableNPCs")?"DefaultLootable":"DefaultNotLootable"}`,lootable:"PF2E.Actor.NPC.Configure.Lootable.Lootable",notLootable:"PF2E.Actor.NPC.Configure.Lootable.NotLootable"},lootableSelection=(()=>{const storedSelection=this.actor._source.flags.pf2e?.lootable;return typeof storedSelection=="boolean"?storedSelection?"lootable":"notLootable":"default"})();return{...await super.getData(options),lootable:createSheetOptions(lootableOptions,{value:[lootableSelection]})}}async _updateObject(event2,formData){const key="flags.pf2e.lootable",lootable=formData[key];return lootable==="default"?(delete formData[key],formData["flags.pf2e.-=lootable"]=null):formData[key]=lootable==="lootable",super._updateObject(event2,formData)}}class AbstractNPCSheet extends CreatureSheetPF2e{static{__name(this,"AbstractNPCSheet")}static{__name2(this,"AbstractNPCSheet")}actorConfigClass=NPCConfig;static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"pf2e","npc","simple"],scrollY:[".sidebar",".inventory-list"]}}async prepareItems(sheetData){this.#prepareAbilities(sheetData.data.abilities),this.#prepareSkills(sheetData.data),this.#prepareSaves(sheetData.data)}async getData(options){const sheetData=await super.getData(options),rollData=this.actor.getRollData();return sheetData.enrichedContent.publicNotes=await TextEditor.enrichHTML(sheetData.data.details.publicNotes,{rollData,secrets:this.actor.isOwner,async:!0}),sheetData.enrichedContent.privateNotes=await TextEditor.enrichHTML(sheetData.data.details.privateNotes,{rollData,async:!0}),sheetData.traitTagifyData=createTagifyTraits(this.actor.system.traits.value,{sourceTraits:this.actor._source.system.traits.value,record:CONFIG.PF2E.creatureTraits}),sheetData}#prepareAbilities(attributes){for(const key of ATTRIBUTE_ABBREVIATIONS){const data=attributes[key],localizedCode=game.i18n.localize(`PF2E.AbilityId.${key}`),nameKey=CONFIG.PF2E.abilities[key],localizedName=game.i18n.localize(nameKey);data.localizedCode=localizedCode,data.localizedName=localizedName}}#prepareSkills(sheetSystemData){const sortedSkillsIds=Object.keys(sheetSystemData.skills),skills=sheetSystemData.skills;for(const shortForm of sortedSkillsIds){const skill=skills[shortForm];skill.adjustedHigher=skill.value>Number(skill.base),skill.adjustedLower=skill.value<Number(skill.base)}sortedSkillsIds.sort((a,b)=>{const skillA=skills[a],skillB=skills[b];return skillA.label<skillB.label?-1:skillA.label>skillB.label?1:0});const sortedSkills={};for(const skillId of sortedSkillsIds)sortedSkills[skillId]=skills[skillId];sheetSystemData.sortedSkills=sortedSkills}#prepareSaves(systemData){for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType];save.labelShort=game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),save.adjustedHigher=save.totalModifier>Number(save.base),save.adjustedLower=save.totalModifier<Number(save.base)}}_canUserView(user){return super._canUserView(user)||this.isLootSheet}activateListeners($html){super.activateListeners($html);const html=$html[0],traitsEl=htmlQuery(html,'input[name="system.traits.value"]');tagify(traitsEl,{whitelist:CONFIG.PF2E.creatureTraits});const rollables=["a.rollable",".item-icon.rollable"].join(", ");for(const rollable of htmlQueryAll(html,rollables))rollable.addEventListener("click",event2=>{this.#onClickRollable(rollable,event2)});this.isEditable&&htmlQuery(html,".skills-edit")?.addEventListener("click",()=>{new NPCSkillsEditor(this.actor).render(!0)})}async#onClickRollable(link,event2){const{attribute,save,skill}=link?.parentElement?.dataset??{},rollParams=eventToRollParams(event2,{type:"check"});if(attribute)attribute==="perception"?await this.actor.perception.roll(eventToRollParams(event2,{type:"check"})):setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)&&this.#rollAbility(event2,attribute);else if(skill){const extraRollOptions=link.dataset.options?.split(",").map(o=>o.trim()).filter(o=>!!o),key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill;await this.actor.skills[key]?.check.roll({...rollParams,extraRollOptions})}else objectHasKey(this.actor.saves,save)&&await this.actor.saves[save].check.roll(rollParams)}async#rollAbility(event2,abilityId){const bonus=this.actor.system.abilities[abilityId].mod,parts=["@bonus"],title=game.i18n.localize(`PF2E.AbilityCheck.${abilityId}`),data={bonus},speaker=ChatMessage.getSpeaker({token:this.token,actor:this.actor});await DicePF2e.d20Roll({event:event2,parts,data,title,speaker})}}class NPCSheetPF2e extends AbstractNPCSheet{static{__name(this,"NPCSheetPF2e")}static{__name2(this,"NPCSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,width:650,height:680,tabs:[{navSelector:".sheet-tabs",contentSelector:".sheet-body",initial:"main"}],scrollY:[...options.scrollY,".tab.main",".tab.inventory",".tab.spells",".tab.effects",".tab.notes"]}}get template(){return this.isLootSheet?"systems/pf2e/templates/actors/npc/loot-sheet.hbs":this.actor.limited?"systems/pf2e/templates/actors/limited/npc-sheet.hbs":"systems/pf2e/templates/actors/npc/sheet.hbs"}get title(){if(this.isLootSheet||this.actor.limited){const actorName=!game.pf2e.settings.tokens.nameVisibility||!this.token||this.token.playersCanSeeName?this.token?.name??this.actor.name:"";return this.actor.isDead?`${actorName} [${game.i18n.localize("PF2E.NPC.Dead")}]`:actorName}return super.title}get isLootSheet(){return this.actor.isLootable&&!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(options){const sheetData=await super.getData(options);(this.actor.limited||this.isLootSheet)&&(sheetData.actor.name=this.actor.token?.name??sheetData.actor.name),sheetData.identificationDCs=(()=>{const data=this.actor.identificationDCs,skills=data.skills.length>0?localizeList(data.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))):null;return{standard:skills?game.i18n.format("PF2E.Actor.NPC.Identification.Skills.Label",{skills,dc:data.standard.dc,adjustment:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.standard.start])}):null,lore:game.i18n.format("PF2E.Actor.NPC.Identification.Lore.Label",{dc1:data.lore[0].dc,adjustment1:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[0].start]),dc2:data.lore[1].dc,adjustment2:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[1].start])})}})();const{heldShield}=this.actor,actorShieldData=sheetData.data.attributes.shield;sheetData.hasShield=!!heldShield||actorShieldData.hp.max>0;const isElite=this.actor.isElite,isWeak=this.actor.isWeak;sheetData.isElite=isElite,sheetData.isWeak=isWeak,sheetData.notAdjusted=!isElite&&!isWeak,isElite?(sheetData.eliteState="active",sheetData.weakState="inactive"):isWeak?(sheetData.eliteState="inactive",sheetData.weakState="active"):(sheetData.eliteState="inactive",sheetData.weakState="inactive"),this.isLootSheet&&(sheetData.actor.name=this.token?.name??this.actor.name);const{level}=sheetData.data.details;level.adjustedHigher=level.value>Number(level.base),level.adjustedLower=level.value<Number(level.base);const{ac,hp,perception,hardness}=sheetData.data.attributes,speedData=sheetData.data.attributes.speed,sourceAttributes=this.actor._source.system.attributes;return ac.adjustedHigher=ac.value>sourceAttributes.ac.value,ac.adjustedLower=ac.value<sourceAttributes.ac.value,hp.adjustedHigher=hp.max>sourceAttributes.hp.max,hp.adjustedLower=hp.max<sourceAttributes.hp.max,perception.adjustedHigher=perception.totalModifier>sourceAttributes.perception.value,perception.adjustedLower=perception.totalModifier<sourceAttributes.perception.value,sheetData.speeds={land:{label:speedData.label??"",value:speedData.total,details:speedData.details,adjustedHigher:speedData.total>speedData.value,adjustedLower:speedData.total<speedData.value},...MOVEMENT_TYPES.filter(t=>t!=="land").reduce((speeds,type)=>{const speed=speedData.otherSpeeds.find(s=>s.type===type);return{...speeds,[type]:speed?{label:speed.label,value:speed.total,adjustedHigher:typeof speed.total=="number"&&speed.total>speed.value,adjustedLower:typeof speed.total=="number"&&speed.total<speed.value}:null}},{})},sheetData.hasHardness=this.actor.traits.has("construct")||(Number(hardness?.value)||0)>0,sheetData.configLootableNpc=game.settings.get("pf2e","automation.lootableNPCs"),sheetData.languageDetails=this.actor.system.traits.languages.custom.trim(),sheetData}async prepareItems(sheetData){super.prepareItems(sheetData),await this.#prepareActions(sheetData),sheetData.spellcastingEntries=await this.prepareSpellcasting()}async prepareSpellcasting(){const entries=await super.prepareSpellcasting();for(const entry of entries){const entryItem=this.actor.items.get(entry.id);entryItem?.isOfType("spellcastingEntry")&&(entry.adjustedHigher=entry.statistic?{dc:entry.statistic.dc.value>entryItem._source.system.spelldc.dc,mod:entry.statistic.check.mod>entryItem._source.system.spelldc.value}:{dc:!1,mod:!1},entry.adjustedLower=entry.statistic?{dc:entry.statistic.dc.value<entryItem._source.system.spelldc.dc,mod:entry.statistic.check.mod<entryItem._source.system.spelldc.value}:{dc:!1,mod:!1})}return entries}async#prepareActions(sheetData){const attacks=sheetData.data.actions,actorRollData=this.actor.getRollData();for(const attack of attacks){if(attack.description.length>0){const itemRollData=attack.item.getRollData();attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})}attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}const actions={passive:{label:game.i18n.localize("PF2E.ActionTypePassive"),actions:[]},active:{label:game.i18n.localize("PF2E.ActionTypeAction"),actions:[]}},baseOrder=["free","reaction","action"],abilities2=sortBy(this.actor.itemTypes.action,a=>a.sort,a=>baseOrder.indexOf(a.actionCost?.type??"action"));for(const item of abilities2){const itemData=item.toObject(!1),chatData=await item.getChatData(),traits=chatData.traits??[],actionGroup=item.actionCost?"active":"passive",hasAura=actionGroup==="passive"&&(item.system.traits.value.includes("aura")||!!item.system.rules.find(r=>r.key==="Aura"));actions[actionGroup].actions.push({...itemData,glyph:getActionGlyph(item.actionCost),imageUrl:getActionIcon(item.actionCost),chatData,traits,hasAura})}sheetData.actions=actions}activateListeners($html){super.activateListeners($html);const html=$html[0],mainPanel=htmlQuery(html,".tab[data-tab=main]");if(mainPanel&&htmlQuery(mainPanel,".recall-knowledge button.breakdown")?.addEventListener("click",()=>{new RecallKnowledgePopup({},this.actor.identificationDCs).render(!0)}),!this.isEditable)return;for(const anchor of htmlQueryAll(html,"a[data-adjustment]"))anchor.addEventListener("click",()=>{const adjustment=anchor.dataset.adjustment;if(adjustment==="elite"||adjustment==="weak"){const alreadyHasAdjustment=adjustment===this.actor.system.attributes.adjustment;this.actor.applyAdjustment(alreadyHasAdjustment?null:adjustment)}});const selector=[".attack-input",".dc-input",".key-attribute select"].map(s=>`.spellcasting-entry ${s}`).join(", ");for(const element of htmlQueryAll(html,selector))element.addEventListener("change",event2=>this.#onChangeSpellcastingEntry(element,event2))}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers["generate-attack"]=async event2=>{const{actor}=this,itemId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId??"",item=actor.items.get(itemId,{strict:!0});if(!item.isOfType("weapon"))return;const existing=actor.itemTypes.melee.filter(m=>m.flags.pf2e.linkedWeapon===itemId).map(m=>m.id);if(existing.length>0)if(await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Title"),content:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Content"),defaultYes:!1}))await actor.deleteEmbeddedDocuments("Item",existing,{render:!1});else return;const attacks=item.toNPCAttacks().map(a=>a.toObject());await actor.createEmbeddedDocuments("Item",attacks),ui.notifications.info(game.i18n.format("PF2E.Actor.NPC.GenerateAttack.Notification",{attack:attacks.at(0)?.name??""}))},handlers}async#onChangeSpellcastingEntry(element,event2){event2.preventDefault();const itemId=htmlClosest(element,".spellcasting-entry")?.dataset.containerId??"",key=element.dataset.baseProperty?.replace(/data\.items\.\d+\./,"")??"",value=element.classList.contains("focus-points")||element.classList.contains("focus-pool")?Math.min(Number(element.value)||0,3):element.nodeName==="SELECT"?element.value:Number(element.value)||0;await this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[key]:value}])}async _updateObject(event2,formData){if(this.actor.isElite||this.actor.isWeak){const{max}=this.actor.system.attributes.hp;formData["system.attributes.hp.max"]===max&&delete formData["system.attributes.hp.max"]}const shield=this.actor.heldShield;return shield&&Number.isInteger(formData["system.attributes.shield.value"])&&await shield.update({"system.hp.value":formData["system.attributes.shield.value"]}),super._updateObject(event2,formData)}}class SimpleNPCSheet extends AbstractNPCSheet{static{__name(this,"SimpleNPCSheet")}static{__name2(this,"SimpleNPCSheet")}static get defaultOptions(){return{...super.defaultOptions,width:650,height:420,scrollY:[".sheet-body"],template:"systems/pf2e/templates/actors/npc/simple-sheet.hbs"}}}class PartySheetPF2e extends ActorSheetPF2e{static{__name(this,"PartySheetPF2e")}static{__name2(this,"PartySheetPF2e")}currentSummaryView="languages";static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"party"],width:720,height:720,template:"systems/pf2e/templates/actors/party/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}regionTemplates={overview:"overview.hbs",inventoryMembers:"inventory-members.hbs",exploration:"exploration.hbs",explorationSidebar:"exploration-sidebar.hbs"};get isLootSheet(){return this.actor.canUserModify(game.user,"update")}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{tab:this._tabs[0].active}})}}),buttons}async getData(options){const base=await super.getData(options),members=this.actor.members,canDistributeCoins=game.user.isGM&&this.isEditable?{enabled:this.actor.inventory.coins.copperValue>0&&members.some(isReallyPC)}:null;return{...base,playerRestricted:!game.settings.get("pf2e","metagame_showPartyStats"),restricted:!(game.user.isGM||game.settings.get("pf2e","metagame_showPartyStats")),members:this.#prepareMembers(),overviewSummary:this.#prepareOverviewSummary(),inventorySummary:{totalCoins:sumBy(members,actor=>actor.inventory.coins.goldValue??0)+this.actor.inventory.coins.goldValue,totalWealth:sumBy(members,actor=>actor.inventory.totalWealth.goldValue??0)+this.actor.inventory.totalWealth.goldValue,totalBulk:members.map(actor=>actor.inventory.bulk.value).reduce((a,b)=>a.plus(b),this.actor.inventory.bulk.value)},canDistributeCoins,explorationSummary:{speed:this.actor.system.attributes.speed.total,activities:Object.entries(CONFIG.PF2E.hexplorationActivities).find(([max])=>Number(max)>=this.actor.system.attributes.speed.total)?.[1]??0},orphaned:this.actor.items.filter(i=>!i.isOfType(...this.actor.allowedItemTypes))}}#prepareMembers(){function sanitizeSense(label){return label.replace(/\((imprecise|precise)\)/gi,"").replace(/\d+/g,"").replaceAll("feet","").trim()}return __name(sanitizeSense,"sanitizeSense"),__name2(sanitizeSense,"sanitizeSense"),this.actor.members.map(actor=>{const observer=actor.testUserPermission(game.user,"OBSERVER"),restricted=!(game.settings.get("pf2e","metagame_showPartyStats")||observer),genderPronouns=actor.isOfType("character")&&actor.system.details.gender.value.trim()||null,blurb=actor.isOfType("character")&&actor.ancestry&&actor.class?game.i18n.format("PF2E.Actor.Character.Blurb",{level:actor.level,ancestry:actor.ancestry.name,class:actor.class.name}):actor.isOfType("familiar")&&actor.master?game.i18n.format("PF2E.Actor.Familiar.Blurb",{master:actor.master.name}):actor.isOfType("npc")&&actor.system.details.blurb.trim()||null,heroPoints=actor.isOfType("character")&&isReallyPC(actor)?actor.system.resources.heroPoints:null,activities=actor.isOfType("character")?compact(actor.system.exploration.map(id=>actor.items.get(id))):[];return{actor,hasBulk:actor.inventory.bulk.encumberedAfter!==1/0,bestSkills:Object.values(actor.skills??{}).filter(s=>!!s?.proficient&&!s.lore).sort((a,b)=>(b.mod??0)-(a.mod??0)).slice(0,4).map(s=>({slug:s.slug,mod:s.mod,label:s.label,rank:s.rank})),genderPronouns,blurb,heroPoints,owner:actor.isOwner,observer,limited:observer||actor.limited,speeds:[{label:"PF2E.Speed",value:actor.attributes.speed.value},...actor.attributes.speed.otherSpeeds.map(s=>({label:s.label,value:s.value}))],senses:(()=>{const rawSenses=actor.system.traits.senses??[];if(!Array.isArray(rawSenses))return rawSenses.value.split(",").filter(s=>!!s.trim()).map(l=>({labelFull:l.trim(),label:sanitizeSense(l)}));const senseTypes=new Set(rawSenses.map(s=>s.type));return(senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision"))&&senseTypes.delete("lowLightVision"),senseTypes.has("greaterDarkvision")&&senseTypes.delete("darkvision"),rawSenses.filter(r=>senseTypes.has(r.type)).map(r=>({acuity:r.acuity,labelFull:r.label??"",label:CONFIG.PF2E.senses[r.type]??r.type}))})(),hp:actor.hitPoints,activities:activities.map(action2=>({uuid:action2.uuid,name:action2.name,img:action2.img,traits:createSheetTags(CONFIG.PF2E.actionTraits,action2.system.traits?.value??[])})),restricted}})}#prepareOverviewSummary(){const members=this.actor.members;if(!members.length)return null;const allLanguages=new Set(members.flatMap(m=>m.system.traits.languages?.value??[])),baseKnowledgeSkills=["arcana","nature","occultism","religion","crafting","society","medicine"],loreSkills=new Set(members.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>s.slug));function getBestSkill(slug){const statistic=maxBy(members,m=>m.skills[slug]?.mod??-1/0)?.skills[slug];return statistic?pick(statistic,["slug","mod","label","rank"]):null}return __name(getBestSkill,"getBestSkill"),__name2(getBestSkill,"getBestSkill"),{languages:sortBy([...allLanguages].map(slug=>({slug,label:game.i18n.localize(CONFIG.PF2E.languages[slug]),actors:this.#getActorsThatUnderstand(slug)})),l=>l.label),skills:sortBy(Array.from(SKILL_LONG_FORMS).map(slug=>{const best=getBestSkill(slug),label=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return best??{mod:0,label,slug,rank:0}}),s=>s.label),knowledge:{regular:compact(baseKnowledgeSkills.map(getBestSkill)),lore:sortBy(compact([...loreSkills].map(getBestSkill)),s=>s.label)}}}#getActorsThatUnderstand(slug){return this.actor.members.filter(m=>!!m?.system.traits.languages?.value.includes(slug))}setSummaryView(view){const summary=htmlQuery(this.element[0],"[data-tab=overview] .summary");if(!summary)return;const viewElements=htmlQueryAll(summary,"[data-view]:not([data-action=change-view])");for(const element of viewElements)element.hidden=view!==element.dataset.view;for(const button of htmlQueryAll(summary,"[data-action=change-view]"))button.classList.toggle("active",button.dataset.view===view);this.currentSummaryView=view}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"a[data-action=open-meta-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.metagame");if(menu){const options={highlightSetting:"showPartyStats"};new menu.type(void 0,options).render(!0)}});for(const rollLink of htmlQueryAll(html,"[data-action=roll]")){const actorUUID=htmlClosest(rollLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");actor instanceof ActorPF2e&&rollLink.addEventListener("click",event2=>{const rollMode=rollLink.dataset.secret?game.user.isGM?"gmroll":"blindroll":void 0;actor.getStatistic(rollLink.dataset.statistic??"")?.roll({...eventToRollParams(event2,{type:"check"}),rollMode})})}for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const tab=openSheetLink.dataset.tab,actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",async()=>actor?.sheet.render(!0,{tab}))}this.setSummaryView(this.currentSummaryView);for(const button of htmlQueryAll(html,"[data-action=change-view]"))button.addEventListener("click",()=>{this.setSummaryView(button.dataset.view??"languages")});for(const memberElem of htmlQueryAll(html,"[data-actor-uuid]")){const actorUUID=memberElem.dataset.actorUuid,actor=this.document.members.find(m=>m.uuid===actorUUID);if(game.user.isGM&&htmlQuery(memberElem,"a[data-action=remove-member]")?.addEventListener("click",async event2=>{(event2.ctrlKey?!0:await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Title"),content:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Content")}))&&actor&&this.document.removeMembers(actor)}),actor?.isOfType("character")&&actor.canUserModify(game.user,"update")){const heroPointsPips=htmlQuery(memberElem,"a[data-action=adjust-hero-points]"),{heroPoints}=actor;heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(heroPoints.value+1,heroPoints.max);await actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(heroPoints.value-1,0);await actor.update({"system.resources.heroPoints.value":newValue})})}}for(const languageTag of htmlQueryAll(html,"[data-language]")){const slug=languageTag.dataset.language,members=this.#getActorsThatUnderstand(slug).map(m=>m.name).join(", "),titleLabel=game.i18n.localize("PF2E.Actor.Party.MembersLabel"),title=createHTMLElement("strong",{children:[titleLabel]}),content=createHTMLElement("span",{children:[title,members]});$(languageTag).tooltipster({content})}for(const skillTag of htmlQueryAll(html,".summary .skills [data-slug]")){const slug=skillTag.dataset.slug??"",statistics=compact(this.actor.members.map(m=>m.skills[slug])),labels=sortBy(statistics,s=>s.mod).map(statistic=>{const rank=statistic.rank??(statistic.proficient?1:0),prof=game.i18n.localize(CONFIG.PF2E.proficiencyLevels[rank]),label=`${statistic.actor.name} (${prof}) ${signedInteger(statistic.mod)}`,row=createHTMLElement("div",{children:[label]});return row.style.textAlign="right",row}),content=createHTMLElement("div",{children:labels});$(skillTag).tooltipster({content})}for(const activityElem of htmlQueryAll(html,".activity[data-activity-uuid]")){const document2=fromUuidSync(activityElem.dataset.activityUuid??"");if(!(document2 instanceof ItemPF2e))continue;const rollData=document2.getRollData();(async()=>{const content=createHTMLElement("div",{classes:["item-summary"],innerHTML:await TextEditor.enrichHTML(document2.description,{async:!0,rollData})});InlineRollLinks.listen(content,document2),$(activityElem).tooltipster({contentAsHTML:!0,content,interactive:!0,maxWidth:500,side:"right",theme:"crb-hover"})})()}htmlQuery(html,"button[data-action=distribute-coins]")?.addEventListener("click",()=>{new DistributeCoinsPopup(this.actor,{recipients:this.actor.members}).render(!0)}),htmlQuery(html,"[data-action=clear-exploration]")?.addEventListener("click",async()=>{await Promise.all(this.actor.members.map(m=>m.update({"system.exploration":[]}))),ui.notifications.info("PF2E.Actor.Party.ClearActivities.Complete",{localize:!0})}),htmlQuery(html,"[data-action=rest]")?.addEventListener("click",event2=>{game.pf2e.actions.restForTheNight({event:event2,actors:this.actor.members})}),htmlQuery(html,"[data-action=prompt]")?.addEventListener("click",()=>{game.pf2e.gm.checkPrompt({actors:this.actor.members})})}async _onDropItemCreate(itemData){const toTest=Array.isArray(itemData)?itemData:[itemData],supported=[...PHYSICAL_ITEM_TYPES,...this.actor.baseAllowedItemTypes],invalid=toTest.filter(i=>!supported.includes(i.type));if(invalid.length){for(const source of invalid){const type=game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase());ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type}))}return[]}return super._onDropItemCreate(itemData)}async _onDropItem(event2,data){const droppedRegion=event2.target?.closest("[data-region]")?.dataset.region,targetActor=event2.target?.closest("[data-actor-uuid]")?.dataset.actorUuid;if(droppedRegion==="inventoryMembers"&&targetActor){const item=await ItemPF2e.fromDropData(data);if(!item)return[];const actorUuid=foundry.utils.parseUuid(targetActor).documentId;if(actorUuid&&item.actor&&item.isOfType("physical"))return await this.moveItemBetweenActors(event2,item.actor.id,item.actor.token?.id??null,actorUuid,null,item.id),[item]}return super._onDropItem(event2,data)}_disableFields(_form){}async#renderRegions(element,data){for(const region of htmlQueryAll(element,"[data-region]")){const regionId=region.dataset.region??"",templateName=this.regionTemplates[regionId];if(!templateName)continue;const template=`systems/pf2e/templates/actors/party/regions/${templateName}`,result=await renderTemplate(template,data);region.innerHTML=result,this._state!==Application.RENDER_STATES.RENDERING&&this.activateListeners($(region)),await this.#renderRegions(region,data)}}async render(force,options){if(options?.actors){const data=await this.getData();return this._saveScrollPositions(this.element),await this.#renderRegions(this.element[0],data),this._restoreScrollPositions(this.element),this}else return super.render(force,options)}async _renderInner(data,options){const result=await super._renderInner(data,options);return await this.#renderRegions(result[0],data),result}async _onDropActor(event2,data){await super._onDropActor(event2,data);const actor=fromUuidSync(data.uuid);actor instanceof CreaturePF2e&&this.document.addMembers(actor)}}class VehicleSheetPF2e extends ActorSheetPF2e{static{__name(this,"VehicleSheetPF2e")}static{__name2(this,"VehicleSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"vehicle"],width:670,height:480,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"details"}],template:"systems/pf2e/templates/actors/vehicle/sheet.hbs"}}async getData(){const sheetData=await super.getData(),actions={action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}};for(const item of this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort)){const itemData=item.toObject(!1),{actionCost,frequency}=item,actionType=actionCost?.type??"free",img=(()=>{const actionIcon=getActionIcon(item.actionCost),defaultIcon=ItemPF2e.getDefaultArtwork(item._source).img;return item.isOfType("action")&&![actionIcon,defaultIcon].includes(item.img)?item.img:item.system.selfEffect?.img??actionIcon})();actions[actionType].actions.push({...itemData,id:item.id,img,actionCost,glyph:actionCost?getActionGlyph(actionCost):null,frequency,hasEffect:!!item.system.selfEffect})}return{...sheetData,actions,actorSizes:CONFIG.PF2E.actorSizes,actorSize:CONFIG.PF2E.actorSizes[this.actor.size],actorRarities:CONFIG.PF2E.rarityTraits,actorRarity:CONFIG.PF2E.rarityTraits[this.actor.system.traits.rarity],ac:getAdjustedValue(this.actor.attributes.ac.value,this.actor._source.system.attributes.ac.value),saves:{fortitude:getAdjustedValue(this.actor.saves.fortitude.mod,this.actor._source.system.saves.fortitude.value)}}}activateListeners($html){super.activateListeners($html);const html=$html[0],titleElem=htmlQuery(html,"nav > .panel-title");if(!titleElem)throw ErrorPF2e("Unexpected missing DOM element");const initialTitle=htmlQuery(html,".sheet-navigation .active")?.title;initialTitle&&(titleElem.title=initialTitle);for(const element of htmlQueryAll(html,".sheet-navigation .item"))element.addEventListener("mouseover",()=>{titleElem.textContent=element.title}),element.addEventListener("mouseout",()=>{const parent=htmlClosest(element,".sheet-navigation"),title=htmlQuery(parent,".item.active")?.title;title&&(titleElem.textContent=title)})}}class AbilitySheetPF2e extends ItemSheetPF2e{static{__name(this,"AbilitySheetPF2e")}static{__name2(this,"AbilitySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}],hasSidebar:!0}}async getData(options={}){const sheetData=await super.getData(options);return{...sheetData,categories:CONFIG.PF2E.actionCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,actionTraits:CONFIG.PF2E.actionTraits,frequencies:CONFIG.PF2E.frequencies,skills:CONFIG.PF2E.skillList,proficiencies:CONFIG.PF2E.proficiencyLevels,selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];activateActionSheetListeners(this.item,html)}async _onDrop(event2){return handleSelfEffectDrop(this,event2)}}class AfflictionSheetPF2e extends ItemSheetPF2e{static{__name(this,"AfflictionSheetPF2e")}static{__name2(this,"AfflictionSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:"[data-stage-id]"}],hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),definingTraits=["disease","poison","curse"],traits=new Set(this.item.system.traits.value),definingTrait=definingTraits.find(t=>traits.has(t));return{...sheetData,itemType:game.i18n.localize(definingTrait?CONFIG.PF2E.actionTraits[definingTrait]:"PF2E.LevelLabel"),conditionTypes:omit(CONFIG.PF2E.conditionTypes,["persistent-damage"]),damageTypes:CONFIG.PF2E.damageTypes,damageCategories:pick(CONFIG.PF2E.damageCategories,["precision","persistent","splash"]),durationUnits:omit(CONFIG.PF2E.timeUnits,["encounter"]),onsetUnits:omit(CONFIG.PF2E.timeUnits,["encounter","unlimited"]),saves:CONFIG.PF2E.saves,stages:await this.prepareStages()}}async prepareStages(){const stages={};for(const[idx,[id,stage]]of Object.entries(Object.entries(this.item.system.stages))){const conditions=Object.entries(stage.conditions).reduce((result,[key,data])=>{const document2=ConditionManager.getCondition(data.slug);return result[key]={...data,document:document2},result},{}),effectDocuments=await UUIDUtils.fromUUIDs(stage.effects.map(e=>e.uuid)),effects=stage.effects.map(effect=>{const document2=effectDocuments.find(d=>d.uuid===effect.uuid);return document2 instanceof ItemPF2e?{...effect,name:document2.name,img:document2.img}:effect});stages[id]={...stage,stage:Number(idx)+1,conditions,effects}}return stages}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=onset-add]")?.addEventListener("click",()=>{const onset={value:1,unit:"minutes",active:!0};this.item.update({system:{onset}})}),htmlQuery(html,"[data-action=onset-delete]")?.addEventListener("click",()=>{this.item.update({system:{"-=onset":null}})}),htmlQuery(html,"[data-action=stage-add]")?.addEventListener("click",()=>{const stage={damage:{},conditions:{},effects:[],duration:{value:-1,unit:"unlimited"}};this.item.update({system:{stages:{[foundry.utils.randomID()]:stage}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=stage-delete]"))deleteIcon.addEventListener("click",event2=>{const deleteId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;deleteId&&this.item.update({[`system.stages.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=damage-create]")??[])addIcon?.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const damage={formula:"",type:"untyped"};this.item.update({[`system.stages.${stageId}.damage.${foundry.utils.randomID()}`]:damage})});for(const deleteIcon of htmlQueryAll(html,"[data-action=damage-delete"))deleteIcon.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const deleteId=htmlClosest(event2.target,"[data-id]")?.dataset.id;this.item.update({[`system.stages.${stageId}.damage.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=condition-create")??[])addIcon?.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const newCondition={slug:"frightened",value:1};this.item.update({[`system.stages.${stageId}.conditions.${foundry.utils.randomID()}`]:newCondition})});for(const conditionEl of htmlQueryAll(html,".stage-condition[data-condition-id]")){const stageId=htmlClosest(conditionEl,"[data-stage-id]")?.dataset.stageId,conditionId=conditionEl.dataset.conditionId??"",stage=this.item.system.stages[stageId??""];!stage||!(conditionId in stage.conditions)||(htmlQuery(conditionEl,"[data-action=condition-link]")?.addEventListener("click",()=>{const linked=stage.conditions[conditionId].linked;this.item.update({[`system.stages.${stageId}.conditions.${conditionId}.linked`]:!linked})}),htmlQuery(conditionEl,"[data-action=condition-delete]")?.addEventListener("click",()=>{this.item.update({[`system.stages.${stageId}.conditions.-=${conditionId}`]:null})}))}for(const deleteIcon of htmlQueryAll(html,"[data-action=effect-delete"))deleteIcon.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId,stage=this.item.system.stages[stageId??""];if(!stage)return;const deleteId=htmlClosest(event2.target,"[data-uuid]")?.dataset.uuid,effects=stage.effects.filter(e=>e.uuid!==deleteId);this.item.update({[`system.stages.${stageId}.effects`]:effects})});for(const link of htmlQueryAll(html,"a.document-link[data-uuid]"))link.addEventListener("click",async event2=>{const uuid=htmlClosest(event2.target,"[data-uuid]")?.dataset.uuid;(await fromUuid(uuid??""))?.sheet?.render(!0)})}async _onDrop(event2){if(!this.isEditable)return;const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!stageId)return;const stage=this.item.system.stages[stageId];if(!stage)return;const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(item?.isOfType("effect")){const effects=[...stage.effects,{uuid:item.uuid}];this.item.update({system:{stages:{[stageId]:{effects}}}})}else ui.notifications.error("PF2E.Item.Affliction.Error.RestrictedStageItem",{localize:!0})}async _updateObject(event2,formData){const categories=Object.keys(formData).filter(k=>/^system\.stages\.[a-z0-9]+\.damage\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event2,formData)}}class ABCSheetPF2e extends ItemSheetPF2e{static{__name(this,"ABCSheetPF2e")}static{__name2(this,"ABCSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const sheetData=await super.getData(options),features=Object.entries(this.item.toObject().system.items).map(([key,ref])=>({key,item:{...ref,fromWorld:ref.uuid.startsWith("Item.")}})).sort((a,b)=>a.item.level-b.item.level);return{...sheetData,features}}getLocalizedAbilities(traits){return traits!==void 0&&traits.value?traits.value.length===6?{free:game.i18n.localize("PF2E.AbilityFree")}:Object.fromEntries(traits.value.map(x=>[x,CONFIG.PF2E.abilities[x]])):{}}#isValidDrop(event2,feat){const validCategories=(htmlClosest(event2.target,"[data-valid-drops]")?.dataset.validDrops?.split(" ")??[]).filter(f=>setHasElement(FEAT_CATEGORIES,f));if(validCategories.includes(feat.category))return!0;const goodCategories=validCategories.map(c=>game.i18n.localize(CONFIG.PF2E.featCategories[c]));if(goodCategories.length>0){const badCategory=game.i18n.localize(CONFIG.PF2E.featCategories[feat.category]),warning=game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:badCategory,goodType:goodCategories[0]});return ui.notifications.warn(warning),!1}return!0}async _onDrop(event2){event2.preventDefault();const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??""),item=await ItemPF2e.fromDropData(dropData);if(!item?.isOfType("feat")||!this.#isValidDrop(event2,item))return;const entry={uuid:item.uuid,img:item.img,name:item.name,level:item.level},items=this.item.system.items,pathPrefix="system.items";let id;do id=foundry.utils.randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const li of htmlQueryAll(html,"li[data-index]")){const index=li.dataset.index,itemUUID=li.dataset.itemUuid;index&&(itemUUID&&htmlQuery(li,"a.name")?.addEventListener("click",()=>fromUuid(itemUUID).then(i=>i?.sheet.render(!0))),htmlQuery(li,"[data-action=remove]")?.addEventListener("click",()=>{this.item.update({[`system.items.-=${index}`]:null})}))}}}class AncestrySheetPF2e extends ABCSheetPF2e{static{__name(this,"AncestrySheetPF2e")}static{__name2(this,"AncestrySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),itemData=sheetData.item;return{...sheetData,selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),selectedFlaws:Object.fromEntries(Object.entries(itemData.system.flaws).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),sizes:createSheetOptions(CONFIG.PF2E.actorSizes,{value:[itemData.system.size]}),languages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.languages),additionalLanguages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.additionalLanguages)}}}class ArmorSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ArmorSheetPF2e")}static{__name2(this,"ArmorSheetPF2e")}async getData(options){const sheetData=await super.getData(options),armor=this.item,adjustedBulkHint=armor.isEquipped||!armor.actor?null:"PF2E.Item.Armor.UnequippedHint",runes=armor.system.runes,propertyRuneSlots=Array.fromRange(armor.isSpecific?runes.property.length:getPropertyRuneSlots(armor)).map(i=>({slug:runes.property[i]??null,label:RUNE_DATA.armor.property[runes.property[i]]?.name??null,disabled:i>0&&!runes.property[i-1]})),specificMagicData=armor._source.system.specific??pick(armor._source.system,["material","runes"]);return{...sheetData,adjustedBulkHint,basePrice:new CoinsPF2e(armor._source.system.price.value),baseTypes:CONFIG.PF2E.baseArmorTypes,categories:CONFIG.PF2E.armorCategories,groups:CONFIG.PF2E.armorGroups,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,sheetData.data.traits.otherTags),preciousMaterials:this.getMaterialSheetData(armor,MATERIAL_DATA.armor),propertyRuneSlots,runeTypes:RUNE_DATA.armor,specificMagicData}}async _updateObject(event2,formData){formData["system.acBonus"]===null&&(formData["system.acBonus"]=0);const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.runes.property.${index}`]}return super._updateObject(event2,formData)}}class BackgroundSheetPF2e extends ABCSheetPF2e{static{__name(this,"BackgroundSheetPF2e")}static{__name2(this,"BackgroundSheetPF2e")}async getData(options){const data=await super.getData(options),itemData=data.item;return{...data,trainedSkills:createSheetOptions(CONFIG.PF2E.skills,itemData.system.trainedSkills),selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)]))}}}class BookSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"BookSheetPF2e")}static{__name2(this,"BookSheetPF2e")}}class CampaignFeatureSheetPF2e extends ItemSheetPF2e{static{__name(this,"CampaignFeatureSheetPF2e")}static{__name2(this,"CampaignFeatureSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}get validTraits(){return CONFIG.PF2E.kingmakerTraits}async getData(options){const sheetData=await super.getData(options),hasLevel=this.item.behavior!=="activity";return{...sheetData,itemType:hasLevel?game.i18n.localize(this.item.levelLabel):null,categories:KINGMAKER_CATEGORIES,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,prerequisites:JSON.stringify(this.item.system.prerequisites?.value??[]),isFeat:this.item.isFeat}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const prerequisites=htmlQuery(html,'input[name="system.prerequisites.value"]');prerequisites&&new Tagify(prerequisites,{editTags:1})}_updateObject(event2,formData){return Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value}))),super._updateObject(event2,formData)}}class ClassSheetPF2e extends ABCSheetPF2e{static{__name(this,"ClassSheetPF2e")}static{__name2(this,"ClassSheetPF2e")}async getData(options){const sheetData=await super.getData(options),itemData=sheetData.item;return{...sheetData,skills:CONFIG.PF2E.skills,proficiencyChoices:CONFIG.PF2E.proficiencyLevels,selectedKeyAbility:this.getLocalizedAbilities(itemData.system.keyAbility),trainedSkills:createSheetTags(CONFIG.PF2E.skills,itemData.system.trainedSkills),ancestryFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.ancestryFeatLevels),classFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.classFeatLevels),generalFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.generalFeatLevels),skillFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillFeatLevels),skillIncreaseLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillIncreaseLevels)}}}class ConditionSheetPF2e extends ItemSheetPF2e{static{__name(this,"ConditionSheetPF2e")}static{__name2(this,"ConditionSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}}class ConsumableSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ConsumableSheetPF2e")}static{__name2(this,"ConsumableSheetPF2e")}async getData(options){const sheetData=await super.getData(options),item=this.item,canHaveDamageOrHealing=DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES.has(item.category),canHaveHealing=canHaveDamageOrHealing&&item.system.category!=="snare"&&!!item.system.damage&&["vitality","void","untyped"].includes(item.system.damage.type);return{...sheetData,canHaveDamageOrHealing,canHaveHealing,categories:sortStringRecord(CONFIG.PF2E.consumableCategories),damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),materialEffects:createSheetTags(CONFIG.PF2E.materialDamageEffects,item.system.material.effects),otherTags:createSheetTags(CONFIG.PF2E.otherConsumableTags,item.system.traits.otherTags),stackGroups:this.item.isAmmo?omit(CONFIG.PF2E.stackGroups,["coins","gems"]):null}}activateListeners($html){super.activateListeners($html);const html=$html[0];html.querySelector("button[data-action=add-damage]")?.addEventListener("click",()=>{this.item.update({"system.damage":{formula:"1d4",type:"untyped",kind:"damage"}})}),html.querySelector("a[data-action=remove-damage]")?.addEventListener("click",()=>{this.item.update({"system.damage":null})})}_updateObject(event2,formData){return formData["system.stackGroup"]===""&&(formData["system.stackGroup"]=null),super._updateObject(event2,formData)}}class ContainerSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ContainerSheetPF2e")}static{__name2(this,"ContainerSheetPF2e")}}const DEITY_SANCTIFICATIONS=[{modal:"can",what:["holy"]},{modal:"can",what:["unholy"]},{modal:"can",what:["holy","unholy"]},{modal:"must",what:["holy"]},{modal:"must",what:["unholy"]}];class DeitySheetPF2e extends ItemSheetPF2e{static{__name(this,"DeitySheetPF2e")}static{__name2(this,"DeitySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sheet-header, .sheet-content"}]}}async getData(options){const sheetData=await super.getData(options),spellEntries=Object.entries(sheetData.data.spells),spells=(await UUIDUtils.fromUUIDs(Object.values(sheetData.data.spells))).filter(i=>i instanceof SpellPF2e).map(spell=>{const level=Number(spellEntries.find(([,uuid])=>uuid===spell.uuid)?.at(0));return{uuid:spell.uuid,level,name:spell.name,img:spell.img}}).sort((spellA,spellB)=>spellA.level-spellB.level),sanctifications=[...DEITY_SANCTIFICATIONS.map(value=>{const modal=value.modal.capitalize(),what=value.what.map(c=>c.capitalize()).join("");return{value,label:`PF2E.Item.Deity.Sanctification.${modal}.${what}`}}),{value:null,label:"PF2E.Item.Deity.Sanctification.None"}];return{...sheetData,sanctifications,skills:CONFIG.PF2E.skills,divineFonts:createSheetOptions({harm:"PF2E.Item.Deity.DivineFont.Harm",heal:"PF2E.Item.Deity.DivineFont.Heal"},sheetData.data.font),spells}}activateListeners($html){super.activateListeners($html);const html=$html[0],getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");if(tagify(getInput("system.attribute"),{whitelist:CONFIG.PF2E.abilities,maxTags:2}),this.item.category==="philosophy")return;tagify(getInput("system.weapons"),{whitelist:CONFIG.PF2E.baseWeaponTypes,maxTags:2});const domainWhitelist=omitBy(CONFIG.PF2E.deityDomains,(_v,k)=>k.endsWith("-apocryphal"));tagify(getInput("system.domains.primary"),{whitelist:domainWhitelist,maxTags:6}),tagify(getInput("system.domains.alternate"),{whitelist:domainWhitelist,maxTags:6});const clericSpells=htmlQuery(html,".cleric-spells");if(!clericSpells)return;for(const link of htmlQueryAll(clericSpells,"a[data-action=view-spell]"))link.addEventListener("click",async()=>{const uuid=htmlClosest(link,"li")?.dataset.uuid??"",spell=await fromUuid(uuid);if(!(spell instanceof SpellPF2e)){this.render(!1),ui.notifications.error(`A spell with the UUID "${uuid}" no longer exists`);return}spell.sheet.render(!0)});for(const link of htmlQueryAll(clericSpells,"a[data-action=remove-spell]"))link.addEventListener("click",async()=>{const uuidToRemove=htmlClosest(link,"li")?.dataset.uuid,[levelToRemove]=Object.entries(this.item.system.spells).find(([_level,uuid])=>uuid===uuidToRemove)??[];if(!levelToRemove){this.render(!1);return}await this.item.update({[`system.spells.-=${levelToRemove}`]:null})});const spellLevelInputs=htmlQueryAll(clericSpells,"input[data-action=update-spell-level]");for(const input of spellLevelInputs)input.addEventListener("change",async()=>{const oldLevel=Number(input.dataset.level),uuid=this.item.system.spells[oldLevel];if(!uuid){this.render(!1);return}const newLevel=Math.clamped(Number(input.value)||1,1,10);oldLevel!==newLevel&&await this.item.update({[`system.spells.-=${oldLevel}`]:null,[`system.spells.${newLevel}`]:uuid})})}async _onDrop(event2){if(!this.isEditable)return;const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof SpellPF2e))throw ErrorPF2e("Invalid item drop on deity sheet");if(item.isCantrip||item.isFocusSpell||item.isRitual){ui.notifications.error("PF2E.Item.Deity.ClericSpells.DropError",{localize:!0});return}await this.item.update({[`system.spells.${item.rank}`]:item.uuid})}async _updateObject(event2,formData){return Array.isArray(formData["system.font"])&&(formData["system.font"]=formData["system.font"].filter(f=>!!f)),typeof formData["system.skill"]=="string"&&(formData["system.skill"]||=null),super._updateObject(event2,formData)}}class EffectSheetPF2e extends ItemSheetPF2e{static{__name(this,"EffectSheetPF2e")}static{__name2(this,"EffectSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}async getData(options){const badge=this.item.badge;return{...await super.getData(options),itemType:game.i18n.localize("PF2E.LevelLabel"),badgeType:badge?game.i18n.localize(`PF2E.Item.Effect.Badge.Type.${badge.type}`):"",timeUnits:CONFIG.PF2E.timeUnits}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"select.badge-type")?.addEventListener("change",event2=>{event2.stopPropagation()}),htmlQuery(html,"[data-action=badge-add]")?.addEventListener("click",()=>{const badge=htmlQuery(html,".badge-type")?.value==="formula"?{type:"formula",value:"1d20",evaluate:!0}:{type:"counter",value:1};this.item.update({system:{badge}})}),htmlQuery(html,"[data-action=badge-delete]")?.addEventListener("click",()=>{this.item.update({"system.-=badge":null})}),htmlQuery(html,"[data-action=badge-add-label")?.addEventListener("click",()=>{if(!this.item.system.badge)throw ErrorPF2e("Unexpected error adding badge label");const labels=this.item.system.badge.labels??[];labels.push(""),this.item.update({system:{badge:{labels}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=badge-delete-label]")){const index=Number(deleteIcon.dataset.idx);deleteIcon.addEventListener("click",()=>{const labels=this.item.system.badge?.labels;labels&&(labels.splice(index,1),labels.length===0?this.item.update({"system.badge.-=labels":null}):this.item.update({system:{badge:{labels}}}))})}}async _updateObject(event2,formData){const expanded=foundry.utils.expandObject(formData),badge=expanded.system?.badge;badge&&("labels"in badge&&typeof badge.labels=="object"&&(badge.labels=Object.values(badge.labels)),"reevaluate"in badge&&(badge.reevaluate||=null)),super._updateObject(event2,foundry.utils.flattenObject(expanded))}}class EquipmentSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"EquipmentSheetPF2e")}static{__name2(this,"EquipmentSheetPF2e")}async getData(options){const item=this.item;return{...await super.getData(options),isApex:item._source.system.traits.value.includes("apex"),attributes:CONFIG.PF2E.abilities,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,item.system.traits.otherTags)}}}class FeatSheetPF2e extends ItemSheetPF2e{static{__name(this,"FeatSheetPF2e")}static{__name2(this,"FeatSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}],hasSidebar:!0}}get validTraits(){return CONFIG.PF2E.featTraits}async getData(options){const sheetData=await super.getData(options),hasLineageTrait=this.item.traits.has("lineage");return{...sheetData,itemType:game.i18n.localize(this.item.isFeature?"PF2E.LevelLabel":"PF2E.Item.Feat.LevelLabel"),categories:CONFIG.PF2E.featCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,mandatoryTakeOnce:hasLineageTrait||sheetData.data.onlyLevel1,hasLineageTrait,canHaveKeyOptions:featCanHaveKeyOptions(this.item),selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");tagify(getInput("system.prerequisites.value"),{maxTags:6}),tagify(getInput("system.subfeatures.keyOptions"),{whitelist:CONFIG.PF2E.abilities,maxTags:3})}async _onDrop(event2){return handleSelfEffectDrop(this,event2)}_updateObject(event2,formData){Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value})));const keyOptionsKey="system.subfeatures.keyOptions",hasEmptyKeyOptions=Array.isArray(formData[keyOptionsKey])&&formData[keyOptionsKey].length===0,hasNoKeyOptions=!(keyOptionsKey in formData);return(hasEmptyKeyOptions||hasNoKeyOptions)&&(delete formData[keyOptionsKey],this.item._source.system.subfeatures&&(formData["system.subfeatures.-=keyOptions"]=null)),super._updateObject(event2,formData)}}class HeritageSheetPF2e extends ItemSheetPF2e{static{__name(this,"HeritageSheetPF2e")}static{__name2(this,"HeritageSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sidebar"}],hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),ancestry=await(async()=>{const item=this.item.system.ancestry?await fromUuid(this.item.system.ancestry.uuid):null;return item instanceof AncestryPF2e?item:null})();return{...sheetData,ancestry,ancestryRefBroken:!!sheetData.data.ancestry&&ancestry===null}}activateListeners($html){super.activateListeners($html),$html.find('a[data-action="remove-ancestry"]').on("click",()=>{this.item.update({"system.ancestry":null})})}async _onDrop(event2){const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof AncestryPF2e))throw ErrorPF2e("Invalid item drop on heritage sheet");const ancestryReference={name:item.name,slug:item.slug??sluggify(item.name),uuid:item.uuid};await this.item.update({"system.ancestry":ancestryReference})}}class KitSheetPF2e extends ItemSheetPF2e{static{__name(this,"KitSheetPF2e")}static{__name2(this,"KitSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const items=Object.fromEntries(Object.entries(this.item.system.items).map(([key,ref])=>[key,{...ref,fromWorld:ref.uuid.startsWith("Item.")}]));return{...await super.getData(options),priceString:this.item.price.value,items}}async _onDrop(event2){event2.preventDefault();const dragData=event2.dataTransfer?.getData("text/plain"),dragItem=JSON.parse(dragData??""),containerId=event2.target.dataset.containerId??event2.target.closest("[data-container-id]")?.dataset.containerId;if(dragItem.type!=="Item")return;const item=await fromUuid(dragItem.uuid??"");if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))return;const entry={uuid:item.uuid,img:item.img,quantity:1,name:item.name,isContainer:item.type==="backpack"&&!containerId,items:{}};let{items}=this.item.system,pathPrefix="system.items";containerId!==void 0&&(pathPrefix=`${pathPrefix}.${containerId}.items`,items=items[containerId]?.items??{});let id;do id=foundry.utils.randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}async removeItem(event2){const target=htmlClosest(event2.currentTarget??null,"li"),index=target?.dataset.index;if(!index)return this.item;const containerId=target.closest("[data-container-id]")?.dataset.containerId,path=containerId?`${containerId}.items.-=${index}`:`-=${target.dataset.index}`;return await this.item.update({[`system.items.${path}`]:null})??null}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const link of htmlQueryAll(html,"[data-action=remove]"))link.addEventListener("click",event2=>{this.removeItem(event2)})}async _updateObject(event2,formData){return formData["system.price.value"]&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"]))),super._updateObject(event2,formData)}}class MeleeSheetPF2e extends ItemSheetPF2e{static{__name(this,"MeleeSheetPF2e")}static{__name2(this,"MeleeSheetPF2e")}async getData(options){const sheetData=await super.getData(options),itemSource=this.item._source;sheetData.data.attack.value=itemSource.system.attack.value;for(const key of Object.keys(sheetData.data.damageRolls))sheetData.data.damageRolls[key].damage=itemSource.system.damageRolls[key].damage;return{...sheetData,damageTypes:CONFIG.PF2E.damageTypes,damageCategories:damageCategoriesUnique,attackEffects:createSheetOptions(this.getAttackEffectOptions(),this.item.system.attackEffects)}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const button of htmlQueryAll(html,"a[data-action=add-partial]"))button.addEventListener("click",()=>{const newKey=foundry.utils.randomID();this.item.update({[`system.damageRolls.${newKey}`]:{damage:"1d4",damageType:"bludgeoning"}})});for(const button of htmlQueryAll(html,"a[data-action=remove-partial]"))button.addEventListener("click",()=>{const partialKey=htmlClosest(button,"[data-key]")?.dataset.key;partialKey&&this.item.update({[`system.damageRolls.-=${partialKey}`]:null})})}async _updateObject(event2,formData){const categories=Object.keys(formData).filter(k=>/^system.damageRolls\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event2,formData)}}class ShieldSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ShieldSheetPF2e")}static{__name2(this,"ShieldSheetPF2e")}async getData(options){const sheetData=await super.getData(options),shield=this.item,isSpecificShield=shield.isSpecific,weaponRunes=shield.system.traits.integrated?.runes,hasPotencyRune=!!weaponRunes?.potency,propertyRuneSlots=(()=>hasPotencyRune?isSpecificShield?weaponRunes.property.map((_p,index)=>index):shield.system.material.type==="orichalcum"?[0,1,2,3]:[0,1,2]:[])().map(i=>({slug:weaponRunes?.property[i]??null,disabled:!weaponRunes?.potency||(i===3||weaponRunes.potency<3)&&i>0&&(!weaponRunes.property[i-1]||!isSpecificShield),readOnly:isSpecificShield})),materialData=shield.isBuckler?MATERIAL_DATA.shield.buckler:shield.isTowerShield?MATERIAL_DATA.shield.towerShield:MATERIAL_DATA.shield.shield;return{...sheetData,baseHardness:shield._source.system.hardness,basePrice:new CoinsPF2e(shield._source.system.price.value),baseTypes:sortStringRecord(CONFIG.PF2E.baseShieldTypes),canChangeMaterial:!shield.isSpecific||!!shield.system.material.type,preciousMaterials:this.getMaterialSheetData(shield,materialData),propertyRuneSlots,reinforcing:mapToObj.indexed(REINFORCING_RUNE_LOC_PATHS,(value,index)=>[index,value]),weaponRunes:weaponRunes?RUNE_DATA.weapon:null}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"input[data-action=toggle-specific")?.addEventListener("change",()=>{const newValue=this.item.system.specific?null:foundry.utils.deepClone({...pick(this.item._source.system,["material","runes"]),integrated:this.item._source.system.traits.integrated?{runes:this.item._source.system.traits.integrated.runes}:null});this.item.update({"system.specific":newValue})})}_updateObject(event2,formData){const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.traits.integrated.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.traits.integrated.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.traits.integrated.runes.property.${index}`]}return super._updateObject(event2,formData)}}const spellOverridable={traits:"PF2E.Traits",time:"PF2E.Item.Spell.Cast",target:"PF2E.SpellTargetLabel",area:"PF2E.AreaLabel",range:"PF2E.SpellRangeLabel",damage:"PF2E.DamageLabel"};class SpellSheetPF2e extends ItemSheetPF2e{static{__name(this,"SpellSheetPF2e")}static{__name2(this,"SpellSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dragSelector:"[data-variant-id]",dropSelector:"[data-can-drop=true]"}]}}get id(){const baseId=super.id,appliedOverlays=this.item.appliedOverlays;return this.item.isVariant&&appliedOverlays?`${baseId}-${[...appliedOverlays.keys()].join("-")}`:baseId}get validTraits(){return omit(CONFIG.PF2E.Item.traits.spell,Array.from(MAGIC_TRADITIONS))}async getData(options){const sheetData=await super.getData(options),spell=this.item,{isCantrip,isFocusSpell,isRitual}=spell,descriptionPrepend=await createDescriptionPrepend(spell,{includeTraditions:!0});sheetData.enrichedContent.description=`${descriptionPrepend}${sheetData.enrichedContent.description}`;const variants=spell.overlays.overrideVariants.map(variant=>({name:variant.name,variantId:variant.variantId,sort:variant.sort,actions:getActionGlyph(variant.system.time.value)})).sort((a,b)=>a.sort-b.sort),passiveDefense=(()=>{switch(spell.system.defense?.passive?.statistic){case"ac":return"PF2E.Check.DC.Specific.armor";case"fortitude-dc":return"PF2E.Check.DC.Specific.fortitude";case"reflex-dc":return"PF2E.Check.DC.Specific.reflex";case"will-dc":return"PF2E.Check.DC.Specific.will";default:return null}})(),damageKinds=mapValues$1(spell.system.damage,(damage,id)=>{const healingDisabled=!["vitality","void","untyped"].includes(damage.type)||!!damage.category,currentKinds=Array.from(spell.system.damage[id].kinds);return[{value:["damage"],label:"PF2E.DamageLabel",selected:equals(currentKinds,["damage"]),disabled:!1},{value:["healing"],label:"PF2E.TraitHealing",selected:equals(currentKinds,["healing"]),disabled:healingDisabled},{value:["damage","healing"],label:"PF2E.Damage.Kind.Both.Label",selected:equals(currentKinds,["damage","healing"]),disabled:healingDisabled}]});return{...sheetData,itemType:createSpellRankLabel(this.item),isCantrip,isFocusSpell,isRitual,passiveDefense,variants,isVariant:this.item.isVariant,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),damageSubtypes:pick(CONFIG.PF2E.damageCategories,[...DAMAGE_CATEGORIES_UNIQUE]),damageKinds,materials:CONFIG.PF2E.materialDamageEffects,areaSizes:CONFIG.PF2E.areaSizes,areaTypes:CONFIG.PF2E.areaTypes,heightenIntervals:[1,2,3,4],heightenOverlays:this.#prepareHeighteningLevels(),canHeighten:this.isEditable&&this.getAvailableHeightenLevels().length>0}}get title(){return this.item.isVariant?game.i18n.format("PF2E.Item.Spell.Variants.SheetTitle",{originalName:this.item.original?.name??""}):super.title}activateListeners($html){super.activateListeners($html);const html=$html[0];if(this.isEditable&&this.item.isVariant){const levelInput=htmlQuery(html,'input[name="system.level.value"');levelInput&&(levelInput.readOnly=!0)}tagify(html.querySelector('input[name="system.traits.traditions"]'),{whitelist:CONFIG.PF2E.magicTraditions});for(const anchor of htmlQueryAll(html,"a[data-action=add-damage-partial]"))anchor.addEventListener("click",()=>{const baseKey=this.#getOverlayFromElement(anchor)?.base??"system",emptyDamage={formula:"",kinds:["damage"],type:"bludgeoning",category:null,materials:[]};this.item.update({[`${baseKey}.damage.${foundry.utils.randomID()}`]:emptyDamage})});for(const anchor of htmlQueryAll(html,"a[data-action=delete-damage-partial]"))anchor.addEventListener("click",()=>{const overlayData=this.#getOverlayFromElement(anchor),baseKey=overlayData?.base??"system",key=anchor.dataset.id;if(key){const values={[`${baseKey}.damage.-=${key}`]:null};overlayData||(values[`${baseKey}.heightening.damage.-=${key}`]=null),this.item.update(values)}});htmlQuery(html,"button[data-action=add-interval-heightening]")?.addEventListener("click",event2=>{event2.preventDefault();const baseKey=this.#getOverlayFromElement(event2.target)?.base??"system",data={type:"interval",interval:1,damage:mapToObj(Object.keys(this.item.system.damage),key=>[key,"0"])};this.item.update({[`${baseKey}.heightening`]:data})}),htmlQuery(html,"button[data-action=add-fixed-heightening]")?.addEventListener("click",()=>{const highestLevel=this.item.getHeightenLayers().at(-1)?.level,available=this.getAvailableHeightenLevels(),level=highestLevel&&highestLevel<10?highestLevel+1:available.at(0);level!==void 0&&this.item.update({"system.heightening":{type:"fixed",levels:{[level]:{}}}})}),htmlQuery(html,"a[data-action=delete-heightening]")?.addEventListener("click",()=>{this.item.update({"system.-=heightening":null})});for(const overlayEditor of htmlQueryAll(html,"[data-overlay-type=heighten]")){const overlay=this.#getOverlayFromElement(overlayEditor);if(!overlay)continue;htmlQuery(overlayEditor,"a[data-action=delete-overlay]")?.addEventListener("click",()=>{if(overlay.type==="heighten"){const layers=this.item.getHeightenLayers();if(layers.length===1&&layers[0].level===overlay.level){this.item.update({"system.-=heightening":null});return}}const parts=overlay.base.split(".");parts.push(`-=${parts.pop()}`),this.item.update({[parts.join(".")]:null})});for(const addProperty of htmlQueryAll(overlayEditor,"button[data-action=add-overlay-property]")){const property=addProperty.dataset.property;!overlay.system||!property||property in overlay.system||addProperty.addEventListener("click",()=>{try{const value=this.#getDefaultProperty(property);this.item.update({[`${overlay.base}.${property}`]:value})}catch(ex){ex instanceof Error&&ui.notifications.error(ex.message)}})}for(const removeProperty of htmlQueryAll(overlayEditor,"a[data-action=delete-overlay-property]")){const property=removeProperty.dataset.property;property&&removeProperty.addEventListener("click",()=>{const updates={[`${overlay.base}.-=${property}`]:null};property==="damage"&&(updates[`${overlay.base}.-=heightening`]=null),this.item.update(updates)})}const levelSelect=htmlQuery(overlayEditor,"select[data-action=change-heighten-level]");levelSelect?.addEventListener("change",()=>{const newLevel=Number(levelSelect.value),existingData=this.item.getHeightenLayers().find(layer=>layer.level===overlay.level);this.item.update({[`system.heightening.levels.-=${overlay.level}`]:null,[`system.heightening.levels.${newLevel}`]:existingData?.system??{}})})}htmlQuery(html,"a[data-action=variant-create]")?.addEventListener("click",()=>{this.item.overlays.create("override")});for(const anchor of htmlQueryAll(html,"a[data-action=edit-variant]"))anchor.addEventListener("click",()=>{const overlayId=anchor.dataset.id;overlayId&&this.item.loadVariant({overlayIds:[overlayId]})?.sheet.render(!0)});for(const anchor of htmlQueryAll(html,"a[data-action=delete-variant]"))anchor.addEventListener("click",()=>{const id=anchor.dataset.id;if(id){const variant=this.item.loadVariant({overlayIds:[id]});if(!variant)throw ErrorPF2e(`Spell ${this.item.name} (${this.item.uuid}) does not have a variant with id: ${id}`);new Dialog({title:game.i18n.localize("PF2E.Item.Spell.Variants.DeleteDialogTitle"),content:`<p>${game.i18n.format("PF2E.Item.Spell.Variants.DeleteDialogText",{variantName:variant.name})}</p>`,buttons:{delete:{icon:fontAwesomeIcon("fa-trash").outerHTML,label:game.i18n.localize("PF2E.DeleteShortLabel"),callback:()=>{this.item.overlays.deleteOverlay(id)}},cancel:{icon:fontAwesomeIcon("fa-times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}});const ritualCheckbox=htmlQuery(html,"input[data-action=toggle-ritual-data]");ritualCheckbox?.addEventListener("click",async event2=>{event2.preventDefault(),ritualCheckbox.readOnly=!0,await this.item.update({"system.ritual":this.item.system.ritual?null:{primary:{check:""},secondary:{checks:"",casters:0}}})})}async _updateObject(event2,formData){if(formData["system.area.value"]?formData["system.area.type"]||="burst":(delete formData["system.area.value"],delete formData["system.area.type"],formData["system.area"]=null),this.item.original&&this.item.appliedOverlays?.has("override")&&!this.rendered){await this.item.original.overlays.updateOverride(this.item,formData);return}super._updateObject(event2,formData)}_onDragStart(event2){const id=event2.target.closest(".variant")?.dataset.variantId??"";event2.dataTransfer.setData("text/plain",JSON.stringify({action:"sort",data:{sourceId:id}}))}async _onDrop(event2){event2.preventDefault();const transferString=event2.dataTransfer.getData("text/plain");if(!transferString)return;const{action:action2,data}=JSON.parse(transferString)??{};switch(action2){case"sort":{const sourceId=data?.sourceId??"",targetId=event2.target.closest(".variant")?.dataset.variantId??"";if(sourceId&&targetId&&sourceId!==targetId){const sourceVariant=this.item.loadVariant({overlayIds:[sourceId]}),targetVariant=this.item.loadVariant({overlayIds:[targetId]});if(sourceVariant&&targetVariant){const siblings=this.item.overlays.overrideVariants.filter(variant=>variant.id!==sourceId&&variant.id!==targetId);siblings.push(targetVariant);const sorting=SortingHelpers.performIntegerSort(sourceVariant,{target:targetVariant,siblings,sortKey:"sort",sortBefore:!0});for(const s of sorting)await this.item.overlays.updateOverride(s.target,s.update,{render:!1});this.render(!0)}}break}}}getAvailableHeightenLevels(){const heightenLayers=this.item.getHeightenLayers();return[2,3,4,5,6,7,8,9,10].filter(level=>level>this.item.baseRank&&!heightenLayers.some(layer=>layer.level===level))}#getOverlayFromElement(target){const overlayEl=htmlClosest(target,"[data-overlay-type]");if(!overlayEl)return null;const domData=overlayEl.dataset,type=String(domData.overlayType);if(!tupleHasValue(["heighten","variant"],type))return null;const id="overlayId"in domData?String(domData.overlayId):null,level="level"in domData?Number(domData.level):null,collectionPath=type==="heighten"?"system.heightening.levels":"system.variants",base=type==="heighten"?`${collectionPath}.${level}`:`${collectionPath}.${id}`,system=(()=>{if(type==="heighten"){const heightening=this.item.system.heightening;if(heightening?.type==="fixed")return heightening.levels[level]??null}return null})();return{id,level,type,base,dataPath:base,system}}#getDefaultProperty(property){const scaling=this.item.getHeightenLayers().reverse(),baseValue=(()=>{for(const entry of[...scaling,{system:foundry.utils.deepClone(this.item._source.system)}])if(objectHasKey(entry.system,property))return entry.system[property];return null})();if(baseValue)return baseValue;if(property==="area")return{value:5,type:"burst"};throw ErrorPF2e(`Failed to initialize property ${property} for overlay`)}#prepareHeighteningLevels(){return this.item.getHeightenLayers().map(layer=>{const base=`system.heightening.levels.${layer.level}`,missing=[];for(const[key,label]of Object.entries(spellOverridable))key in layer.system||missing.push({key,label});return{id:null,type:"heighten",level:layer.level,base,dataPath:base,system:layer.system,missing,heightenLevels:[layer.level,...this.getAvailableHeightenLevels()].sort(),traits:layer.system.traits?.value?createTagifyTraits(layer.system.traits.value,{record:CONFIG.PF2E.spellTraits}):null}})}}class TreasureSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"TreasureSheetPF2e")}static{__name2(this,"TreasureSheetPF2e")}async getData(options){return{...await super.getData(options),currencies:CONFIG.PF2E.currencies,stackGroups:pick(CONFIG.PF2E.stackGroups,["coins","gems"])}}_updateObject(event2,formData){return formData["system.stackGroup"]===""&&(formData["system.stackGroup"]=null),super._updateObject(event2,formData)}}class WeaponSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"WeaponSheetPF2e")}static{__name2(this,"WeaponSheetPF2e")}async getData(options){const sheetData=await super.getData(options),weapon=this.item,runes=weapon.system.runes,propertyRuneSlots=Array.fromRange(weapon.isSpecific?runes.property.length:getPropertyRuneSlots(weapon)).map(i=>({slug:runes.property[i]??null,label:RUNE_DATA.weapon.property[runes.property[i]]?.name??null,disabled:i>0&&!runes.property[i-1]})),abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),hintText=abpEnabled?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",adjustedDiceHint=weapon.system.damage.dice!==weapon._source.system.damage.dice?game.i18n.format(game.i18n.localize(hintText),{property:game.i18n.localize("PF2E.Item.Weapon.Damage.DiceNumber"),value:weapon.system.damage.dice}):null,damageDieFaces=Object.fromEntries(Object.entries(CONFIG.PF2E.damageDie).map(([num,label])=>[Number(num.replace("d","")),label]).sort(([numA],[numB])=>numA-numB)),traitSet=weapon.traits,isComboWeapon=traitSet.has("combination"),weaponRanges=Array.from(WEAPON_RANGES).reduce((ranges,range2)=>({...ranges,[range2]:game.i18n.format("PF2E.WeaponRangeN",{range:range2})}),{}),rangedOnlyTraits=["combination","thrown","volley-20","volley-30","volley-50"],mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,weapon.group)||rangedOnlyTraits.some(trait=>traitSet.has(trait)),mandatoryMelee=sheetData.data.traits.value.some(trait=>/^thrown-\d+$/.test(trait)),otherTags=(()=>{const otherWeaponTags2=foundry.utils.deepClone(CONFIG.PF2E.otherWeaponTags);return weapon.hands!=="1"&&delete otherWeaponTags2.implement,createSheetTags(otherWeaponTags2,sheetData.data.traits.otherTags)})(),meleeUsage=sheetData.data.meleeUsage??{group:"knife",damage:{type:"piercing",die:"d4"},traits:[]},specificMagicData=weapon._source.system.specific??pick(weapon._source.system,["material","runes"]);return{...sheetData,abpEnabled,adjustedDiceHint,baseTypes:sortStringRecord(CONFIG.PF2E.baseWeaponTypes),categories:sortStringRecord(CONFIG.PF2E.weaponCategories),conditionTypes:sortStringRecord(CONFIG.PF2E.conditionTypes),damageDice:CONFIG.PF2E.damageDice,damageDie:CONFIG.PF2E.damageDie,damageDieFaces,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),groups:sortStringRecord(CONFIG.PF2E.weaponGroups),isBomb:weapon.group==="bomb",isComboWeapon,itemBonuses:CONFIG.PF2E.itemBonuses,mandatoryMelee,mandatoryRanged,meleeGroups:sortStringRecord(CONFIG.PF2E.meleeWeaponGroups),meleeUsage,meleeUsageTraits:createSheetTags(CONFIG.PF2E.weaponTraits,meleeUsage.traits??[]),otherTags,preciousMaterials:this.getMaterialSheetData(weapon,MATERIAL_DATA.weapon),propertyRuneSlots,runeTypes:RUNE_DATA.weapon,specificMagicData,weaponMAP:CONFIG.PF2E.weaponMAP,weaponRanges,weaponReload:CONFIG.PF2E.weaponReload}}activateListeners($html){super.activateListeners($html);const html=$html[0],pdElements=htmlQueryAll(html,"[data-action=update-persistent]");for(const element of pdElements)element.addEventListener("change",async event2=>{if(!(event2.target instanceof HTMLInputElement||event2.target instanceof HTMLSelectElement))throw ErrorPF2e("Unexpected error updating persistent damage data");const diceNumber=Number(pdElements.find(e=>e.dataset.persistentField==="number")?.value)||0,dieFaces=Number(pdElements.find(e=>e.dataset.persistentField==="faces")?.value),baseDamageType=this.item.system.damage.damageType,damageType=pdElements.find(e=>e.dataset.persistentField==="type")?.value||baseDamageType;if(!(typeof diceNumber=="number"&&typeof dieFaces=="number"&&damageType))throw ErrorPF2e("Unexpected error updating persistent damage data");const maybeDiceNumber=Math.trunc(Math.abs(Number(event2.target.value)||0));if(event2.target.dataset.persistentField==="number"&&maybeDiceNumber===0)await this.item.update({"system.damage.persistent":null});else if(objectHasKey(CONFIG.PF2E.damageTypes,damageType)){const damage={number:Math.trunc(Math.abs(diceNumber))||1,faces:tupleHasValue([4,6,8,10,12],dieFaces)?dieFaces:null,type:damageType};await this.item.update({"system.damage.persistent":damage})}})}async _updateObject(event2,formData){const weapon=this.item;formData["system.bonusDamage.value"]||=0,formData["system.splashDamage.value"]||=0,formData["system.range"]||=null,"system.damage.dice"in formData&&(formData["system.damage.dice"]=Math.clamped(Number(formData["system.damage.dice"])||0,0,8)),weapon.system.meleeUsage&&!this.item.traits.has("combination")&&(formData["system.-=meleeUsage"]=null);const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.runes.property.${index}`]}return super._updateObject(event2,formData)}}class UserConfigPF2e extends UserConfig{static{__name(this,"UserConfigPF2e")}static{__name2(this,"UserConfigPF2e")}async getData(options){const data=await super.getData(options);return data.actors=data.actors.filter(a=>a.type!=="party"),data}get template(){return"systems/pf2e/templates/user/sheet.hbs"}}class SceneConfigPF2e extends SceneConfig{static{__name(this,"SceneConfigPF2e")}static{__name2(this,"SceneConfigPF2e")}get scene(){return this.document}async _renderInner(data,options){const html=(await super._renderInner(data,options))[0],[tab,panel]=await(async()=>{const hbsPath="systems/pf2e/templates/scene/sheet-partials.hbs",rbvWorldDefault=game.i18n.localize(game.pf2e.settings.rbv?"PF2E.SETTINGS.EnabledDisabled.Enabled":"PF2E.SETTINGS.EnabledDisabled.Disabled"),templates=await renderTemplate(hbsPath,{scene:this.scene,rbvWorldDefault});return htmlQueryAll(createHTMLElement("div",{innerHTML:templates}),"template")})(),tabs=htmlQuery(html,"nav.tabs"),ambientTabContent=htmlQuery(html,".tab[data-tab=ambience]");if(!tabs||!ambientTabContent)throw ErrorPF2e("Unexpected error in scene configuration");return tabs.append(...tab.content.children),ambientTabContent.after(...panel.content.children),$(html)}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=world-rbv-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(menu){const options={highlightSetting:"rulesBasedVision"};new menu.type(void 0,options).render(!0)}}),this.#activateRBVListeners(html)}#activateRBVListeners(html){if(!this.document.rulesBasedVision)return;const globalLight=html.querySelector("input[name^=globalLight]"),hasglobalThreshold=html.querySelector("input[name=hasGlobalThreshold]"),globalLightThreshold=html.querySelector("input[name=globalLightThreshold]");if(globalLight&&hasglobalThreshold&&globalLightThreshold){globalLight.disabled=!0,hasglobalThreshold.disabled=!0,globalLightThreshold.disabled=!0,globalLightThreshold.nextElementSibling?.classList.add("disabled");for(const input of[globalLight,globalLightThreshold]){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy"));const rbvLink=managedBy.querySelector("rbv"),anchor=document.createElement("a");anchor.innerText=rbvLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event2=>{event2.preventDefault(),event2.stopPropagation();const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),rbvLink?.replaceWith(anchor),input.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}if(this.document.darknessSyncedToTime){const darknessInput=html.querySelector("input[name=darkness]");if(darknessInput){darknessInput.disabled=!0,darknessInput.nextElementSibling?.classList.add("disabled");const managedBy=WorldClock.createSyncedMessage();darknessInput.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}}}}async _updateObject(event2,formData){const rbvSetting=formData["flags.pf2e.rulesBasedVision"];formData["flags.pf2e.rulesBasedVision"]=rbvSetting==="true"?!0:rbvSetting==="false"?!1:null;const hearingRange=formData["flags.pf2e.hearingRange"];return formData["flags.pf2e.hearingRange"]=typeof hearingRange=="number"?Math.ceil(Math.clamped(hearingRange||5,5,3e3)/5)*5:null,super._updateObject(event2,formData)}}function registerSheets(){const sheetLabel=game.i18n.localize("PF2E.SheetLabel");Scenes.registerSheet("pf2e",SceneConfigPF2e,{makeDefault:!0}),DocumentSheetConfig.registerSheet(TokenDocumentPF2e,"pf2e",TokenConfigPF2e,{makeDefault:!0}),Actors.unregisterSheet("core",ActorSheet);const localizeType=__name2(type=>{const docType=type in CONFIG.PF2E.Actor.documentClasses?"Actor":"Item";return game.i18n.localize(`TYPES.${docType}.${type}`)},"localizeType");Actors.registerSheet("pf2e",CharacterSheetPF2e,{types:["character"],label:game.i18n.format(sheetLabel,{type:localizeType("character")}),makeDefault:!0}),Actors.registerSheet("pf2e",NPCSheetPF2e,{types:["npc"],label:game.i18n.format(sheetLabel,{type:localizeType("npc")}),makeDefault:!0}),Actors.registerSheet("pf2e",SimpleNPCSheet,{types:["npc"],label:"PF2E.Actor.NPC.SimpleSheet",canBeDefault:!1}),Actors.registerSheet("pf2e",HazardSheetPF2e,{types:["hazard"],label:game.i18n.format(sheetLabel,{type:localizeType("hazard")})}),Actors.registerSheet("pf2e",LootSheetPF2e,{types:["loot"],label:game.i18n.format(sheetLabel,{type:localizeType("loot")}),makeDefault:!0}),Actors.registerSheet("pf2e",FamiliarSheetPF2e,{types:["familiar"],label:game.i18n.format(sheetLabel,{type:localizeType("familiar")}),makeDefault:!0}),Actors.registerSheet("pf2e",VehicleSheetPF2e,{types:["vehicle"],label:game.i18n.format(sheetLabel,{type:localizeType("vehicle")}),makeDefault:!0}),Actors.registerSheet("pf2e",PartySheetPF2e,{types:["party"],label:game.i18n.format(sheetLabel,{type:localizeType("party")}),makeDefault:!0}),Actors.registerSheet("pf2e",ArmySheetPF2e,{types:["army"],label:game.i18n.format(sheetLabel,{type:localizeType("army")}),makeDefault:!0}),Items.unregisterSheet("core",ItemSheet);const itemTypes=["lore","spellcastingEntry"];for(const itemType of itemTypes)Items.registerSheet("pf2e",ItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});const sheetEntries=[["action",AbilitySheetPF2e],["affliction",AfflictionSheetPF2e],["ancestry",AncestrySheetPF2e],["armor",ArmorSheetPF2e],["background",BackgroundSheetPF2e],["backpack",ContainerSheetPF2e],["book",BookSheetPF2e],["campaignFeature",CampaignFeatureSheetPF2e],["class",ClassSheetPF2e],["condition",ConditionSheetPF2e],["consumable",ConsumableSheetPF2e],["deity",DeitySheetPF2e],["effect",EffectSheetPF2e],["equipment",EquipmentSheetPF2e],["feat",FeatSheetPF2e],["heritage",HeritageSheetPF2e],["kit",KitSheetPF2e],["lore",LoreSheetPF2e],["melee",MeleeSheetPF2e],["shield",ShieldSheetPF2e],["spell",SpellSheetPF2e],["treasure",TreasureSheetPF2e],["weapon",WeaponSheetPF2e]];for(const[type,Sheet]of sheetEntries)Items.registerSheet("pf2e",Sheet,{types:[type],label:game.i18n.format(sheetLabel,{type:localizeType(type)}),makeDefault:!0});for(const itemType of PHYSICAL_ITEM_TYPES)sheetEntries.some(([type,_sheet])=>itemType===type)||Items.registerSheet("pf2e",PhysicalItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});Journal.unregisterSheet("core",JournalSheet),Journal.registerSheet("pf2e",JournalSheetPF2e,{label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.JournalEntry")}),makeDefault:!0}),DocumentSheetConfig.unregisterSheet(JournalEntryPage,"core",JournalTextTinyMCESheet),DocumentSheetConfig.registerSheet(JournalEntryPage,"pf2e",JournalTextTinyMCESheetPF2e,{types:["text"],label:game.i18n.localize("EDITOR.TinyMCE")}),Users.unregisterSheet("core",UserConfig),Users.registerSheet("pf2e",UserConfigPF2e,{makeDefault:!0,label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.User")})})}__name(registerSheets,"registerSheets"),__name2(registerSheets,"registerSheets");const Setup={listen:()=>{Hooks.once("setup",()=>{registerSheets(),game.settings.settings.get("core.chatBubblesPan").default=!1,game.settings.settings.get("core.notesDisplayToggle").default=!0;const defaultTokenSettingsDefaults=game.settings.settings.get("core.defaultToken").default;defaultTokenSettingsDefaults.displayName=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,defaultTokenSettingsDefaults.displayBars=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER})}},TargetToken={listen:()=>{Hooks.on("targetToken",(user,token)=>{const tokenDocument=token.document;ui.combat.refreshTargetDisplay(tokenDocument);const actors=getSelectedOrOwnActors();if(actors.length===1&&tokenDocument.object){const actorToken=actors[0].getActiveTokens(!1,!1).shift();canvas.tokens.highlightObjects&&user===game.user&&actorToken?.flankingHighlight.draw()}})}},UpdateWorldTime={listen:()=>{Hooks.on("updateWorldTime",async(_total,diff)=>{game.combat?.started||game.pf2e.effectTracker.refresh({resetItemData:!0});const worldClock=game.pf2e.worldClock;setTimeout(()=>worldClock.render(!1),1),await worldClock.animateDarkness(diff)})}},HooksPF2e={listen(){const listeners=[Load,BabeleReady,CanvasInit,CanvasReady,CloseCombatTrackerConfig,CloseWorldClockSettings,DiceSoNiceReady,DropCanvasData,GetSceneControlButtons,I18nInit,Init,LightingRefresh,Ready,RenderChatPopout,RenderCombatTrackerConfig,RenderDialog,RenderJournalPageSheet,RenderJournalTextPageSheet,RenderSettings,RenderTokenHUD,Setup,TargetToken,UpdateWorldTime];for(const Listener of listeners)Listener.listen()}};HooksPF2e.listen();
|