All user data for FoundryVTT. Includes worlds, systems, modules, and any asset in the "foundryuserdata" directory. Does NOT include the FoundryVTT installation itself.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1 lines
58 KiB

const e={base:Error,internal:Error,package:Error,already_overridden:Error,invalid_chain:Error};Object.seal(e);const t="lib-wrapper",r="libWrapper",i="libWrapper",n=!1,a=function(e,t,i,n=!0){if(Object.isFrozen(e))throw new Error(`${r}: Enum '${e.name}' is frozen.`);if(t!==t.toUpperCase())throw new Error(`${r}: Enum keys must be all uppercase.`);const a=new(Function("x",`return class ${t} extends x {}`)(e.value_cls));if(a.name!=t)throw new Error(`${r}: Incorrect value_obj name ${a.name}. Expected ${t}.`);if(void 0!==i&&(a.value=i),Object.freeze(a),Object.freeze(a.prototype),Object.freeze(a.constructor),Object.freeze(a.constructor.prototype),t in e)throw new Error(`${r}: Name '${t}' is already present in ${e.name}.`);if(e[t]=a,void 0!==i){if(e.reverse.has(i))throw new Error(`${r}: Value '${i}' is already present in ${e.name}.`);e.reverse.set(i,a)}return e.list.push(a),n&&e.sort_list_by_value(),a},s=function(e,t,i=!0){let n;if("string"!=typeof e)throw new Error(`${r}: Enum name must be a string`);if("object"!=typeof t)throw new Error(`${r}: Enum collection must be a dictionary or an array`);const s=!(t instanceof Array),o=`${e}Enum`,c={[o]:class{constructor(e,t=void 0){return this.constructor.get(e,t)}static get(t,i=void 0){if(t instanceof n)return t;if("string"==typeof t){const e=this[t.toUpperCase()];if(e)return e}{let e=this.reverse.get(t);if(void 0===e&&"string"==typeof t){const r=parseInt(t);Number.isInteger(r)&&(e=this.reverse.get(r))}if(void 0!==e)return e}if(void 0===i)throw new Error(`${r}: '${t}' is not a valid key or value for the enum ${e}.`);return i}static has(e){return e instanceof n}static toString(){return this.name}static get value_cls(){return n}static sort_list_by_value(){return this.list.sort((function(e,t){return(e.value??0)-(t.value??0)}))}}}[o],l=`${e}Value`;if(n={[l]:class{static toString(){return l}get name(){return this.constructor.name}get enum(){return c}toString(){return this.name}get lower(){return this.name.toLowerCase()}}}[l],Object.freeze(n),Object.freeze(n.prototype),c.list=[],s&&(c.reverse=new Map),t instanceof Array)for(const e of t)a(c,e,void 0,!1);else for(const e in t)a(c,e,t[e],!1);return c.sort_list_by_value(),i&&(Object.freeze(c),Object.freeze(c.prototype),Object.freeze(c.list),s&&Object.freeze(c.reverse)),c},o=function(t=!1){const r=globalThis.game?.user?.data;if(r)return r;const i=globalThis.game?.userId??globalThis.game?.data?.userId;if(!i){if(t)return null;throw new e.internal("Unable to obtain the current user ID")}const n=globalThis.game?.data?.users?.find((e=>e._id==i));if(!n){if(t)return null;throw new e.internal("Unable to obtain the current user data object")}return n},c=function(t,r,i=!1,n=!0){try{const e=globalThis.game?.settings?.get;if(e)return e.call(game.settings,t,r)}catch(e){if(!i)throw e}const a=`${t}.${r}`;try{const t=globalThis.localStorage?.[a];if(null==t){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}'`)}const r=JSON.parse(t);if(null==r){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}'`)}return r}catch(t){if(n)return null;throw new e.internal(`Unable to obtain the setting '${a}' due to exception in polyfill:`,t)}},l=s("PackageType",{ZERO:0,TRACE:100,DEBUG:200,INFO:300,WARNING:400,ERROR:500,CRITICAL:Number.MAX_SAFE_INTEGER-1,ALWAYS:Number.MAX_SAFE_INTEGER}),p={NEVER:l.ZERO,ALL:l.ZERO,WARN:l.WARNING},d={[l.ZERO.value]:[console,"debug"],[l.TRACE.value]:[console,"debug"],[l.DEBUG.value]:[console,"debug"],[l.INFO.value]:[console,"info"],[l.WARNING.value]:[console,"warn"],[l.ERROR.value]:[console,"error"],[l.CRITICAL.value]:[console,"error"],[l.ALWAYS.value]:[console,"info"]},u={never:l.ZERO,trace:l.TRACE,debug:l.DEBUG,info:l.INFO,warning:l.WARNING,warn:l.WARNING,error:l.ERROR,critical:l.CRITICAL,always:l.ALWAYS},h=`${r}:`,g={[l.ZERO.value]:`[0] ${h}`,[l.TRACE.value]:`[T] ${h}`,[l.DEBUG.value]:`[D] ${h}`,[l.INFO.value]:`[I] ${h}`,[l.WARNING.value]:`[W] ${h}`,[l.ERROR.value]:`[E] ${h}`,[l.CRITICAL.value]:`[!] ${h}`,[l.ALWAYS.value]:h};let f=null;const _=function(e){return null==e?0:e.value??e},w=function(e,t,r){const i=_(e);{const e=t[i];if(e)return e}for(const e of l.list)if(!(i>e.value))return t[e.value];return r};function m(){for(const e in u){const t=u[e],r=Log.fn(t);Log[e]=r??(()=>{}),Log[`${e}$`]=r}Log.stack=console.trace&&Log.has_trace?console.trace.bind(console):()=>{}}class Log{static get verbosity(){return f??l.WARNING}static set verbosity(t){const r=l.get(t,parseInt(t));if(!l.has(r)&&!Number.isInteger(r))throw new e.internal(`Parameter 'value' must be a 'VERBOSITY' enum value or an integer, but got '${t}'.`);f=r,m()}static get verbosity_value(){return _(this.verbosity)}static get verbosities(){return l}static init(e=!1){if(!e&&null!=f)return;const i=c(t,"log-verbosity",!0,!0);if(null!=i)try{this.verbosity=i}catch(e){console.error(`${r}: Unable to set logging verbosity.\n`,e)}}static enabled(e=null){return _(e)>=this.verbosity_value}static fn(e,t=e){if(!this.enabled(e))return null;const[r,i]=function(e){return w(e,d,[console,"log"])}(t),n=function(e,t){return w(e,g,h)}(e);return r[i].bind(r,n)}static log(e,...t){return this.fn(e)?.(...t)}}!function(){for(const e of l.list)Log[e.name]=e;for(const e in p)Log[e]=p[e]}(),function(){for(const e in u){const t=u[e];Object.defineProperty(Log,`has_${e}`,{get:Log.enabled.bind(Log,t),configurable:!1})}}(),m(),Log.init(!0),Object.seal(Log);var b={"lib-wrapper":{settings:{yes:"Yes",no:"No",save:"Save",reload:"Reload",reset:"Reset","notify-issues-gm":{name:"Notify GM of Issues",hint:"Whether to notify GMs when an issue is detected, for example a conflict."},"notify-issues-player":{name:"Notify Players of Issues",hint:"Whether to notify Players when an issue is detected, for example a conflict."},"high-performance-mode":{name:"High-Performance Mode",hint:"This disables most dynamic conflict detection capabilities in exchange for performance, especially relevant on low-end systems. Note that this will significantly decrease the chance conflicts are detected. As such, it is recommended to turn this off when installing or updating packages."},"log-verbosity":{name:"Verbosity",hint:"The verbosity of libWrapper's Javascript console messages.",choices:{never:"Never",all:"All",trace:"Trace",debug:"Debug",info:"Information",warning:"Warning",error:"Error",critical:"Critical",always:"Always"}},menu:{title:"libWrapper Settings Menu",priorities:{name:"Priorities","package-inactive":"Inactive","statistics-disabled":"Note: Statistics collection is disabled, not able to show unprioritized packages.",prioritized:{title:"Prioritized Packages",hint:"These packages will be prioritized compared to any package not in this list.\nHigher positions in the list result in a higher priority."},unprioritized:{title:"Unprioritized Packages",hint:"These packages will be neither prioritized nor deprioritized.\nPriorities among these packages are decided on a first-come-first-served basis.\nNew packages will default to this list."},deprioritized:{title:"Deprioritized Packages",hint:"These packages will be deprioritized compared to any package not in this list.\nHigher positions in the list result in a higher priority.",note:"Note that packages that do not use libWrapper are deprioritized even compared to these."}},conflicts:{name:"Conflicts","none-detected":"No conflicts have been detected.","statistics-disabled":"Statistics collection is disabled.","show-ignored":"Show ignored conflicts"},"active-wrappers":{name:"Active Wrappers","none-active":"No wrappers are active right now."},about:{name:"About","full-name":"About libWrapper",credits:"{name} {version} by {author}.","credits-translation":"",description:"'libWrapper' is a library which provides package developers with a simple way to modify core Foundry VTT code, while reducing the likelihood of conflict with other packages.",info:'You can find more information about this module in the <a href="{repo_url}">Foundry VTT package repository</a>, as well as the project\'s <a href="{github_url}">Github page</a>.',support:"<b>If you encounter any issues</b>, the easiest way to find support is to ask the community. The largest community-provided support channels are:","issue-tracker":'If you encounter an <b>internal libWrapper error</b>, or are a <b>package developer</b>, you may also submit a support request in the <a href="{issues_url}">libWrapper Github Issue Tracker</a>.'},"warning-reset-priorities":"Resetting the package priorities will move all packages back to 'Unprioritized'. This action cannot be undone. Are you sure you want to continue?","warning-save":"It is recommended you reload this page to apply the new package priorities. Do you wish to reload?"}},packages:{"unknown-title":"Unknown","type-plus-id":"{type} {id}","type-plus-title":"{type} {title}",types:{module:"module",system:"system",world:"world script",unknown:"package"}},error:{"see-js-console":"(See JS Console)","tech-details":"== Technical Details:","community-support":"Ask the community for support:","not-lw":"This is *not* a libWrapper bug.",external:{notification:"{title}: Error detected in {type}.",message:"Error detected in {type} {title}.",info:"Find information about this {type} here: {url}",report:"Report this issue here: {url}","likely-not-updated":"It is likely this {type} has not been updated for FVTT {version}."},internal:{message:"Internal error detected.","message-with-package":"Internal error detected, involving {type} {title}.",info:"Find information about libWrapper here: {url}",report:"Report this issue here: {url}"},conflict:{potential:"{main} and {other} modify the same FoundryVTT functionality and are more likely to conflict.",confirmed:"Conflict detected between {main} and {other}.",info:"Find information about these packages here:",report:"Report this conflict here:"}},"support-channels":[{title:"FoundryVTT Discord's #modules-troubleshooting channel",url:"https://discord.gg/foundryvtt"},{title:"FoundryVTT Reddit",url:"https://www.reddit.com/r/FoundryVTT"}]}};const y=["en","es","ja","pt-BR","pt-PT"],k=import.meta?.url?.endsWith(`dist/${t}.js`)?"../lang":"./lang";class i18n{static async _fetch(e){if(Array.isArray(y)&&!y.includes(e))return null;try{const t=new URL(`${k}/${e}.json`,import.meta.url),r=await fetch(t);return 200===r.status&&r.ok?r.json():null}catch(e){return Log.warn$?.(`Failed to load or parse ${url.href}.`,e),null}}static async init(){this.jsons=[];const e=[];try{const t=c("core","language",!0,!1);t&&"en"!==t&&e.push(t)}catch(e){Log.debug$?.("Could not find or parse client language settings.")}const t=game?.i18n?.lang;if(t&&"en"!==t&&e.push(t),e.length>0){const t=await Promise.all(e.map((e=>this._fetch(e))));for(const e of t)e&&this.jsons.push(e)}}static on_ready(){delete this.jsons}static localize(e){if(game?.i18n){const t=game.i18n.localize(e);if(t!==e)return t}try{const t=e.split(".");if(this.jsons)for(const e of this.jsons){const r=t.reduce(((e,t)=>e?.[t]),e);if(r)return r}return t.reduce(((e,t)=>e?.[t]),b)??e}catch(t){return Log.error(t),e}}static format(e,t){if(game?.i18n){const r=game.i18n.format(e,t);if(r!==e)return r}const r=this.localize(e);if(r===e)return r;try{return r.replace(/\{(.*?)\}/g,((e,r)=>t?.[r]))}catch(t){return Log.error(t),e}}}Hooks.once("ready",i18n.on_ready.bind(i18n));const v=s("PackageType",["UNKNOWN","MODULE","SYSTEM","WORLD"]),E="«unknown»",W=new RegExp("^[a-z0-9_-]+$","i"),L=/^.*?\/(worlds|systems|modules)\/(.+?)(?=\/).*?$/gim;let I=t;const O=function(e,t,i){if(void 0!==t){if("string"!=typeof t)throw new Error(`${r}: Parameter 'stack_trace' must be a string, got ${typeof t}.`)}else{const e=Error.stackTraceLimit;try{Error.stackTraceLimit=1/0,t=Error().stack}finally{Error.stackTraceLimit=e}if("string"!=typeof t)return!0}if(!t)return!0;const n=t.matchAll(L);if(!n)return!0;for(const t of n){const n=t[1],a=t[2];if(!n||!a)continue;let s,o;if("worlds"===n){const e=globalThis.game?.data?.world?.id;if(e&&a!=e)continue;s=a,o=v.WORLD}else if("systems"===n){const e=globalThis.game?.data?.system?.id;if(e&&a!=e)continue;s=a,o=v.SYSTEM}else{if("modules"!==n)throw new Error(`${r}: Invalid script type: ${n}`);if(globalThis.game?.modules&&!globalThis.game.modules.has(a))continue;if(i&&(a===i||i?.includes?.(a)))continue;s=a,o=v.MODULE}if(!1===e(s,o,t[0]))return!1}return!0};class PackageInfo{static get UNKNOWN(){return new PackageInfo(E,v.UNKNOWN)}static collect_all(e=void 0,t=void 0,r=void 0){const i=new Set;O(((e,r,n)=>{const a=`${r.lower}:${e}`;return!!i.has(a)||(void 0!==t&&!t(e,r,n)||(i.add(a),!0))}),e,r);const n=[];for(const e of i)n.push(new PackageInfo(e));return n}static is_valid_key_or_id(e){return this.is_valid_key(e)||this.is_valid_id(e)}static is_valid_key(e){if(!e||"string"!=typeof e)return!1;const[t,r]=this.parse_key(e);return!(!t||!r)&&!!this.is_valid_id(t)}static is_valid_id(e){return!(!e||"string"!=typeof e)&&!!W.test(e)}static parse_key(e){const t=e.split(":");if(2!==t.length)return[null,null];return[t[1],v.get(t[0])]}constructor(e=null,t=null){this.set(e,t)}set(e=null,t=null,i=!0){if(!e)return this.detect_id();if("string"!=typeof e)throw new Error(`${r}: PackageInfo IDs must be strings`);if(e!==E){if(null!==t||!this.from_key(e,!1)){if(!this.constructor.is_valid_id(e))throw new Error(`${r}: Invalid package ID '${e}'`);if(null!==t&&!v.has(t))throw new Error(`${r}: Package type for '${e}' must belong to the PACKAGE_TYPES enum, but got '${t}'.`);this.id=e,this.type=t,t||this.detect_type(),i&&Object.freeze(this)}}else this.set_unknown()}set_unknown(){this.id=E,this.type=v.UNKNOWN}equals(e){return e&&e.constructor===this.constructor&&e.id===this.id&&e.type===this.type}detect_id(e=void 0){this.set_unknown(),O(((e,t)=>(this.set(e,t),!1)),e,I)}detect_type(){globalThis.game?.modules?globalThis.game.modules?.get(this.id)?.active?this.type=v.MODULE:this.id===globalThis.game.data?.system?.id?this.type=v.SYSTEM:this.id===globalThis.game.data?.world?.id?this.type=v.WORLD:this.type=v.UNKNOWN:this.id===t?this.type=v.MODULE:this.type=v.UNKNOWN}from_key(e,t=!0){const[i,n]=this.constructor.parse_key(e);if(!i||!n){if(t)throw new Error(`${r}: Invalid key '${e}'`);return!1}return this.set(i,n),!0}toString(){return this.key}get known(){return this.type!=v.UNKNOWN}get exists(){switch(this.type){case v.MODULE:return globalThis.game?.modules?.get(this.id)?.active;case v.SYSTEM:return globalThis.game?.data?.system?.id===this.id;case v.WORLD:return globalThis.game?.data?.world?.id===this.id;default:return!1}}get data(){if(!this.exists)return null;const e=globalThis.game?.release?.generation,t=e&&e>=10;switch(this.type){case v.MODULE:return t?globalThis.game?.modules?.get(this.id):globalThis.game?.modules?.get(this.id)?.data;case v.SYSTEM:return t?globalThis.game?.data?.system:globalThis.game?.data?.system?.data;case v.WORLD:return globalThis.game?.data?.world;default:return null}}static get unknown_title(){return i18n.localize(`${t}.packages.unknown-title`)}get title(){if(!this.exists)return this.constructor.unknown_title;switch(this.type){case v.MODULE:case v.SYSTEM:case v.WORLD:return this.data.title;default:return this.constructor.unknown_title}}get key(){return`${this.type.lower}:${this.id}`}get type_i18n(){return i18n.localize(`${t}.packages.types.${this.type.lower}`)}get type_plus_id(){return`${this.type.lower} ${this.id}`}get type_plus_id_capitalized(){let e=this.type_plus_id;return e.charAt(0).toUpperCase()+e.slice(1)}get type_plus_id_i18n(){return i18n.format(`${t}.packages.type-plus-id`,{type:this.type_i18n,id:this.id})}get type_plus_title(){return`${this.type.lower} ${this.title}`}get type_plus_title_i18n(){return i18n.format(`${t}.packages.type-plus-title`,{type:this.type_i18n,title:this.title})}get logId(){return this.type==v.MODULE?this.id:this.key}get settingsName(){switch(this.type){case v.MODULE:return this.id;case v.SYSTEM:return`${this.id} [System]`;case v.WORLD:return`${this.id} [World]`;default:return this.id}}get url(){return this.data?.url}get bugs(){return this.data?.bugs}get version(){return this.data?.version}get core_version_range(){const e=this.data;return e?e.compatibility?[e.compatibility.minimum,e.compatibility.verified,e.compatibility.maximum]:[e.minimumCoreVersion,e.compatibleCoreVersion,null]:null}get compatible_with_core(){const t=this.core_version_range,r=function(t=!0){const r=globalThis.game?.version??globalThis.game?.release?.version??globalThis.game?.data?.version??null;if(!t&&null===r)throw new e.internal("Unable to obtain the Foundry version");return r}(!0),i=r?.split(".")[0];if(!t||!r||!i)return!0;const[n,a,s]=t;if(n){const e=n.includes(".")?r:i;if(n!==e&&!isNewerVersion(e,n))return!1}if(a){const e=a.includes(".")?r:i;if(isNewerVersion(e,a))return!1}if(s){const e=s.includes(".")?r:i;if(e==s||isNewerVersion(e,s))return!1}return!0}}Object.freeze(PackageInfo);const R=eval;function A(e,t){try{e.displayName=t,Object.defineProperty(e,"name",{value:t,writable:!1,enumerable:!1,configurable:!0})}catch(e){}}function T(e,t=""){return""!==t?`🎁${e}#${t}`:`🎁${e}`}function N(e){const t=Object.getOwnPropertyNames(e);t.push(...Object.getOwnPropertySymbols(e));for(const r of t){const t=Object.getOwnPropertyDescriptor(e,r);"function"==typeof t.value&&A(t.value,T(r)),"function"==typeof t.get&&A(t.get,T(r,"getter")),"function"==typeof t.set&&A(t.set,T(r,"setter"))}e.prototype&&N(e.prototype)}function P(e){return null!=e&&"object"==typeof e&&("message"in e&&"stack"in e)}const z=["/listeners.js",T("call_wrapped"),T("Application.prototype._render")];function S(e,r=void 0){const i=function(e,r){return PackageInfo.collect_all(e,((e,r,i)=>{if(e!==t||r!==v.MODULE)return!0;for(const e of z)if(i.includes(e))return!1;return!0}),r)}(e,r),n=i.length;return n<=0?"[No packages detected]":1==n?`[Detected 1 package: ${i[0].logId}]`:`[Detected ${n} packages: ${i.map((e=>e.logId)).join(", ")}]`}function C(e,t){if(!(t in e))return!1;const r=Object.getOwnPropertyDescriptor(e,t);if(r){if(!("value"in r))return!1;if("string"!=typeof r.value)return!1;if(!r.writable)return!1}else{if("string"!=typeof e[t])return!1}return!0}function j(e,t=void 0){let r;try{if(!P(e))return;if(e.libwrapper_skip_package_detection)return;if(!function(e){return!Object.isFrozen(e)&&!(!C(e,"message")||!C(e,"stack"))}(e))return;if(r=S(e.stack),e.message.endsWith(r))return void(e.libwrapper_skip_package_detection=!0)}catch(e){Log.error("Exception thrown while attempting to inject package information into an error.",e)}try{const i=e.message;e.message+=`\n${r}`,e.stack=e.stack.replace(i,`${t}. ${e.message}`),e.libwrapper_skip_package_detection=!0}catch(e){Log.debug$?.("Exception thrown while modifying error object.",e)}}class LibWrapperError extends Error{get notification_verbosity(){return Log.ERROR}constructor(e,r,...i){super(r,...i),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.ui_msg=e,this.console_msg=r,j(this,this instanceof LibWrapperInternalError?null:t)}onUnhandled(){}}Object.freeze(LibWrapperError),e.base=LibWrapperError;class LibWrapperInternalError extends LibWrapperError{static construct_message(e,t){const i="lib-wrapper.error",n=`${i}.internal`,a=t.known?i18n.format(`${type.prefix}.message-with-package`,{type:t.type_i18n,title:t.title}):i18n.localize(`${n}.message`),s=i18n.format(`${n}.info`,{url:"https://github.com/ruipin/fvtt-lib-wrapper"}),o=i18n.format(`${n}.report`,{url:"https://github.com/ruipin/fvtt-lib-wrapper/issues"}),c=i18n.localize(`${i}.tech-details`),l=t.known?`Related Package ID= ${t.logId}\n`:"";return[`${r}: ${a}`,`${a}\n\n${s}\n${o}\n\n${c}\nInternal libWrapper error.\n${l}Error= ${e}\n`]}constructor(e,...t){const r=new PackageInfo,[i,n]=LibWrapperInternalError.construct_message(e,r);super(i,n,...t),this.package_info=r}get package_id(){return this.package_info?.id}}Object.freeze(LibWrapperInternalError),e.internal=LibWrapperInternalError;class LibWrapperPackageError extends LibWrapperError{static get_community_support_message(){const e=[],r=`${t}.support-channels`,i=i18n.localize(r);if(Array.isArray(i))for(const t of i)"title"in t&&"url"in t&&e.push(`- ${t.title}: ${t.url}`);return e.length>0?e.join("\n"):null}static construct_message(t,r){const i="lib-wrapper.error",n=`${i}.external`,a=r.title,s=r.type_i18n;let o=i18n.format(`${n}.notification`,{title:a,type:s}),c=i18n.format(`${n}.message`,{title:a,type:s});if(!r.compatible_with_core){const t=function(t=!0){const r=globalThis.game?.release?.display??globalThis.game?.version??globalThis.game?.data?.version??null;if(!t&&null===r)throw new e.internal("Unable to obtain the Foundry display version");return r}(!0);if(t){const e=` ${i18n.format(`${n}.likely-not-updated`,{type:s,version:t})}`;o+=e,c+=e}}let l=`${c}\n\n${i18n.localize(`${i}.not-lw`)}\n\n`;const p=r.url,d="string"==typeof p;d&&(l+=i18n.format(`${n}.info`,{type:s,url:p}));const u=r.bugs;if("string"==typeof u)d&&(l+="\n"),l+=i18n.format(`${n}.report`,{url:u});else{const e=this.get_community_support_message();e&&(d&&(l+="\n\n"),l+=i18n.localize(`${i}.community-support`),l+="\n",l+=e)}return l+="\n\n",l+=i18n.localize(`${i}.tech-details`),l+=`\nDetected by libWrapper.\nPackage ID= ${r.logId}\nError= ${t}\n`,[o,l]}constructor(e,t,...r){t?t?.constructor!==PackageInfo&&(t=new PackageInfo(t)):t=new PackageInfo;const[i,n]=LibWrapperPackageError.construct_message(e,t);super(i,n,...r),this.package_info=t}get package_id(){return this.package_info?.id}}function D(e,r=void 0){try{return game?.settings?.get(t,e)}catch(e){if(void 0!==r)return r;throw e}}function x(){const e=function(e=!1){const t=globalThis.game?.user?.isGM;if(void 0!==t)return t;const r=o(e);return r?4===r.role:null}(!0);return null===e||D(e?"notify-issues-gm":"notify-issues-player",!0)}Object.freeze(LibWrapperPackageError),e.package=LibWrapperPackageError;const U={[Log.INFO.value]:"info",[Log.WARNING.value]:"warn",[Log.ERROR.value]:"error"};class LibWrapperNotifications{static get ui_notifications_enabled(){try{if(!x())return!1}catch(e){return Log.error("Could not decide whether to show notifications or not. Defaulting to 'yes'.\n",e),!0}return!0}static init(){this.NOTIFICATION_SET=new Set,Object.seal(this)}static _ui(t,i=Log.ERROR,n=!0){if(!this.ui_notifications_enabled)return;const a=globalThis?.ui?.notifications;if(!a)return;const s=function(t){if("string"!=typeof t)throw e.internal("Parameter 'str' must be a string.");const r=t.length;let i=0;for(let e=0;e<r;e++)i=(i<<5)-i+t.charCodeAt(e),i&=i;return i}(t);if(this.NOTIFICATION_SET.has(s))return;this.NOTIFICATION_SET.add(s);const o=w(i,U,"error");a[o].call(a,n?`${r}: ${t}`:t,{permanent:"error"==o})}static ui(...e){globalThis.game?.ready?this._ui(...e):Hooks.once("ready",this._ui.bind(this,...e))}static console_ui(e,t,r=Log.ERROR,...i){const n=Log.fn(r);n&&(n(`${e}\n${t}`,...i),e+=` ${i18n.localize("lib-wrapper.error.see-js-console")}`),this.ui(e,r)}static conflict(e,t,r,i){let n;n=Array.isArray(t)?t.length>1?`[${t.map((e=>e.type_plus_title_i18n)).join(", ")}]`:t[0].type_plus_title_i18n:t.type_plus_title_i18n;const a={main:e.type_plus_title_i18n,other:n};this.console_ui(r?i18n.format("lib-wrapper.error.conflict.potential",a):i18n.format("lib-wrapper.error.conflict.confirmed",a),i,r?Log.WARNING:Log.ERROR)}}N(LibWrapperNotifications);class LibWrapperStats{static _collect_stats(){try{return function(e,t=!1){const r=globalThis.game?.user?.can;if(r)return r.call(game.user,e);const i=o(t);if(!i)return null;if(4===i.role)return!0;if(e in i.permissions)return i.permissions[e];const n=globalThis.game?.data?.settings?.find((e=>"core.permissions"===e.key));if(n?.value){const t=JSON.parse(n.value)[e];if(t&&t.includes(i.role))return!0}return!1}("SETTINGS_MODIFY")}catch(e){return LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not read user permissions during initialization.\n",Log.WARNING,e),!0}}static init(){this.collect_stats=this._collect_stats(),this.collect_stats&&(this.PACKAGES=new Set,this.CONFLICTS=new Map,Object.seal(this))}static register_package(e){this.collect_stats&&e.id!=t&&this.PACKAGES.add(e.key)}static register_conflict(e,t,r,i){if(!this.collect_stats)return;const n=`${e.key}/${t.key}`;let a=this.CONFLICTS.get(n);a||(a={count:0,ignored:0,package_info:e,other_info:t,targets:new Map},this.CONFLICTS.set(n,a));const s=r.name;let o=a.targets.get(s);o||(o={count:0,ignored:0},a.targets.set(s,o)),i?(a.ignored++,o.ignored++):(a.count++,o.count++)}static get conflicts(){return this.CONFLICTS}static get packages(){return this.PACKAGES}}class IgnoredConflictEntry{constructor(e,t,r){this.ignore_infos=new Set(e.map((e=>e.key))),this.targets=new Set(t),this.ignore_errors=r,Object.seal(this)}is_ignored(e,t,r){if(!r&&!this.ignore_errors)return!1;if(!this.ignore_infos.has(e.key))return!1;return void 0!==t.names.find((e=>this.targets.has(e)))}}class LibWrapperConflicts{static init(){this.IGNORED=new Map,Object.seal(this)}static register_ignore(e,t,r,i){const n=new IgnoredConflictEntry(t,r,i),a=e.key;let s=this.IGNORED.get(a);s||(s=[],this.IGNORED.set(a,s)),s.push(n)}static clear_ignores(){this.IGNORED.clear()}static _is_ignored_oneway(e,t,r,i){const n=e.key,a=this.IGNORED.get(n);if(!a)return!1;for(const e of a)if(e.is_ignored(t,r,i))return!0;return!1}static _is_ignored(e,t,r,i){return this._is_ignored_oneway(e,t,r,i)||this._is_ignored_oneway(t,e,r,i)}static register_conflict(t,r,n,a,s){if(!r)return!1;if(Array.isArray(r)){let e=!1;return r.forEach((r=>{e|=this.register_conflict(t,r,n,a,s)})),e}if(t.constructor!==PackageInfo)throw new e.internal(`LibWrapperConflicts.register_conflict: 'package_info' must be a PackageInfo object, but got '${t}'.`);if(r.constructor!==PackageInfo)throw new e.internal(`LibWrapperConflicts.register_conflict: 'other_info' must be a PackageInfo object, but got '${r}'.`);if(null!=a&&"string"!=typeof a)throw new e.internal(`LibWrapperConflicts.register_conflict: 'target' must be a string, or null, but got '${a}'.`);if("boolean"!=typeof s)throw new e.internal(`LibWrapperConflicts.register_conflict: 'is_warning' must be a boolean, but got '${s}'.`);let o=!1;return!o&&this._is_ignored(t,r,n,s)&&(o=!0,Log.debug$?.(`Conflict between ${t.type_plus_id} and ${r.type_plus_id} over '${n.name}' ignored through 'ignore_conflicts' API.`)),o||!1!==Hooks.call(`${i}.ConflictDetected`,t.id,r.id,a,n.frozen_names)||(o=!0,Log.debug$?.(`Conflict between ${t.type_plus_id} and ${r.type_plus_id} over '${n.name}' ignored, as 'libWrapper.ConflictDetected' hook returned false.`)),LibWrapperStats.register_conflict(t,r,n,o),!o}}class LibWrapperAlreadyOverriddenError extends LibWrapperError{static construct_message(e,t,i){const n="lib-wrapper.error",a=`${n}.conflict`,s=e.type_plus_title_i18n,o=s.charAt(0).toUpperCase()+s.slice(1),c=t.type_plus_title_i18n,l=c.charAt(0).toUpperCase()+c.slice(1),p=i18n.format(`${a}.confirmed`,{main:s,other:c});let d=`${r}: ${p}`,u=`${p}\n\n${i18n.localize(`${n}.not-lw`)}\n\n`,h="";const g=e.url;"string"==typeof g&&(h+=`\n- ${o}: ${g}`);const f=t.url;"string"==typeof f&&(h+=`\n- ${l}: ${f}`),h&&(u+=`${i18n.localize(`${a}.info`)}${h}\n\n`);let _="";const w=e.bugs;"string"==typeof w&&(_+=`\n- ${o}: ${w}`);const m=t.bugs;"string"==typeof m&&(_+=`\n- ${l}: ${m}`),_&&(u+=`${i18n.localize(`${a}.report`)}${_}\n\n`);const b=LibWrapperPackageError.get_community_support_message();return b&&(u+=i18n.localize(`${n}.community-support`),u+="\n",u+=b,u+="\n\n"),u+=i18n.localize(`${n}.tech-details`),u+=`\nDetected by libWrapper.\nPackage IDs= ${e.logId}, ${t.logId}\nError= ${i}\n`,[d,u]}constructor(e,t,r,i,...n){e?.constructor!==PackageInfo&&(e=new PackageInfo(e)),t?.constructor!==PackageInfo&&(t=new PackageInfo(t));const[a,s]=LibWrapperAlreadyOverriddenError.construct_message(e,t,`Failed to wrap '${i}' for ${e.type_plus_id} with type OVERRIDE. An OVERRIDE wrapper for the same method has already been registered by ${t.type_plus_id}.`);super(a,s,...n),this.package_info=e,this.conflicting_info=t,this.target=i,this._wrapper=r}get package_id(){return this.package_info?.id}get module(){return this.package_id}get conflicting_id(){return this.conflicting_info?.id}get conflicting_module(){return this.conflicting_id}onUnhandled(){super.onUnhandled(),LibWrapperConflicts.register_conflict(this.package_info,this.conflicting_info,this._wrapper,this.target,!1)}}Object.freeze(LibWrapperAlreadyOverriddenError),e.already_overridden=LibWrapperAlreadyOverriddenError;class LibWrapperInvalidWrapperChainError extends LibWrapperPackageError{constructor(e,t,r,...i){t?.constructor!==PackageInfo&&(t=new PackageInfo(t)),super(r,t,...i),this._wrapper=e}}Object.freeze(LibWrapperInvalidWrapperChainError),e.invalid_chain=LibWrapperInvalidWrapperChainError,Error.stackTraceLimit=1/0;const F=function(e,t=void 0){try{if(!P(e))return;e instanceof LibWrapperError&&function(e){e.ui_msg&&e.notification_verbosity&&LibWrapperNotifications.ui(`${e.ui_msg} ${i18n.localize("lib-wrapper.error.see-js-console")}`,e.notification_verbosity,!1),e.onUnhandled&&e.onUnhandled.apply(e)}(e),function(e,t){j(e,t)}(e,t)}catch(e){Log.error("Exception thrown while processing an unhandled error.",e)}},M=function(e){try{const t=e.reason??e.error??e;return F(t)}catch(e){Log.error("Exception thrown while processing an unhandled error event.",e)}};const G="1.12.13.0",V=1,H=12,Y=13,B=0,K="",Z="71276d1e0c3070d20f97dd65cb1907ce48e9ee78",q="1.12.13.0 (71276d1)",X=function(e,t=0,r=0,i=0){return V==e?H==t?Y==r?B==i:Y>=r:H>t:V>e},J=s("WrapperType",{WRAPPER:1,MIXED:2,OVERRIDE:3}),Q=s("PerformanceMode",{NORMAL:1,AUTO:2,FAST:3});const ee=new class WrapperStorage{constructor(){this.clear()}index_for_id(e){return Math.floor(e/2)}index_for_wrapper(e){return this.index_for_id(e.getter_id)}get_next_id_pair(){return[this.next_id++,this.next_id++]}_delete(e){this.data.delete(e)}_set(e,t){if(null==t)return this._delete(e);const r=new WeakRef(t);this.data.set(e,r)}_deref(e,t){const r=t?.deref();return r||this._delete(e),r}_get(e){const t=this.data.get(e);return this._deref(e,t)}exists(t,r=void 0){void 0===r&&(r=this.index_for_wrapper(t));const i=this._get(r);if(i){if(i!==t)throw new e.internal(`Sanity check failed: The WrapperStorage index ${r} does not contain the wrapper object '${t.name}'.`);return!0}return!1}add(e){const t=this.index_for_wrapper(e);this.exists(e,t)||this._set(t,e)}remove(e){const t=this.index_for_wrapper(e);this.exists(e,t)&&this._delete(t)}clear(){this.data=new Map,this.next_id=0}*wrappers(){for(const[e,t]of this.data.entries()){const r=this._deref(e,t);r&&(yield r)}}forEach(e){for(const t of this.wrappers())e(t)}find(e){for(const t of this.wrappers())if(e(t))return t}find_by_id(e){const t=this.index_for_id(e);return this._get(t)}};class Wrapper{get_id(e=!1){return e?this.setter_id:this.getter_id}get name(){return this.names[0]}get frozen_names(){return Object.freeze(this.names),this.names}get_name(e=!1){return e?`${this.name}#set`:this.name}get_names(e=!1){return e?this.names.map((e=>`${e}#set`)):this.frozen_names}_add_name(e){this.names.includes(e)||(Object.isFrozen(this.names)&&(this.names=this.names.slice()),this.names.push(e))}_callstack_name(e,t=this.name){return T(t,e)}constructor(t,r,i=void 0,n=void 0){this.fn_name=r,this.object=t;let a=Object.getOwnPropertyDescriptor(t,r);if(a){if(a.get?._lib_wrapper){const t=a.get?._lib_wrapper;if(!(t instanceof this.constructor))throw new e.internal(`'${i}' cannot be wrapped, the descriptor already has a wrapper, but of an unexpected class ('${t.constructor.name}' vs '${this.constructor.name}').`);return t._add_name(i),t}if(!1===a.configurable)throw new e.package(`'${i}' cannot be wrapped, the corresponding descriptor has 'configurable=false'.`,n);a.get?(this.is_property=!0,this._wrapped_getter=a.get,this._wrapped_setter=a.set):(this.is_property=!1,this._wrapped=a.value)}else{if(a=this._get_inherited_descriptor(),!a)throw new e.package(`Can't wrap '${i}', target does not exist or could not be found.`,n);const t=a.get?._lib_wrapper;t?this.is_property=t.is_property:a.get??a.set?this.is_property=!0:this.is_property=!1}[this.getter_id,this.setter_id]=ee.get_next_id_pair(),this.names=[],this.getter_data=[],this.is_property&&(this.setter_data=[]),this.active=!1,this._outstanding_wrappers=0,this.is_property||(this._current_handler_id=0,this._pending_wrapped_calls=[],this._pending_wrapped_calls_cnt=0),this.use_static_dispatch=!1,i||(i=r),this._add_name(i),this._wrap()}_get_handler(){if(this.is_property)throw new e.internal("Unreachable: _get_handler with is_property=false");const t=this._current_handler_id;if(t===this._cached_handler_id)return this._cached_handler;const r=this,i=this._callstack_name(t),n=this._wrapped??null,a={[i]:function(...e){const i=r.use_static_dispatch;return r.should_skip_wrappers(this,t,i)?r.get_wrapped(this,!1,n).apply(this,e):i?r.get_static_dispatch_chain(this).apply(this,e):r.call_wrapper(null,this,...e)}}[i];return a.toString=function(){return"/* WARNING: libWrapper wrappers present! */\n"+r.get_wrapped(this).toString()},this._cached_handler=a,this._cached_handler_id=t,a}should_skip_wrappers(t,r,i){if(r==this._current_handler_id)return!1;if(r>this._current_handler_id)throw new e.internal(`Unreachable: handler_id=${r} > this._current_handler_id=${this._current_handler_id}`);if(!this.is_property){if(this._pending_wrapped_calls_cnt<=0)return!1;if(!i){if(this._pending_wrapped_calls.indexOf(t)<0)return!1}}return!0}skip_existing_handlers(){this._current_handler_id++}_get_static_dispatch_chain_cache(e){return this._static_dispatch_weakmap?.get(e)??this._static_dispatch_strongmap?.get(e)}_set_static_dispatch_chain_cache(e,t){try{this._static_dispatch_weakmap||(this._static_dispatch_weakmap=new WeakMap),this._static_dispatch_weakmap.set(e,t)}catch{this._static_dispatch_strongmap||(this._static_dispatch_strongmap=new Map),this._static_dispatch_strongmap.set(e,t)}}clear_static_dispatch_chain_cache(){this._static_dispatch_weakmap?.clear?this._static_dispatch_weakmap.clear():delete this._static_dispatch_weakmap,this._static_dispatch_strongmap?.clear()}get_static_dispatch_chain(t){if(this.is_property)throw new e.internal("Unreachable: get_static_dispatch_chain with is_property=false");let r=this._get_static_dispatch_chain_cache(t);if(!r){r=this.call_wrapped.bind(this,null,t);const e=this.get_fn_data(!1);for(let i=e.length-1;i>=0;i--){const n=e[i],a=n.fn;r=n.chain?a.bind(t,r,...n.bind??[]):a.bind(t,...n.bind??[])}this._set_static_dispatch_chain_cache(t,r)}return r}_calc_use_static_dispatch(){if(this.is_property)return!1;let e=Q.AUTO;const t=this.get_fn_data(!1);for(const r of t)if(r.perf_mode)if(e===Q.AUTO)e=r.perf_mode;else if(e!==r.perf_mode){e=Q.AUTO;break}return e===Q.AUTO&&(e=D("high-performance-mode",!1)?Q.FAST:Q.NORMAL),e===Q.FAST}update_use_static_dispatch(){this.use_static_dispatch=this._calc_use_static_dispatch()}_wrap(){if(this.active)return;const e=this._callstack_name("getter"),t=this._callstack_name("setter"),r=this;let i;i=this.is_property?{[e]:function(...e){return r.call_wrapper(null,this,...e)},[t]:function(...e){return r.call_wrapper({setter:!0},this,...e)}}:{[e]:r._get_handler.bind(r),[t]:function(e){return r.set_nonproperty(e,this)}};const a=i[e],s=i[t];a._lib_wrapper=this,Object.defineProperty(this.object,this.fn_name,{get:a,set:s,configurable:n}),this.active=!0,Log.debug$?.(`Wrapped '${this.name}'.`)}unwrap(){if(this.active)throw new e.internal(`${r}: Cannot unwrap when PROPERTIES_CONFIGURABLE==false`)}_get_inherited_descriptor(){let e=Object.getPrototypeOf(this.object);for(;e;){const t=Object.getOwnPropertyDescriptor(e,this.fn_name);if(t)return t;e=Object.getPrototypeOf(e)}return null}get_wrapped(t,r=!1,i=void 0){let n;if(n=void 0!==i?i:this.is_property?r?this._wrapped_setter:this._wrapped_getter:this._wrapped,null===n&&(n=void 0),void 0===n){const i=this._get_inherited_descriptor();if(i)if(this.is_property){if(!i.get&&!i.set)throw new e.internal("This wrapper is set up to wrap a property, but the inherited descriptor is a method.");n=r?i.set:i.get}else n=i.value??i.get.apply(t)}return void 0===n&&Log.warn$?.(`There is no wrapped method for '${this.name}', returning 'undefined'.`),n}call_wrapped(e,t,...r){e&&this._call_wrapper_update_state(e);const i=e?.setter??!1,n=!!e;let a,s;this.is_property||(this._pending_wrapped_calls_cnt++,n&&(a=t,this._pending_wrapped_calls.push(a)));try{const e=this.get_wrapped(this.object,i);s=e?.apply(t,r)}catch(e){throw this.is_property||this._cleanup_call_wrapped(a,n),e}return this.is_property||("function"==typeof s?.then?s=s.then((e=>(this._cleanup_call_wrapped(a,n),e)),(e=>{throw this._cleanup_call_wrapped(a,n),e})):this._cleanup_call_wrapped(a,n)),s}_cleanup_call_wrapped(t,r){if(this._pending_wrapped_calls_cnt<=0)throw new e.internal(`this._pending_wrapped_calls_cnt=${this._pending_wrapped_calls_cnt} should be unreachable at this point.`);if(this._pending_wrapped_calls_cnt--,r){const r=this._pending_wrapped_calls.indexOf(t);if(r<0)throw new e.internal("Could not find 'pend' inside 'this._pending_wrapped_calls'.");this._pending_wrapped_calls.splice(r,1)}}call_wrapper(t,r,...i){t&&this._call_wrapper_update_state(t);const n=t?.index??0,a=t?.setter??!1,s=t?.fn_data??this.get_fn_data(a),o=s[n];if(!o){if(s.length>0)throw new e.internal(`Must not have 'data===${o}' when 'fn_data.length==${s.length}'.`);return this.call_wrapped(t,r,...i)}const c=o.fn;if(!o.chain)return c.apply(r,...o.bind??[],i);const l=n+1,p=l>=s.length,d={index:l,called:!1,valid:!0,setter:a,prev_data:o,fn_data:s},u=p?this.call_wrapped.bind(this,d,r):this.call_wrapper.bind(this,d,r);let h;this._outstanding_wrappers++;try{h=c.call(r,u,...o.bind??[],...i)}catch(e){return this._cleanup_call_wrapper_thrown(d,e)}return h="function"==typeof h?.then?h.then((e=>this._cleanup_call_wrapper(e,d,o,s,u,r,i)),(e=>this._cleanup_call_wrapper_thrown(d,e))):this._cleanup_call_wrapper(h,d,o,s,u,r,i),h}_call_wrapper_update_state(t){if(!1===t.valid)throw new e.invalid_chain(this,t.prev_data?.package_info,`This wrapper function for '${this.name}' is no longer valid, and must not be called.`);t.called=!0}_invalidate_state(t){if(t.valid=!1,this._outstanding_wrappers--,this._outstanding_wrappers<0)throw new e.internal(`Outstanding wrappers = ${this._outstanding_wrappers}, should never fall below 0.`)}_cleanup_call_wrapper_thrown(e,t){throw this._invalidate_state(e),t}_cleanup_call_wrapper(t,r,i,n,a,s,o){try{if(!r.called){let c=!i.warned_conflict||LibWrapperStats.collect_stats,l=null,p=!1,d=!1;if(c&&(l=n.slice(r.index).filter((e=>!e.package_info.equals(i.package_info))).map((e=>e.package_info)),p=0==l.length,p||(d=LibWrapperConflicts.register_conflict(i.package_info,l,this,null,!0))),i.type===J.WRAPPER){const r=new e.package(`The wrapper for '${i.target}' registered by ${i.package_info.type_plus_id} with type WRAPPER did not chain the call to the next wrapper, which breaks a libWrapper API requirement. This wrapper will be unregistered.`,i.package_info);F(r),Log.error$?.(r),globalThis.libWrapper.unregister(i.package_info.id,this.get_id(i.setter)),p||(t=a.apply(s,o))}else d&&!i.warned_conflict&&(LibWrapperNotifications.conflict(i.package_info,l,!0,`${i.package_info.type_plus_id_capitalized} did not chain the wrapper for '${i.target}'.`),i.warned_conflict=!0)}}finally{this._invalidate_state(r)}return t}set_nonproperty(t,r=null){if(this.is_property)throw new e.internal("Must not call 'set_nonproperty' for a property wrapper.");r!==this.object?Object.defineProperty(r,this.fn_name,{value:t,configurable:!0,enumerable:!0,writable:!0}):(this._wrapped=t,this.skip_existing_handlers(),this.warn_classic_wrapper())}get_affected_packages(){return this.getter_data.map((e=>e.package_info))}warn_classic_wrapper(){const e=new PackageInfo,t=this.get_affected_packages();if(t.length>0){LibWrapperConflicts.register_conflict(e,t,this,null,!0)&&(LibWrapperNotifications.conflict(e,t,!0,`Detected non-libWrapper wrapping of '${this.name}' by ${e.type_plus_id}. This will potentially lead to conflicts.`),Log.trace())}this.detected_classic_wrapper||(this.detected_classic_wrapper=[]),this.detected_classic_wrapper.push(e.key)}get_fn_data(t,r=!1){if(t&&!this.is_property)throw new e.internal(`'${this.name}' does not wrap a property, thus setter=true is illegal.`);const i=t?"setter_data":"getter_data";let n=this[i];return r&&this._outstanding_wrappers>0&&(n=this[i].slice(0),this[i]=n),n}_post_update_fn_data(){this.update_use_static_dispatch(),this.clear_static_dispatch_chain_cache()}sort(){for(let e of[!1,!0]){if(e&&!this.is_property)continue;this.get_fn_data(e).sort(((e,t)=>e.type.value-t.type.value||t.priority-e.priority))}}add(e){const t=e.fn;t.name&&"anonymous"!==t.name||A(t,this._callstack_name(e.package_info.id??"<unknown>"));this.get_fn_data(e.setter,!0).splice(0,0,e),this.sort(e.setter),this._post_update_fn_data()}remove(e){const t=this.get_fn_data(e.setter,!0),r=t.indexOf(e);t.splice(r,1),this._post_update_fn_data()}clear(){this.getter_data=[],this.is_property&&(this.setter_data=[]),this._post_update_fn_data()}is_empty(){return!this.getter_data.length&&!this.setter_data?.length}}N(Wrapper),Object.freeze(Wrapper);const te=new Map;function re(e,t){return!!PackageInfo.is_valid_key_or_id(e)&&(!!t&&("string"==typeof t.id&&"string"==typeof t.title&&"number"==typeof t.index))}const ie=function(e=null){te.clear();const r=e??game?.settings?.get(t,"module-priorities");if(r)for(let e of["prioritized","deprioritized"]){const t=r[e];if(!t)continue;const i="prioritized"==e?1e4:-1e4;Object.entries(t).forEach((e=>{let[t,r]=e;re(t,r)?te.has(t)||te.set(t,i-r.index):Log.warn$?.(`Ignoring '${t}' entry while loading module priorities due to invalid format.`)}))}};class LibWrapperSettings extends FormApplication{static init(){game.settings.register(t,"notify-issues-gm",{name:`${t}.settings.notify-issues-gm.name`,hint:`${t}.settings.notify-issues-gm.hint`,default:!0,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"notify-issues-player",{name:`${t}.settings.notify-issues-player.name`,hint:`${t}.settings.notify-issues-player.hint`,default:!1,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"high-performance-mode",{name:`${t}.settings.high-performance-mode.name`,hint:`${t}.settings.high-performance-mode.hint`,default:!1,type:Boolean,scope:"world",config:!0}),game.settings.register(t,"log-verbosity",{name:`${t}.settings.log-verbosity.name`,hint:`${t}.settings.log-verbosity.hint`,default:Log.WARNING.value,type:Number,choices:{0:i18n.localize(`${t}.settings.log-verbosity.choices.all`),[Log.DEBUG.value]:i18n.localize(`${t}.settings.log-verbosity.choices.debug`),[Log.INFO.value]:i18n.localize(`${t}.settings.log-verbosity.choices.info`),[Log.WARNING.value]:i18n.localize(`${t}.settings.log-verbosity.choices.warning`)},scope:"client",config:!0,onChange:e=>Log.init(!0)}),game.settings.registerMenu(t,"menu",{name:"",label:`${t}.settings.menu.title`,icon:"fas fa-cog",type:LibWrapperSettings,restricted:!0}),game.settings.register(t,"module-priorities",{name:"",default:{},type:Object,scope:"world",config:!1,onChange:e=>ie()}),this.show_ignored_conflicts=!1,Log.init(),ie(),Object.seal(this)}static get defaultOptions(){return{...super.defaultOptions,template:`modules/${t}/templates/settings.html`,height:700,title:i18n.localize(`${t}.settings.menu.title`),width:600,classes:[t,"settings"],tabs:[{navSelector:".tabs",contentSelector:"form",initial:"name"}],submitOnClose:!1,closeOnSubmit:!1}}constructor(e={},t){super(e,t)}static showYesNoDialog(e,r){new Dialog({content:e,buttons:{yes:{icon:'<i class="fas fa-check"></i>',label:i18n.localize(`${t}.settings.yes`),callback:r},no:{icon:'<i class="fas fa-times"></i>',label:i18n.localize(`${t}.settings.no`)}}}).render(!0)}getActiveWrappers(){let e=[];return ee.forEach((r=>{for(let i of[!1,!0]){if(i&&!r.is_property)continue;const n=[];if(r.get_fn_data(i).forEach((e=>{if(e.package_info.id==t)return;const r={name:e.package_info.settingsName,type:e.type.name,perf_mode:e.perf_mode.name};"AUTO"==r.perf_mode?r.perf_mode=null:r.perf_mode=`, ${r.perf_mode}`,n.push(r)})),r.detected_classic_wrapper&&r.detected_classic_wrapper.forEach((e=>{n.push({name:new PackageInfo(e).settingsName,type:"MANUAL",perf_mode:null})})),n.length<=0)continue;const a=r.get_id(i),s=r.get_names(i);e.push({id:a,name:s[0],names:s.slice(1),packages:n})}})),e.sort(((e,t)=>t.packages.length-e.packages.length)),e}getConflicts(){if(!LibWrapperStats.collect_stats)return null;let e=[];return LibWrapperStats.conflicts.forEach((t=>{let r=t.count;if(this.show_ignored_conflicts&&(r+=t.ignored),0==r)return;const i=[];e.push({count:t.count,ignored:this.show_ignored_conflicts?t.ignored:0,total:r,package_id:t.package_info.settingsName,other_id:t.other_info.settingsName,targets:i}),t.targets.forEach(((e,t)=>{let r=e.count;this.show_ignored_conflicts&&(r+=e.ignored),r>0&&i.push({target:t,count:e.count,total:r,ignored:this.show_ignored_conflicts?e.ignored:0})})),i.sort(((e,t)=>e.total-t.total))})),e.sort(((e,t)=>e.total-t.total)),e}getPackages(){let e={prioritized:[],normal:[],deprioritized:[]};const r=game.settings.get(t,"module-priorities"),i=r.prioritized??{},n=r.deprioritized??{},a=i18n.localize(`${t}.settings.menu.priorities.package-inactive`);return LibWrapperStats.collect_stats&&(LibWrapperStats.packages.forEach((t=>{const r=new PackageInfo(t);r.key in i||r.key in n||e.normal.push(r)})),e.normal.sort(((e,t)=>e.id.localeCompare(t.id)))),Object.entries(i).forEach((t=>{let[r,i]=t;re(r,i)?e.prioritized.push({key:r,id:i.id,title:i.title??`${i.title} <${a}>`,index:i.index}):Log.warn$?.(`Ignoring '${r}' entry while loading module priorities due to invalid format.`)})),e.prioritized.sort(((e,t)=>e.index-t.index)),Object.entries(n).forEach((t=>{let[r,n]=t;r in i||(re(r,n)?e.deprioritized.push({key:r,id:n.id,title:n.title??`${n.title} <${a}>`,index:n.index}):Log.warn$?.(`Ignoring '${r}' entry while loading module priorities due to invalid format.`))})),e.deprioritized.sort(((e,t)=>e.index-t.index)),e}getData(){const e=[];{const r=`${t}.support-channels`,i=i18n.localize(r);if(Array.isArray(i))for(const t of i)"title"in t&&"url"in t&&e.push(t)}return{about:{name:r,version:q,collect_stats:LibWrapperStats.collect_stats,translation_credits:i18n.localize(`${t}.settings.menu.about.credits-translation`),support:e},wrappers:this.getActiveWrappers(),conflicts:this.getConflicts(),packages:this.getPackages(),show_ignored_conflicts:this.show_ignored_conflicts}}activateListeners(e){super.activateListeners(e);let r=this;e.find(".caret.has-nested").on("click",(function(e){const t=$(this);t.parent().find(".nested").toggleClass("active"),t.toggleClass("caret-down")})),e.find("button.reload").on("click",(function(e){r.render(!0)})),e.find(".lw-show-ignored-conflicts").on("change",(function(e){const t=$(this).find("input[type=checkbox]").prop("checked");r.show_ignored_conflicts=t,r.render(!0)})),e.find(".package-priority-group").on("click",(function(e){const t=$(this).find("select");t.is(":focus")||t.focus()})),e.find("button.change-priority").on("click",(function(t){const r=$(this),i=r.data("which"),n="up"===r.data("direction"),a=e.find(`.${i}`).find("option:selected"),s=n?a.prev():a.next();s.length&&(n?s.before(a):s.after(a))})),e.find("button.change-category").on("click",(function(t){const r=$(this),i=r.data("from"),n=r.data("to"),a=e.find(`.${i}`),s=e.find(`.${n}`),o=a.find("option:selected");let c=o.next();if(0==c.length&&(c=o.prev()),s.append(o),"packages-normal"==n){const e=s.find("option");e.sort(((e,t)=>$(e).val()>$(t).val()?1:-1)),s.empty().append(e)}c.length&&a.val(c.val()),a.focus()})),e.find(".submit").on("click",(function(t){for(let t of["packages-prioritized","packages-deprioritized"]){const r=e.find(`.${t}`).find("option");let i=[];r.each(((e,t)=>{i.push($(t).val())})),$("<input>").attr("type","hidden").attr("name",`${t}-hidden`).attr("value",i.join(",")).appendTo(e)}e.submit()})),e.find(".reset").on("click",(function(r){$("input[type=hidden]").remove(),LibWrapperSettings.showYesNoDialog(`<p>${i18n.localize(`${t}.settings.menu.warning-reset-priorities`)}</p>`,(()=>{for(let t of["packages-prioritized","packages-deprioritized"])$("<input>").attr("type","hidden").attr("name",`${t}-hidden`).attr("value","").appendTo(e);e.submit()}))}))}async _updateObject(e,r){const i=game.settings.get(t,"module-priorities");for(let e of["prioritized","deprioritized"]){const t=`packages-${e}-hidden`;if(!(t in r))continue;const n=r[t],a=""===n?[]:n.split(",");let s=i[e]??{},o={},c=0;a.forEach((e=>{if(!e)return;const t=s[e],r=new PackageInfo(e);o[e]={id:r.id,title:r.exists?r.title:t.title,index:c++}})),i[e]=o}Object.keys(i.deprioritized).forEach((e=>{e in i.prioritized&&delete i.deprioritized[e]})),await game.settings.set(t,"module-priorities",i),this.render(!0),LibWrapperSettings.showYesNoDialog(`<p>${i18n.localize(`${t}.settings.menu.warning-save`)}</p>`,(()=>location.reload()))}}let ne=!1,ae=!0;const se=new RegExp(["(","[^.[]+","|","\\[","(","'","(","[^'\\\\]","|","\\\\.",")+?","'","|",'"',"(",'[^"\\\\]',"|","\\\\.",")+?",'"',")","\\]",")"].join(""),"g"),oe=new RegExp(["(","^\\['","|","'\\]$","|",'^\\["',"|",'"\\]$',")"].join(""),"g");function ce(e){let t=e.endsWith("#set");return[t?e.slice(0,-4):e,t]}function le(e){return/^[a-zA-Z_$][0-9a-zA-Z_$]*?([.[]|$)/.test(e)}function pe(t,r=void 0){const i=ce(t)[0];if(!le(i))throw new e.package(`Invalid target '${i}'.`,r);const n=i.match(se).map((e=>e.replace(/\\(.)/g,"$1").replace(oe,""))),a=n.splice(0,1)[0];if(!/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a))throw new e.package(`Invalid target '${i}': Invalid root scope '${a}'.`,r);if("libWrapper"==a)throw new e.package("Not allowed to wrap libWrapper internals.",r);let s,o;if(0==n.length){if(!(a in globalThis))throw new e.package(`Could not find target '${i}': Could not find scope 'globalThis.${a}'.`,r);o=a,s=globalThis}else{o=n.pop();const t=function(e){try{return globalThis[e]??R(e)}catch(e){return}}(a);if(!t)throw new e.package(`Could not find target '${i}': Could not find root scope '${a}'.`,r);s=t;for(const t of n)if(s=s[t],!s)throw new e.package(`Could not find target '${i}': Could not find scope '${t}'.`,r)}return[s,o,i]}function de(e,t=void 0){return function(e,t,r,i){const n=new Wrapper(e,t,r,i);return ee.add(n),n}(...pe(e,t),t)}function ue(e,t=void 0){return function(e,t){const r=Object.getOwnPropertyDescriptor(e,t);return r?.get?._lib_wrapper??null}(...pe(e,t))}function he(e){const t=ee.find_by_id(e);return[t,e===t?.setter_id]}function ge(e,t,r){return t.get_fn_data(r).find((t=>t.package_info?.equals(e)))}function fe(t,r,i){const a=function(e,t){let r,i=null;if("number"==typeof t)[i,r]=he(t);else{const e=ce(t);i=ue(e[0]),r=e[1]}return i?r&&!i.is_property?null:ge(e,i,r):null}(t,r);if(!a){if(i)throw new e.package(`Cannot unregister '${r}' by ${t.type_plus_id} as no such wrapper has been registered`,t);return}const s=a.wrapper;return s.remove(a),function(e){e.is_empty()&&n&&(e.unwrap(),ee.remove(e))}(s),a}function _e(r){let i=new PackageInfo;if(!PackageInfo.is_valid_key_or_id(r))throw new e.package("Parameter 'package_id' is invalid.",i);const n=new PackageInfo(r);if(i.exists){if(!i.equals(n))throw new e.package(`${i.type_plus_id_capitalized} is not allowed to call libWrapper with package_id='${r}'.`,i)}else i=n;if(r==t){if(!ae)throw new e.package(`Not allowed to call libWrapper with package_id='${r}'.`,i)}else if(!i.exists&&globalThis.game?.modules?.size)throw new e.package(`Package '${r}' is not a valid package.`,i);return i}let we=class libWrapper{static get version(){return G}static get versions(){return[V,H,Y,B,K]}static get git_version(){return Z}static get is_fallback(){return!1}static get LibWrapperError(){return e.base}static get Error(){return e.base}static get LibWrapperInternalError(){return e.internal}static get InternalError(){return e.internal}static get LibWrapperPackageError(){return e.package}static get PackageError(){return e.package}static get LibWrapperAlreadyOverriddenError(){return e.already_overridden}static get AlreadyOverriddenError(){return e.already_overridden}static get LibWrapperInvalidWrapperChainError(){return e.invalid_chain}static get InvalidWrapperChainError(){return e.invalid_chain}static get onUnhandledError(){return F}static get WRAPPER(){return J.WRAPPER}static get MIXED(){return J.MIXED}static get OVERRIDE(){return J.OVERRIDE}static get PERF_NORMAL(){return Q.NORMAL}static get PERF_AUTO(){return Q.AUTO}static get PERF_FAST(){return Q.FAST}static get version_at_least(){return X}static register(r,n,a,s="MIXED",o={}){const c=_e(r);if(r!=t&&!ne)throw new e.package("Not allowed to register wrappers before the 'libWrapper.Ready' hook fires",c);if("string"!=typeof n&&"number"!=typeof n)throw new e.package("Parameter 'target' must be a number or a string.",c);if(!(a&&a instanceof Function))throw new e.package("Parameter 'fn' must be a function.",c);if(null===(s=J.get(s,null)))throw new e.package(`Parameter 'type' must be one of [${J.list.join(", ")}].`,c);const l=o?.chain??s.value<J.OVERRIDE.value;if("boolean"!=typeof l)throw new e.package("Parameter 'options.chain' must be a boolean.",c);if(!l&&s.value<J.OVERRIDE.value)throw new e.package("Parameter 'options.chain' must be 'true' for non-OVERRIDE wrappers.",c);const p=Q.get(o?.perf_mode??"AUTO",null);if(null===p)throw new e.package(`Parameter 'options.perf_mode' must be one of [${PERF_MODE.list.join(", ")}].`,c);const d=o?.bind??null;if(null!==d&&!Array.isArray(d))throw new e.package("Parameter 'options.bind' must be an array.",c);let u,h;if("number"==typeof n){if([u,h]=he(n),!u)throw new e.package(`Could not find target '${n}': Invalid or unknown unique identifier.`,c)}else{const t=ce(n),r=t[0];if(h=t[1],u=de(n,c),!u)throw new e.internal("Sanity check failed: 'wrapper' must not be falsy after _create_wrapper call");if(h&&!u.is_property)throw new e.package(`Cannot register a wrapper for '${n}' by ${c.type_plus_id}' because '${r}' is not a property, and therefore has no setter.`,c)}const g=u.get_id(h),f=u.get_name(h);if(ge(c,u,h))throw new e.package(`A wrapper for '${f}' (ID=${g}) has already been registered by ${c.type_plus_id}.`,c);const _=function(e,r){if(e.id===t)return Number.MAX_VALUE;const i=te.get(e.key);return void 0!==i?i:0}(c);if(c.id!=t&&LibWrapperStats.register_package(c),s.value>=J.OVERRIDE.value){const t=u.get_fn_data(h).find((e=>e.type===J.OVERRIDE));if(t){if(_<=t.priority)throw new e.already_overridden(c,t.package_info,u,n);if(!1!==Hooks.call(`${i}.OverrideLost`,t.package_info.id,c.id,u.name,u.frozen_names)){LibWrapperConflicts.register_conflict(c,t.package_info,u,null,!1)&&LibWrapperNotifications.conflict(t.package_info,c,!1,`${c.type_plus_id_capitalized} has higher priority, and is replacing the 'OVERRIDE' registered by ${c.type_plus_id} for '${f}'.`)}}}let w={package_info:c,target:n,setter:h,fn:a,type:s,wrapper:u,priority:_,chain:l,perf_mode:p,bind:d};return u.add(w),c.id!=t&&Hooks.callAll(`${i}.Register`,c.id,"number"==typeof n?f:n,s,o,g),Log.info$?.(`Registered a wrapper for '${f}' (ID=${g}) by ${c.type_plus_id} with type ${s}.`),g}static unregister(r,n,a=!0){const s=_e(r);if(r!=t&&!ne)throw new e.package("Not allowed to unregister wrappers before the 'libWrapper.Ready' hook fires",s);if("string"!=typeof n&&"number"!=typeof n)throw new e.package("Parameter 'target' must be a number or a string.",s);const o=fe(s,n,a);if(!o)return;const c=o.wrapper.get_id(o.setter),l=o.wrapper.get_name(o.setter);s.id!=t&&Hooks.callAll(`${i}.Unregister`,s.id,"number"==typeof n?l:n,c),Log.info$?.(`Unregistered the wrapper for '${l}' (ID=${c}) by ${s.type_plus_id}.`)}static unregister_all(r){const n=_e(r);if(r!=t&&!ne)throw new e.package("Not allowed to unregister wrappers before the 'libWrapper.Ready' hook fires",n);ee.forEach((e=>{this.unregister(n.id,e.getter_id,!1),e.is_property&&this.unregister(n.id,e.setter_id,!1)})),n.id!=t&&Hooks.callAll(`${i}.UnregisterAll`,n.id),Log.info$?.(`Unregistered all wrapper functions by ${n.type_plus_id}.`)}static ignore_conflicts(r,i,n,a={}){const s=_e(r);if(!ne)throw new e.package("Not allowed to ignore conflicts before the 'libWrapper.Ready' hook fires",s);Array.isArray(i)||(i=[i]),Array.isArray(n)||(n=[n]);const o=e=>"string"==typeof e;if(!i.every(o))throw new e.package("Parameter 'ignore_ids' must be a string, or an array of strings.",s);if(!n.every(o))throw new e.package("Parameter 'targets' must be a string, or an array of strings.",s);if(!n.every((e=>le(e))))throw new e.package("Parameter 'targets' must only contain valid targets.",s);const c=a.ignore_errors??!1;if("boolean"!=typeof c)throw new e.package("Parameter 'options.ignore_errors' must be a boolean.",s);const l=i.map((e=>new PackageInfo(e))).filter((e=>e.exists));0!=l.length?(LibWrapperConflicts.register_ignore(s,l,n,c),s.id!=t&&Log.info$?.(`Ignoring conflicts involving ${s.type_plus_id} and [${l.map((e=>e.type_plus_id)).join(", ")}] for targets [${n.join(", ")}].`)):Log.debug$?.(`Ignoring 'ignore_conflict' call for ${s.type_plus_id} since none of the package IDs provided exist or are active.`)}};N(we),Object.freeze(we),delete globalThis.libWrapper,Object.defineProperty(globalThis,"libWrapper",{get:()=>we,set:t=>{throw new e.package("Not allowed to re-assign the global instance of libWrapper")},configurable:!1}),globalThis.addEventListener("error",M),globalThis.addEventListener("unhandledrejection",M),Hooks.onError?function(){try{libWrapper.register("lib-wrapper","Hooks.onError",(function(e,...t){const r=t[1],i=t?.[2]?.msg;return F(r,i),e(...t)}),"WRAPPER",{perf_mode:"FAST"})}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Hooks.onError' wrapper.\n",Log.WARNING,e)}}():function(){try{const e="() => function "+Hooks._call.toString(),t=e.replace(/catch[\s\n]*\((.*)\)[\s\n]*{/gim,"$& globalThis.libWrapper.onUnhandledError($1);");if(e===t)throw new Error(`Could not patch 'Hooks._call' method:\n${e}`);Log.debug$?.(`Patched Hooks._call: ${t}`);const r=R(t)?.();if("function"!=typeof r)throw new Error(`Evaluation of patched 'Hooks._call' method did not return a function:\nPatched Method: ${t}\nReturned: ${r}`);Hooks._call=r}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Hooks._call' wrapper.\n",Log.WARNING,e)}try{libWrapper.register("lib-wrapper","Application.prototype._render",(function(e,...t){return e(...t).catch((e=>{throw F(e),e}))}),"WRAPPER",{perf_mode:"FAST"})}catch(e){LibWrapperNotifications.console_ui("A non-critical error occurred while initializing libWrapper.","Could not setup 'Application.prototype._render' wrapper.\n",Log.WARNING,e)}}();{let t,r;const n=T("libWrapperInit"),a={[n]:async function(e,...n){{const e=new PackageInfo("lib-wrapper",v.MODULE);fe(e,r,!0),fe(e,t,!0)}return ne=!0,await i18n.init(),LibWrapperSettings.init(),LibWrapperStats.init(),LibWrapperConflicts.init(),LibWrapperNotifications.init(),Log.fn(Log.ALWAYS,Log.INFO)(`Version ${q} ready.`),Hooks.callAll(`${i}.Ready`,we),e(...n)}};t=we.register("lib-wrapper","Game.prototype.initialize",a[n],we.WRAPPER,{perf_mode:we.PERF_FAST}),r=we.register("lib-wrapper","Game.toString",(function(){throw new e.package("Using 'Game.toString()' before libWrapper initialises is not allowed for compatibility reasons.")}),we.WRAPPER,{perf_mode:we.PERF_FAST}),Hooks.once("init",(()=>{if(!ne)throw new e.internal("Could not successfuly initialise libWrapper, likely due to a compatibility issue with another module.")}))}ae=!1;//# sourceMappingURL=lib-wrapper.js.map