@inpageedit/core 0.13.0-alpha.1 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-C_BIsubQ.js → index-BuYNq7f3.js} +2 -2
- package/dist/{index-C_BIsubQ.js.map → index-BuYNq7f3.js.map} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/services/index.js +1 -1
- package/lib/index.umd.js +1 -1
- package/lib/index.umd.js.map +1 -1
- package/package.json +3 -3
package/lib/index.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
(function(J,re){typeof exports=="object"&&typeof module<"u"?re(exports):typeof define=="function"&&define.amd?define(["exports"],re):(J=typeof globalThis<"u"?globalThis:J||self,re(J.InPageEditBundle={}))})(this,(function(J){"use strict";var Yv=Object.defineProperty;var Sf=J=>{throw TypeError(J)};var Qv=(J,re,Se)=>re in J?Yv(J,re,{enumerable:!0,configurable:!0,writable:!0,value:Se}):J[re]=Se;var F=(J,re,Se)=>Qv(J,typeof re!="symbol"?re+"":re,Se),sa=(J,re,Se)=>re.has(J)||Sf("Cannot "+Se);var X=(J,re,Se)=>(sa(J,re,"read from private field"),Se?Se.call(J):re.get(J)),Hi=(J,re,Se)=>re.has(J)?Sf("Cannot add the same private member more than once"):re instanceof WeakSet?re.add(J):re.set(J,Se),Qe=(J,re,Se,K)=>(sa(J,re,"write to private field"),K?K.call(J,Se):re.set(J,Se),Se),lt=(J,re,Se)=>(sa(J,re,"access private method"),Se);var at,ji,pi,Ui,Fi,Bi,qi,_e,it,fe,Ve,oa,Cf,aa,Rf,Af,$t,If,Of,Tf,Lf,In,pt,mi;const re=()=>{let t,e;return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}};Promise.withResolvers||(Promise.withResolvers=re);var Se=Object.defineProperty,K=(t,e)=>Se(t,"name",{value:e,configurable:!0});function Nf(){}K(Nf,"noop");function be(t){return t==null}K(be,"isNullable");function Mf(t){return!be(t)}K(Mf,"isNonNullable");function Mn(t){return t&&typeof t=="object"&&!Array.isArray(t)}K(Mn,"isPlainObject");function la(t,e){return Object.fromEntries(Object.entries(t).filter(([i,n])=>e(i,n)))}K(la,"filterKeys");function It(t,e){return Object.fromEntries(Object.entries(t).map(([i,n])=>[i,e(n,i)]))}K(It,"mapValues");function ca(t,e,i){if(!e)return{...t};const n={};for(const r of e)(i||t[r]!==void 0)&&(n[r]=t[r]);return n}K(ca,"pick");function Df(t,e){if(!e)return{...t};const i={...t};for(const n of e)Reflect.deleteProperty(i,n);return i}K(Df,"omit");function Ie(t,e,i){return Object.defineProperty(t,e,{writable:!0,value:i,enumerable:!1})}K(Ie,"defineProperty");function jf(t,e){return e.every(i=>t.includes(i))}K(jf,"contain");function Uf(t,e){return t.filter(i=>e.includes(i))}K(Uf,"intersection");function Ff(t,e){return t.filter(i=>!e.includes(i))}K(Ff,"difference");function Bf(t,e){return Array.from(new Set([...t,...e]))}K(Bf,"union");function qf(t){return[...new Set(t)]}K(qf,"deduplicate");function zt(t,e){const i=t?.indexOf(e);return i>=0?(t.splice(i,1),!0):!1}K(zt,"remove");function Hf(t){return Array.isArray(t)?t:be(t)?[]:[t]}K(Hf,"makeArray");function Kt(t,e){return arguments.length===1?i=>Kt(t,i):t in globalThis&&e instanceof globalThis[t]||Object.prototype.toString.call(e).slice(8,-1)===t}K(Kt,"is");function zi(t){return Kt("ArrayBuffer",t)||Kt("SharedArrayBuffer",t)}K(zi,"isArrayBufferLike");function ua(t){return zi(t)||ArrayBuffer.isView(t)}K(ua,"isArrayBufferSource");var gt;(t=>{t.is=zi,t.isSource=ua;function e(o){return ArrayBuffer.isView(o)?o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength):o}t.fromSource=e,K(e,"fromSource");function i(o){if(typeof Buffer<"u")return Buffer.from(o).toString("base64");let a="";const l=new Uint8Array(o);for(let c=0;c<l.byteLength;c++)a+=String.fromCharCode(l[c]);return btoa(a)}t.toBase64=i,K(i,"toBase64");function n(o){return typeof Buffer<"u"?e(Buffer.from(o,"base64")):Uint8Array.from(atob(o),a=>a.charCodeAt(0))}t.fromBase64=n,K(n,"fromBase64");function r(o){return typeof Buffer<"u"?Buffer.from(o).toString("hex"):Array.from(new Uint8Array(o),a=>a.toString(16).padStart(2,"0")).join("")}t.toHex=r,K(r,"toHex");function s(o){if(typeof Buffer<"u")return e(Buffer.from(o,"hex"));const a=o.length%2===0?o:o.slice(0,o.length-1),l=[];for(let c=0;c<a.length;c+=2)l.push(parseInt(`${a[c]}${a[c+1]}`,16));return Uint8Array.from(l).buffer}t.fromHex=s,K(s,"fromHex")})(gt||(gt={})),gt.fromBase64,gt.toBase64,gt.fromHex,gt.toHex;function Dn(t,e=new Map){if(!t||typeof t!="object")return t;if(Kt("Date",t))return new Date(t.valueOf());if(Kt("RegExp",t))return new RegExp(t.source,t.flags);if(zi(t))return t.slice(0);if(ArrayBuffer.isView(t))return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);const i=e.get(t);if(i)return i;if(Array.isArray(t)){const r=[];return e.set(t,r),t.forEach((s,o)=>{r[o]=Reflect.apply(Dn,null,[s,e])}),r}const n=Object.create(Object.getPrototypeOf(t));e.set(t,n);for(const r of Reflect.ownKeys(t)){const s={...Reflect.getOwnPropertyDescriptor(t,r)};"value"in s&&(s.value=Reflect.apply(Dn,null,[s.value,e])),Reflect.defineProperty(n,r,s)}return n}K(Dn,"clone");function Zt(t,e,i){if(t===e||!i&&be(t)&&be(e))return!0;if(typeof t!=typeof e||typeof t!="object"||!t||!e)return!1;function n(r,s){return r(t)?r(e)?s(t,e):!1:r(e)?!1:void 0}return K(n,"check"),n(Array.isArray,(r,s)=>r.length===s.length&&r.every((o,a)=>Zt(o,s[a])))??n(Kt("Date"),(r,s)=>r.valueOf()===s.valueOf())??n(Kt("RegExp"),(r,s)=>r.source===s.source&&r.flags===s.flags)??n(zi,(r,s)=>{if(r.byteLength!==s.byteLength)return!1;const o=new Uint8Array(r),a=new Uint8Array(s);for(let l=0;l<o.length;l++)if(o[l]!==a[l])return!1;return!0})??Object.keys({...t,...e}).every(r=>Zt(t[r],e[r],i))}K(Zt,"deepEqual");function zf(t){return t.charAt(0).toUpperCase()+t.slice(1)}K(zf,"capitalize");function Kf(t){return t.charAt(0).toLowerCase()+t.slice(1)}K(Kf,"uncapitalize");function Wf(t){return t.replace(/[_-][a-z]/g,e=>e.slice(1).toUpperCase())}K(Wf,"camelCase");function Xr(t,e,i){const n=[];let r=0;for(let s=0;s<t.length;s++){const o=t.charCodeAt(s);if(o>=65&&o<=90){if(r===1){const a=t.charCodeAt(s+1);a>=97&&a<=122&&n.push(i),n.push(o+32)}else r!==0&&n.push(i),n.push(o+32);r=1}else o>=97&&o<=122?(n.push(o),r=2):e.includes(o)?(r!==0&&n.push(i),r=0):n.push(o)}return String.fromCharCode(...n)}K(Xr,"tokenize");function Vf(t){return Xr(t,[45,95],45)}K(Vf,"paramCase");function Gf(t){return Xr(t,[45,95],95)}K(Gf,"snakeCase");function Yf(t){return typeof t!="string"?`[${t.toString()}]`:/^[a-z_$][\w$]*$/i.test(t)?`.${t}`:`[${JSON.stringify(t)}]`}K(Yf,"formatProperty");function fa(t){return t.replace(/\/$/,"")}K(fa,"trimSlash");function Qf(t){return t.startsWith("/")||(t="/"+t),fa(t)}K(Qf,"sanitize");var da;(t=>{t.millisecond=1,t.second=1e3,t.minute=t.second*60,t.hour=t.minute*60,t.day=t.hour*24,t.week=t.day*7;let e=new Date().getTimezoneOffset();function i(p){e=p}t.setTimezoneOffset=i,K(i,"setTimezoneOffset");function n(){return e}t.getTimezoneOffset=n,K(n,"getTimezoneOffset");function r(p=new Date,f){return typeof p=="number"&&(p=new Date(p)),f===void 0&&(f=e),Math.floor((p.valueOf()/t.minute-f)/1440)}t.getDateNumber=r,K(r,"getDateNumber");function s(p,f){const _=new Date(p*t.day);return f===void 0&&(f=e),new Date(+_+f*t.minute)}t.fromDateNumber=s,K(s,"fromDateNumber");const o=/\d+(?:\.\d+)?/.source,a=new RegExp(`^${["w(?:eek(?:s)?)?","d(?:ay(?:s)?)?","h(?:our(?:s)?)?","m(?:in(?:ute)?(?:s)?)?","s(?:ec(?:ond)?(?:s)?)?"].map(p=>`(${o}${p})?`).join("")}$`);function l(p){const f=a.exec(p);return f?(parseFloat(f[1])*t.week||0)+(parseFloat(f[2])*t.day||0)+(parseFloat(f[3])*t.hour||0)+(parseFloat(f[4])*t.minute||0)+(parseFloat(f[5])*t.second||0):0}t.parseTime=l,K(l,"parseTime");function c(p){const f=l(p);return f?p=Date.now()+f:/^\d{1,2}(:\d{1,2}){1,2}$/.test(p)?p=`${new Date().toLocaleDateString()}-${p}`:/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(p)&&(p=`${new Date().getFullYear()}-${p}`),p?new Date(p):new Date}t.parseDate=c,K(c,"parseDate");function u(p){const f=Math.abs(p);return f>=t.day-t.hour/2?Math.round(p/t.day)+"d":f>=t.hour-t.minute/2?Math.round(p/t.hour)+"h":f>=t.minute-t.second/2?Math.round(p/t.minute)+"m":f>=t.second?Math.round(p/t.second)+"s":p+"ms"}t.format=u,K(u,"format");function d(p,f=2){return p.toString().padStart(f,"0")}t.toDigits=d,K(d,"toDigits");function h(p,f=new Date){return p.replace("yyyy",f.getFullYear().toString()).replace("yy",f.getFullYear().toString().slice(2)).replace("MM",d(f.getMonth()+1)).replace("dd",d(f.getDate())).replace("hh",d(f.getHours())).replace("mm",d(f.getMinutes())).replace("ss",d(f.getSeconds())).replace("SSS",d(f.getMilliseconds(),3))}t.template=h,K(h,"template")})(da||(da={}));var Jf=Object.defineProperty,W=(t,e)=>Jf(t,"name",{value:e,configurable:!0}),M={shadow:Symbol.for("cordis.shadow"),receiver:Symbol.for("cordis.receiver"),original:Symbol.for("cordis.original"),store:Symbol.for("cordis.store"),events:Symbol.for("cordis.events"),static:Symbol.for("cordis.static"),filter:Symbol.for("cordis.filter"),expose:Symbol.for("cordis.expose"),isolate:Symbol.for("cordis.isolate"),internal:Symbol.for("cordis.internal"),intercept:Symbol.for("cordis.intercept"),setup:Symbol.for("cordis.setup"),invoke:Symbol.for("cordis.invoke"),extend:Symbol.for("cordis.extend"),tracker:Symbol.for("cordis.tracker"),provide:Symbol.for("cordis.provide"),immediate:Symbol.for("cordis.immediate")},Xf=function*(){}.constructor,ha=async function*(){}.constructor;function Zr(t){return!(!t.prototype||t instanceof Xf||ha!==Function&&t instanceof ha)}W(Zr,"isConstructor");function Ki(t,e){const i=t.Config||t.schema;return i&&t.schema!==!1&&(e=i(e)),e??{}}W(Ki,"resolveConfig");function pa(t){return[Map,Set,Date,Promise].some(e=>t instanceof e)}W(pa,"isUnproxyable");function es(t,e){if(t===Object.prototype)return e;const i=Object.create(es(Object.getPrototypeOf(t),e));for(const n of Reflect.ownKeys(t))Object.defineProperty(i,n,Object.getOwnPropertyDescriptor(t,n));return i}W(es,"joinPrototype");function ts(t){return t&&(typeof t=="object"||typeof t=="function")}W(ts,"isObject");function yt(t,e,i){if(!ts(e))return e;if(Object.hasOwn(e,M.shadow))return Object.getPrototypeOf(e);const n=e[M.tracker];return n?Un(t,e,n,i):e}W(yt,"getTraceable");function Wi(t,e){return e?new Proxy(t,{get:W((i,n,r)=>n in e&&n!=="constructor"?Reflect.get(e,n,r):Reflect.get(i,n,r),"get"),set:W((i,n,r,s)=>n in e&&n!=="constructor"?Reflect.set(e,n,r,s):Reflect.set(i,n,r,s),"set")}):t}W(Wi,"withProps");function jn(t,e,i){return Wi(t,Object.defineProperty(Object.create(null),e,{value:i,writable:!1}))}W(jn,"withProp");function is(t,e,i,n){if(!i)return n;const r=Reflect.getOwnPropertyDescriptor(e,i)?.value;return r?jn(n,i,t.extend({[M.shadow]:r})):n}W(is,"createShadow");function ma(t,e,i,n){return new Proxy(e,{apply:W((r,s,o)=>(s===i&&(s=n),o=o.map(a=>typeof a!="function"||a[M.original]?a:new Proxy(a,{get:W((l,c,u)=>{if(c===M.original)return l;const d=Reflect.get(l,c,u);return c==="toString"&&d===Function.prototype.toString?function(...h){return Reflect.apply(d,this===u?l:this,h)}:d},"get"),apply:W((l,c,u)=>Reflect.apply(l,yt(t,c),u.map(d=>yt(t,d))),"apply"),construct:W((l,c,u)=>Reflect.construct(l,c.map(d=>yt(t,d)),u),"construct")})),yt(t,Reflect.apply(r,s,o))),"apply")})}W(ma,"createShadowMethod");function Un(t,e,i,n){t[M.shadow]&&(t=Object.getPrototypeOf(t));const r=new Proxy(e,{get:W((s,o,a)=>{if(o===M.original)return s;if(o===i.property)return t;if(typeof o=="symbol")return Reflect.get(s,o,a);if(i.associate&&t[M.internal][`${i.associate}.${o}`])return Reflect.get(t,`${i.associate}.${o}`,jn(t,M.receiver,a));const l=is(t,s,i.property,a),c=Reflect.get(s,o,l),u=c?.[M.tracker];return u?Un(t,c,u):!n&&typeof c=="function"?ma(t,c,a,l):c},"get"),set:W((s,o,a,l)=>{if(o===M.original||o===i.property)return!1;if(typeof o=="symbol")return Reflect.set(s,o,a,l);if(i.associate&&t[M.internal][`${i.associate}.${o}`])return Reflect.set(t,`${i.associate}.${o}`,a,jn(t,M.receiver,l));const c=is(t,s,i.property,l);return Reflect.set(s,o,a,c)},"set"),apply:W((s,o,a)=>ns(r,s,o,a),"apply")});return r}W(Un,"createTraceable");function ns(t,e,i,n){return e[M.invoke]?e[M.invoke].apply(t,n):Reflect.apply(e,i,n)}W(ns,"applyTraceable");function rs(t,e,i){const n=W(function(...r){const s=Un(n.ctx,n,i);return ns(s,n,this,r)},"self");return Ie(n,"name",t),Object.setPrototypeOf(n,e)}W(rs,"createCallable");var Zf=(at=class{constructor(e){this.ctx=e,Ie(this,M.tracker,{associate:"reflect",property:"ctx"}),this._mixin("reflect",["get","set","provide","accessor","mixin","alias"]),this._mixin("scope",["config","runtime","effect","collect","accept","decline"]),this._mixin("registry",["using","inject","plugin"]),this._mixin("lifecycle",["on","once","parallel","emit","serial","bail","start","stop"])}static resolveInject(e,i){let n=e[M.internal][i];for(;n?.type==="alias";)i=n.name,n=e[M.internal][i];return[i,n]}static checkInject(e,i,n){if(e=e[M.shadow]??e,["prototype","then","registry","lifecycle"].includes(i)||i[0]==="$"||i[0]==="_"||!e.runtime.plugin||e.bail(e,"internal/inject",i))return;const r=n.stack.split(`
|
|
2
2
|
`);r.splice(1,1),n.stack=r.join(`
|
|
3
3
|
`),e.emit(e,"internal/warning",n)}get(e){if(this.ctx[M.internal][e]?.type!=="service")return;const n=this.ctx[M.isolate][e],r=this.ctx[M.store][n]?.value;return yt(this.ctx,r)}set(e,i){this.provide(e);const n=this.ctx[M.isolate][e],r=this.ctx[M.store][n]?.value;i??(i=void 0);let s=W(()=>{},"dispose");if(r===i)return s;if(!be(i)&&!be(r))throw new Error(`service ${e} has been registered`);const o=this.ctx;be(i)||(s=o.effect(()=>()=>{o.set(e,void 0)})),pa(i)&&o.emit(o,"internal/warning",new Error(`service ${e} is an unproxyable object, which may lead to unexpected behavior`));const a=Object.create(o);return a[M.filter]=l=>o[M.isolate][e]===l[M.isolate][e],o.emit(a,"internal/before-service",e,i),o[M.store][n]={value:i,source:o},o.emit(a,"internal/service",e,r),s}provide(e,i,n){const r=this.ctx.root[M.internal];if(e in r)return;const s=Symbol(e);r[e]={type:"service",builtin:n},this.ctx.root[M.isolate][e]=s,ts(i)&&(this.ctx[M.store][s]={value:i,source:null},Ie(i,M.tracker,{associate:e,property:"ctx"}))}_accessor(e,i){const n=this.ctx.root[M.internal];return e in n?()=>{}:(n[e]={type:"accessor",...i},()=>delete this.ctx.root[M.isolate][e])}accessor(e,i){this.ctx.scope.effect(()=>this._accessor(e,i))}alias(e,i){const n=this.ctx.root[M.internal];if(!(e in n))for(const r of i)n[r]||(n[r]={type:"alias",name:e})}_mixin(e,i){const n=Array.isArray(i)?i.map(o=>[o,o]):Object.entries(i),r=typeof e=="string"?o=>o[e]:()=>e,s=n.map(([o,a])=>this._accessor(a,{get(l){const c=r(this);if(be(c))return c;const u=l?Wi(l,c):c,d=Reflect.get(c,o,u);return typeof d!="function"?d:d.bind(u??c)},set(l,c){const u=r(this),d=c?Wi(c,u):u;return Reflect.set(u,o,l,d)}}));return()=>s.forEach(o=>o())}mixin(e,i){this.ctx.scope.effect(()=>this._mixin(e,i))}trace(e){return yt(this.ctx,e)}bind(e){return new Proxy(e,{apply:W((i,n,r)=>i.apply(this.trace(n),r.map(s=>this.trace(s))),"apply")})}},W(at,"ReflectService"),F(at,"handler",{get:W((e,i,n)=>{if(typeof i!="string")return Reflect.get(e,i,n);if(Reflect.has(e,i))return yt(n,Reflect.get(e,i,n),!0);const[r,s]=at.resolveInject(e,i),o=new Error(`property ${r} is not registered, declare it as \`inject\` to suppress this warning`);return s?s.type==="accessor"?s.get.call(n,n[M.receiver]):(s.builtin||at.checkInject(n,r,o),n.reflect.get(r)):(at.checkInject(n,r,o),Reflect.get(e,r,n))},"get"),set:W((e,i,n,r)=>{if(typeof i!="string")return Reflect.set(e,i,n,r);const[s,o]=at.resolveInject(e,i);return o?o.type==="accessor"?o.set?o.set.call(r,n,r[M.receiver]):!1:(r.reflect.set(s,n),!0):Reflect.set(e,s,n,r)},"set"),has:W((e,i)=>{if(typeof i!="string")return Reflect.has(e,i);if(Reflect.has(e,i))return!0;const[,n]=at.resolveInject(e,i);return!!n},"has")}),at),ss=Zf;function os(t){return t!==null&&t!==!1&&t!==void 0}W(os,"isBailed");var ed=(ji=class{constructor(e){F(this,"isActive",!1);F(this,"_tasks",new Set);F(this,"_hooks",{});this.ctx=e,Ie(this,M.tracker,{associate:"lifecycle",property:"ctx"}),Ie(this.on("internal/listener",function(n,r,s){const o=s.prepend?"unshift":"push";if(n==="ready")return this.lifecycle.isActive?(this.scope.ensure(async()=>r()),()=>!1):void 0;if(n==="dispose")return this.scope.disposables[o](r),Ie(r,"name","event <dispose>"),()=>zt(this.scope.disposables,r);if(n==="fork")return this.scope.runtime.forkables[o](r),this.scope.collect("event <fork>",()=>zt(this.scope.runtime.forkables,r))}),Be.static,e.scope);for(const n of["info","error","warning"])Ie(this.on(`internal/${n}`,(r,...s)=>{this._hooks[`internal/${n}`].length>1}),Be.static,e.scope);Ie(this.on("internal/before-service",function(n){for(const r of this.registry.values()){if(!r.inject[n]?.required)continue;const s=r.isReusable?r.children:[r];for(const o of s)this[M.filter](o.ctx)&&(o.updateStatus(),o.reset())}},{global:!0}),Be.static,e.scope),Ie(this.on("internal/service",function(n){for(const r of this.registry.values()){if(!r.inject[n]?.required)continue;const s=r.isReusable?r.children:[r];for(const o of s)this[M.filter](o.ctx)&&o.start()}},{global:!0}),Be.static,e.scope);const i=W((n,r)=>{if(!n.runtime.plugin)return!1;for(const s in n.runtime.inject)if(r===ss.resolveInject(n.ctx,s)[0])return!0;return i(n.parent.scope,r)},"checkInject");Ie(this.on("internal/inject",function(n){return i(this.scope,n)},{global:!0}),Be.static,e.scope)}async flush(){for(;this._tasks.size;)await Promise.all(Array.from(this._tasks))}filterHooks(e,i){return i=yt(this.ctx,i),e.slice().filter(n=>{const r=i?.[Be.filter];return n.global||!r||r.call(i,n.ctx)})}*dispatch(e,i){const n=typeof i[0]=="object"||typeof i[0]=="function"?i.shift():null,r=i.shift();r!=="internal/event"&&this.emit("internal/event",e,r,i,n);for(const s of this.filterHooks(this._hooks[r]||[],n))yield s.callback.apply(n,i)}async parallel(...e){await Promise.all(this.dispatch("emit",e))}emit(...e){Array.from(this.dispatch("emit",e))}async serial(...e){for await(const i of this.dispatch("serial",e))if(os(i))return i}bail(...e){for(const i of this.dispatch("bail",e))if(os(i))return i}register(e,i,n,r){const s=r.prepend?"unshift":"push";return i[s]({ctx:this.ctx,callback:n,...r}),this.ctx.state.collect(e,()=>this.unregister(i,n))}unregister(e,i){const n=e.findIndex(r=>r.callback===i);if(n>=0)return e.splice(n,1),!0}on(e,i,n){var a;typeof n!="object"&&(n={prepend:n}),this.ctx.scope.assertActive(),i=this.ctx.reflect.bind(i);const r=this.bail(this.ctx,"internal/listener",e,i,n);if(r)return r;const s=(a=this._hooks)[e]||(a[e]=[]),o=typeof e=="string"?`event <${e}>`:"event (Symbol)";return this.register(o,s,i,n)}once(e,i,n){const r=this.on(e,function(...s){return r(),i.apply(this,s)},n);return r}async start(){this.isActive=!0;const e=this._hooks.ready||[];for(;e.length;){const{ctx:i,callback:n}=e.shift();i.scope.ensure(async()=>n())}await this.flush()}async stop(){this.isActive=!1,this.ctx.scope.reset()}},W(ji,"Lifecycle"),ji),td=ed,as=(pi=class extends Error{constructor(e,i){super(i??pi.Code[e]),this.code=e}},W(pi,"CordisError"),pi);(t=>{t.Code={INACTIVE_EFFECT:"cannot create effect on inactive context"}})(as||(as={}));var ga=(Ui=class{constructor(e,i){F(this,"uid");F(this,"ctx");F(this,"disposables",[]);F(this,"error");F(this,"status",0);F(this,"isActive",!1);F(this,"context");F(this,"proxy");F(this,"acceptors",[]);F(this,"tasks",new Set);F(this,"hasError",!1);this.parent=e,this.config=i,this.uid=e.registry?e.registry.counter:0,this.ctx=this.context=e.extend({scope:this}),this.proxy=new Proxy({},{get:W((n,r)=>Reflect.get(this.config,r),"get")})}get _config(){return this.runtime.isReactive?this.proxy:this.config}assertActive(){if(!(this.uid!==null||this.isActive))throw new as("INACTIVE_EFFECT")}effect(e,i){this.assertActive();const n=Zr(e)?new e(this.ctx,i):e(this.ctx,i);let r=!1;const s=typeof n=="function"?n:n.dispose.bind(n),o=W((...a)=>{if(!r)return r=!0,zt(this.disposables,o),s(...a)},"wrapped");return this.disposables.push(o),typeof n=="function"?o:(n.dispose=o,n)}collect(e,i){const n=Ie(()=>(zt(this.disposables,n),i()),"name",e);return this.disposables.push(n),n}restart(){this.reset(),this.error=null,this.hasError=!1,this.status=0,this.start()}_getStatus(){return this.uid===null?4:this.hasError?3:this.tasks.size?1:this.ready?2:0}updateStatus(e){const i=this.status;e?.(),this.status=this._getStatus(),i!==this.status&&this.context.emit("internal/status",this,i)}ensure(e){const i=e().catch(n=>{this.context.emit(this.ctx,"internal/error",n),this.cancel(n)}).finally(()=>{this.updateStatus(()=>this.tasks.delete(i)),this.context.events._tasks.delete(i)});this.updateStatus(()=>this.tasks.add(i)),this.context.events._tasks.add(i)}cancel(e){this.error=e,this.updateStatus(()=>this.hasError=!0),this.reset()}get ready(){return Object.entries(this.runtime.inject).every(([e,i])=>!i.required||!be(this.ctx.get(e)))}reset(){this.isActive=!1,this.disposables=this.disposables.splice(0).filter(e=>{if(this.uid!==null&&e[Be.static]===this)return!0;(async()=>e())().catch(i=>{this.context.emit(this.ctx,"internal/error",i)})})}init(e){this.config?this.start():this.cancel(e)}start(){if(!this.ready||this.isActive||this.uid===null)return!0;this.isActive=!0,this.updateStatus(()=>this.hasError=!1)}accept(...e){const n={keys:Array.isArray(e[0])?e.shift():null,callback:e[0],...e[1]};return this.effect(()=>(this.acceptors.push(n),n.immediate&&n.callback?.(this.config),()=>zt(this.acceptors,n)))}decline(e){return this.accept(e,()=>!0)}checkUpdate(e,i){if(i||!this.config)return[!0,!0];if(i===!1)return[!1,!1];const n=Object.create(null),r=W(c=>{const u=n[c]??(n[c]=!Zt(this.config[c],e[c]));return o||(o=u),u},"checkPropertyUpdate"),s=new Set;let o=!1,a=!1,l=this.runtime.isReactive||null;for(const{keys:c,callback:u,passive:d}of this.acceptors){if(!c)l||(l=!d);else if(d)c?.forEach(p=>s.add(p));else{let p=!1;for(const f of c)p||(p=r(f));if(!p)continue}u?.(e)&&(a=!0)}for(const c in{...this.config,...e})if(l!==!1&&!(c in n)&&!s.has(c)){const u=r(c);l===null&&(a||(a=u))}return[o,a]}},W(Ui,"EffectScope"),Ui),id=(Fi=class extends ga{constructor(i,n,r,s){super(i,r);F(this,"dispose");this.runtime=n,this.dispose=Ie(i.scope.collect(`fork <${i.runtime.name}>`,()=>{this.uid=null,this.reset(),this.context.emit("internal/fork",this);const o=zt(n.disposables,this.dispose);return zt(n.children,this)&&!n.children.length&&i.registry.delete(n.plugin),o}),Be.static,n),n.children.push(this),n.disposables.push(this.dispose),this.context.emit("internal/fork",this),this.init(s)}start(){if(super.start())return!0;for(const i of this.runtime.forkables)this.ensure(async()=>i(this.context,this._config))}update(i,n){const r=this.config,s=this.runtime.isForkable?this:this.runtime;if(s.config!==r)return;let o;try{o=Ki(this.runtime.plugin,i)}catch(c){return this.context.emit("internal/error",c),this.cancel(c)}const[a,l]=s.checkUpdate(o,n);this.context.emit("internal/before-update",this,i),this.config=o,s.config=o,a&&this.context.emit("internal/update",this,r),l&&s.restart()}},W(Fi,"ForkScope"),Fi),ya=(Bi=class extends ga{constructor(i,n,r,s){super(i,r);F(this,"value");F(this,"runtime",this);F(this,"schema");F(this,"name");F(this,"inject",Object.create(null));F(this,"forkables",[]);F(this,"children",[]);F(this,"isReusable",!1);F(this,"isReactive",!1);F(this,"apply",W((i,n)=>{if(typeof this.plugin!="function")return this.plugin.apply(i,n);if(Zr(this.plugin)){const r=new this.plugin(i,n),s=r[Be.expose];return s&&i.set(s,r),r.fork&&this.forkables.push(r.fork.bind(r)),r}else return this.plugin(i,n)},"apply"));this.plugin=n,n?(this.setup(),this.init(s)):(this.name="root",this.isActive=!0)}get isForkable(){return this.forkables.length>0}fork(i,n,r){return new id(i,this,n,r)}dispose(){return this.uid=null,this.reset(),this.context.emit("internal/runtime",this),!0}setup(){const{name:i}=this.plugin;i&&i!=="apply"&&(this.name=i),this.schema=this.plugin.Config||this.plugin.schema,this.inject=$e.resolve(this.plugin.using||this.plugin.inject),this.isReusable=this.plugin.reusable,this.isReactive=this.plugin.reactive,this.context.emit("internal/runtime",this),this.isReusable&&this.forkables.push(this.apply)}reset(){super.reset();for(const i of this.children)i.reset()}start(){if(super.start())return!0;!this.isReusable&&this.plugin&&this.ensure(async()=>this.value=this.apply(this.ctx,this._config));for(const i of this.children)i.start()}update(i,n){if(this.isForkable){const c=new Error(`attempting to update forkable plugin "${this.plugin.name}", which may lead to unexpected behavior`);this.context.emit(this.ctx,"internal/warning",c)}const r=this.config;let s;try{s=Ki(this.runtime.plugin||this.context.constructor,i)}catch(c){return this.context.emit("internal/error",c),this.cancel(c)}const[o,a]=this.checkUpdate(s,n),l=this.children.find(c=>c.config===r);this.config=s,l&&(this.context.emit("internal/before-update",l,i),l.config=s,o&&this.context.emit("internal/update",l,r)),a&&this.restart()}},W(Bi,"MainScope"),Bi);function ba(t){return t&&typeof t=="object"&&typeof t.apply=="function"}W(ba,"isApplicable");function $e(t){return function(e,i){if(i.kind==="class")e.inject=t;else if(i.kind==="method")i.addInitializer(function(){const n=this[M.tracker]?.property;if(!n)throw new Error("missing context tracker");this[n].inject(t,r=>{e.call(Wi(this,{[n]:r}))})});else throw new Error("@Inject can only be used on class or class methods")}}W($e,"Inject"),(t=>{function e(i){if(!i)return{};if(Array.isArray(i))return Object.fromEntries(i.map(o=>[o,{required:!0}]));const{required:n,optional:r,...s}=i;return Array.isArray(n)&&Object.assign(s,Object.fromEntries(n.map(o=>[o,{required:!0}]))),Array.isArray(r)&&Object.assign(s,Object.fromEntries(r.map(o=>[o,{required:!1}]))),s}t.resolve=e,W(e,"resolve")})($e||($e={}));var nd=(qi=class{constructor(e,i){F(this,"_counter",0);F(this,"_internal",new Map);F(this,"context");this.ctx=e,Ie(this,M.tracker,{associate:"registry",property:"ctx"}),this.context=e;const n=new ya(e,null,i);e.scope=n,n.ctx=e,this.set(null,n)}get counter(){return++this._counter}get size(){return this._internal.size}resolve(e,i=!1){if(e===null||typeof e=="function")return e;if(ba(e))return e.apply;if(i)throw new Error('invalid plugin, expect function or object with an "apply" method, received '+typeof e)}get(e){const i=this.resolve(e);return i&&this._internal.get(i)}has(e){const i=this.resolve(e);return!!i&&this._internal.has(i)}set(e,i){const n=this.resolve(e);this._internal.set(n,i)}delete(e){const i=this.resolve(e),n=i&&this._internal.get(i);if(n)return this._internal.delete(i),n.dispose(),n}keys(){return this._internal.keys()}values(){return this._internal.values()}entries(){return this._internal.entries()}forEach(e){return this._internal.forEach(e)}using(e,i){return this.inject(e,i)}inject(e,i){return this.plugin({inject:e,apply:i,name:i.name})}plugin(e,i,n){if(this.resolve(e,!0),this.ctx.scope.assertActive(),!n)try{i=Ki(e,i)}catch(s){this.context.emit(this.ctx,"internal/error",s),n=s,i=null}let r=this.get(e);return r?(r.isForkable||this.context.emit(this.ctx,"internal/warning",new Error(`duplicate plugin detected: ${e.name}`)),r.fork(this.ctx,i,n)):(r=new ya(this.ctx,e,i,n),this.set(e,r),r.fork(this.ctx,i,n))}},W(qi,"Registry"),qi),rd=nd,Be=(_e=class{static is(e){return!!e?.[_e.is]}static associate(e,i){return e}constructor(e){e=Ki(this.constructor,e),this[M.store]=Object.create(null),this[M.isolate]=Object.create(null),this[M.internal]=Object.create(null),this[M.intercept]=Object.create(null);const i=new Proxy(this,ss.handler);i.root=i,i.reflect=new ss(i),i.registry=new rd(i,e),i.lifecycle=new td(i);const n=W(r=>{if(r){n(Object.getPrototypeOf(r));for(const s of Object.getOwnPropertyNames(r)){const o=r[s].prototype?.constructor;o&&(i[r[s].key]=new o(i,e),Ie(i[r[s].key],"ctx",i))}}},"attach");return n(this[M.internal]),i}[Symbol.for("nodejs.util.inspect.custom")](){return`Context <${this.name}>`}get name(){let e=this.runtime;for(;e&&!e.name;)e=e.parent.runtime;return e?.name}get events(){return this.lifecycle}get state(){return this.scope}extend(e={}){const i=Reflect.getOwnPropertyDescriptor(this,M.shadow)?.value,n=Object.assign(Object.create(yt(this,this)),e);return i?Object.assign(Object.create(n),{[M.shadow]:i}):n}isolate(e,i){const n=Object.create(this[M.isolate]);return n[e]=i??Symbol(e),this.extend({[M.isolate]:n})}intercept(e,i){const n=Object.create(this[M.intercept]);return n[e]=i,this.extend({[M.intercept]:n})}},W(_e,"Context"),F(_e,"store",M.store),F(_e,"events",M.events),F(_e,"static",M.static),F(_e,"filter",M.filter),F(_e,"expose",M.expose),F(_e,"isolate",M.isolate),F(_e,"internal",M.internal),F(_e,"intercept",M.intercept),F(_e,"origin","ctx"),F(_e,"current","ctx"),_e.is[Symbol.toPrimitive]=()=>Symbol.for("cordis.is"),_e.prototype[_e.is]=!0,_e);Be.prototype[Be.internal]=Object.create(null);var Ot=(it=class{constructor(...e){F(this,"ctx");F(this,"name");F(this,"config");let i,n,r,s;Be.is(e[0])?(i=e[0],typeof e[1]=="string"?(n=e[1],r=e[2]):s=e[1]):s=e[0],n??(n=this.constructor[M.provide]),r??(r=this.constructor[M.immediate]);let o=this;const a={associate:n,property:"ctx"};return o[M.invoke]&&(o=rs(n,es(Object.getPrototypeOf(this),Function.prototype),a)),i?o.ctx=i:o[M.setup](),o.name=n,o.config=s,Ie(o,M.tracker,a),o.ctx.provide(n),o.ctx.runtime.name=n,r&&(i?o[M.expose]=n:o.ctx.set(n,o)),o.ctx.on("ready",async()=>{await Promise.resolve(),await o.start(),r||o.ctx.set(n,o)}),o.ctx.on("dispose",()=>o.stop()),o}start(){}stop(){}[M.filter](e){return e[M.isolate][this.name]===this.ctx[M.isolate][this.name]}[M.setup](){this.ctx=new Be}[M.extend](e){let i;return this[it.invoke]?i=rs(this.name,this,this[M.tracker]):i=Object.create(this),Object.assign(i,e)}static[Symbol.hasInstance](e){let i=e.constructor;for(;i;){if(i=i.prototype?.constructor,i===this)return!0;i=Object.getPrototypeOf(i)}return!1}},W(it,"Service"),F(it,"setup",M.setup),F(it,"invoke",M.invoke),F(it,"extend",M.extend),F(it,"tracker",M.tracker),F(it,"provide",M.provide),F(it,"immediate",M.immediate),it),sd=Object.defineProperty,od=Object.getOwnPropertyNames,Z=(t,e)=>sd(t,"name",{value:e,configurable:!0}),ad=(t,e)=>function(){return e||(0,t[od(t)[0]])((e={exports:{}}).exports,e),e.exports},ld=ad({"src/index.ts"(t,e){var R;var i=Symbol.for("schemastery"),n=Symbol.for("ValidationError");globalThis.__schemastery_index__??(globalThis.__schemastery_index__=0);var r=(R=class extends TypeError{constructor(v,w){let S="$";for(const k of w.path||[])typeof k=="string"?S+="."+k:typeof k=="number"?S+="["+k+"]":typeof k=="symbol"&&(S+=`[Symbol(${k.toString()})]`);S.startsWith(".")&&(S=S.slice(1));super((S==="$"?"":`${S} `)+v);F(this,"name","ValidationError");this.options=w}static is(v){return!!v?.[n]}},Z(R,"ValidationError"),R);Object.defineProperty(r.prototype,n,{value:!0});var s=Z(function(y){const g=Z(function(v,w={}){return s.resolve(v,g,w)[0]},"schema");if(y.refs){const v=It(y.refs,S=>new s(S)),w=Z(S=>v[S],"getRef");for(const S in v){const k=v[S];k.sKey=w(k.sKey),k.inner=w(k.inner),k.list=k.list&&k.list.map(w),k.dict=k.dict&&It(k.dict,w)}return v[y.uid]}if(Object.assign(g,y),typeof g.callback=="string")try{g.callback=new Function("return "+g.callback)()}catch{}return Object.defineProperty(g,"uid",{value:globalThis.__schemastery_index__++}),Object.setPrototypeOf(g,s.prototype),g.meta||(g.meta={}),g.toString=g.toString.bind(g),g},"Schema");s.prototype=Object.create(Function.prototype),s.prototype[i]=!0,s.ValidationError=r;var o;s.prototype.toJSON=Z(function(){var v;if(o)return o[v=this.uid]??(o[v]=JSON.parse(JSON.stringify({...this}))),this.uid;o={[this.uid]:{...this}},o[this.uid]=JSON.parse(JSON.stringify({...this}));const g={uid:this.uid,refs:o};return o=void 0,g},"toJSON"),s.prototype.set=Z(function(g,v){return this.dict[g]=v,this},"set"),s.prototype.push=Z(function(g){return this.list.push(g),this},"push");function a(y,g){const v=typeof y=="string"?{"":y}:{...y};for(const w in g){const S=g[w];S?.$description||S?.$desc?v[w]=S.$description||S.$desc:typeof S=="string"&&(v[w]=S)}return v}Z(a,"mergeDesc");function l(y){return y?.$value??y?.$inner}Z(l,"getInner");function c(y){return la(y??{},g=>!g.startsWith("$"))}Z(c,"extractKeys"),s.prototype.i18n=Z(function(g){const v=s(this),w=a(v.meta.description,g);return Object.keys(w).length&&(v.meta.description=w),v.dict&&(v.dict=It(v.dict,(S,k)=>S.i18n(It(g,j=>l(j)?.[k]??j?.[k])))),v.list&&(v.list=v.list.map((S,k)=>S.i18n(It(g,(j={})=>Array.isArray(l(j))?l(j)[k]:Array.isArray(j)?j[k]:c(j))))),v.inner&&(v.inner=v.inner.i18n(It(g,S=>l(S)?l(S):c(S)))),v.sKey&&(v.sKey=v.sKey.i18n(It(g,S=>S?.$key))),v},"i18n"),s.prototype.extra=Z(function(g,v){const w=s(this);return w.meta={...w.meta,[g]:v},w},"extra");for(const y of["required","disabled","collapse","hidden","loose"])Object.assign(s.prototype,{[y](g=!0){const v=s(this);return v.meta={...v.meta,[y]:g},v}});s.prototype.deprecated=Z(function(){var v;const g=s(this);return(v=g.meta).badges||(v.badges=[]),g.meta.badges.push({text:"deprecated",type:"danger"}),g},"deprecated"),s.prototype.experimental=Z(function(){var v;const g=s(this);return(v=g.meta).badges||(v.badges=[]),g.meta.badges.push({text:"experimental",type:"warning"}),g},"experimental"),s.prototype.pattern=Z(function(g){const v=s(this),w=ca(g,["source","flags"]);return v.meta={...v.meta,pattern:w},v},"pattern"),s.prototype.simplify=Z(function(g){if(Zt(g,this.meta.default,this.type==="dict"))return null;if(be(g))return g;if(this.type==="object"||this.type==="dict"){const v={};for(const w in g){const k=(this.type==="object"?this.dict[w]:this.inner)?.simplify(g[w]);(this.type==="dict"||!be(k))&&(v[w]=k)}return Zt(v,this.meta.default,this.type==="dict")?null:v}else if(this.type==="array"||this.type==="tuple"){const v=[];return g.forEach((w,S)=>{const k=this.type==="array"?this.inner:this.list[S],j=k?k.simplify(w):w;v.push(j)}),v}else if(this.type==="intersect"){const v={};for(const w of this.list)Object.assign(v,w.simplify(g));return v}else if(this.type==="union")for(const v of this.list)try{return s.resolve(g,v,{}),v.simplify(g)}catch{}return g},"simplify"),s.prototype.toString=Z(function(g){return P[this.type]?.(this,g)??`Schema<${this.type}>`},"toString"),s.prototype.role=Z(function(y,g){const v=s(this);return v.meta={...v.meta,role:y,extra:g},v},"role");for(const y of["default","link","comment","description","max","min","step"])Object.assign(s.prototype,{[y](g){const v=s(this);return v.meta={...v.meta,[y]:g},v}});var u={};s.extend=Z(function(g,v){u[g]=v},"extend"),s.resolve=Z(function(g,v,w={},S=!1){if(!v)return[g];if(w.ignore?.(g,v))return[g];if(be(g)&&v.type!=="lazy"){if(v.meta.required)throw new r("missing required value",w);let j=v,z=v.meta.default;for(;j?.type==="intersect"&&be(z);)j=j.list[0],z=j?.meta.default;if(be(z))return[g];g=Dn(z)}const k=u[v.type];if(!k)throw new r(`unsupported type "${v.type}"`,w);try{return k(g,v,w,S)}catch(j){if(!v.meta.loose)throw j;return[v.meta.default]}},"resolve"),s.from=Z(function(g){if(be(g))return s.any();if(["string","number","boolean"].includes(typeof g))return s.const(g).required();if(g[i])return g;if(typeof g=="function")switch(g){case String:return s.string().required();case Number:return s.number().required();case Boolean:return s.boolean().required();case Function:return s.function().required();default:return s.is(g).required()}else throw new TypeError(`cannot infer schema from ${g}`)},"from"),s.lazy=Z(function(g){const v=Z(()=>(w.inner[i]||(w.inner=w.builder(),w.inner.meta={...w.meta,...w.inner.meta}),w.inner.toJSON()),"toJSON"),w=new s({type:"lazy",builder:g,inner:{toJSON:v}});return w},"lazy"),s.natural=Z(function(){return s.number().step(1).min(0)},"natural"),s.percent=Z(function(){return s.number().step(.01).min(0).max(1).role("slider")},"percent"),s.date=Z(function(){return s.union([s.is(Date),s.transform(s.string().role("datetime"),(g,v)=>{const w=new Date(g);if(isNaN(+w))throw new r(`invalid date "${g}"`,v);return w},!0)])},"date"),s.regExp=Z(function(g=""){return s.union([s.is(RegExp),s.transform(s.string().role("regexp",{flag:g}),(v,w)=>{try{return new RegExp(v,g)}catch(S){throw new r(S.message,w)}},!0)])},"regExp"),s.arrayBuffer=Z(function(g){return s.union([s.is(ArrayBuffer),s.is(SharedArrayBuffer),s.transform(s.any(),(v,w)=>{if(gt.isSource(v))return gt.fromSource(v);throw new r(`expected ArrayBufferSource but got ${v}`,w)},!0),...g?[s.transform(s.string(),(v,w)=>{try{return g==="base64"?gt.fromBase64(v):gt.fromHex(v)}catch(S){throw new r(S.message,w)}},!0)]:[]])},"arrayBuffer"),s.extend("lazy",(y,g,v,w)=>(g.inner[i]||(g.inner=g.builder(),g.inner.meta={...g.meta,...g.inner.meta}),s.resolve(y,g.inner,v,w))),s.extend("any",y=>[y]),s.extend("never",(y,g,v)=>{throw new r(`expected nullable but got ${y}`,v)}),s.extend("const",(y,{value:g},v)=>{if(Zt(y,g))return[g];throw new r(`expected ${g} but got ${y}`,v)});function d(y,g,v,w,S=!1){const{max:k=1/0,min:j=-1/0}=g;if(y>k)throw new r(`expected ${v} <= ${k} but got ${y}`,w);if(y<j&&!S)throw new r(`expected ${v} >= ${j} but got ${y}`,w)}Z(d,"checkWithinRange"),s.extend("string",(y,{meta:g},v)=>{if(typeof y!="string")throw new r(`expected string but got ${y}`,v);if(g.pattern){const w=new RegExp(g.pattern.source,g.pattern.flags);if(!w.test(y))throw new r(`expect string to match regexp ${w}`,v)}return d(y.length,g,"string length",v),[y]});function h(y,g){const v=y.toString();if(v.includes("e"))return y*Math.pow(10,g);const w=v.indexOf(".");if(w===-1)return y*Math.pow(10,g);const S=v.slice(w+1),k=v.slice(0,w);return S.length<=g?+(k+S.padEnd(g,"0")):+(k+S.slice(0,g)+"."+S.slice(g))}Z(h,"decimalShift");function p(y,g,v){if(v=Math.abs(v),!/^\d+\.\d+$/.test(v.toString()))return(y-g)%v===0;const w=v.toString().indexOf("."),S=v.toString().slice(w+1).length;return Math.abs(h(y,S)-h(g,S))%h(v,S)===0}Z(p,"isMultipleOf"),s.extend("number",(y,{meta:g},v)=>{if(typeof y!="number")throw new r(`expected number but got ${y}`,v);d(y,g,"number",v);const{step:w}=g;if(w&&!p(y,g.min??0,w))throw new r(`expected number multiple of ${w} but got ${y}`,v);return[y]}),s.extend("boolean",(y,g,v)=>{if(typeof y=="boolean")return[y];throw new r(`expected boolean but got ${y}`,v)}),s.extend("bitset",(y,{bits:g,meta:v},w)=>{let S=0,k=[];if(typeof y=="number"){S=y;for(const j in g)y&g[j]&&k.push(j)}else if(Array.isArray(y)){k=y;for(const j of k){if(typeof j!="string")throw new r(`expected string but got ${j}`,w);j in g&&(S|=g[j])}}else throw new r(`expected number or array but got ${y}`,w);return S===v.default?[S]:[S,k]}),s.extend("function",(y,g,v)=>{if(typeof y=="function")return[y];throw new r(`expected function but got ${y}`,v)}),s.extend("is",(y,{constructor:g},v)=>{if(typeof g=="function"){if(y instanceof g)return[y];throw new r(`expected ${g.name} but got ${y}`,v)}else{if(be(y))throw new r(`expected ${g} but got ${y}`,v);let w=Object.getPrototypeOf(y);for(;w;){if(w.constructor?.name===g)return[y];w=Object.getPrototypeOf(w)}throw new r(`expected ${g} but got ${y}`,v)}});function f(y,g,v,w){try{const[S,k]=s.resolve(y[g],v,{...w,path:[...w.path||[],g]});return k!==void 0&&(y[g]=k),S}catch(S){if(!w?.autofix)throw S;return delete y[g],v.meta.default}}Z(f,"property"),s.extend("array",(y,{inner:g,meta:v},w)=>{if(!Array.isArray(y))throw new r(`expected array but got ${y}`,w);return d(y.length,v,"array length",w,!be(g.meta.default)),[y.map((S,k)=>f(y,k,g,w))]}),s.extend("dict",(y,{inner:g,sKey:v},w,S)=>{if(!Mn(y))throw new r(`expected object but got ${y}`,w);const k={};for(const j in y){let z;try{z=s.resolve(j,v,w)[0]}catch(mt){if(S)continue;throw mt}k[z]=f(y,j,g,w),y[z]=y[j],j!==z&&delete y[j]}return[k]}),s.extend("tuple",(y,{list:g},v,w)=>{if(!Array.isArray(y))throw new r(`expected array but got ${y}`,v);const S=g.map((k,j)=>f(y,j,k,v));return w?[S]:(S.push(...y.slice(g.length)),[S])});function _(y,g){for(const v in g)v in y||(y[v]=g[v])}Z(_,"merge"),s.extend("object",(y,{dict:g},v,w)=>{if(!Mn(y))throw new r(`expected object but got ${y}`,v);const S={};for(const k in g){const j=f(y,k,g[k],v);(!be(j)||k in y)&&(S[k]=j)}return w||_(S,y),[S]}),s.extend("union",(y,{list:g,toString:v},w,S)=>{for(const k of g)try{return s.resolve(y,k,w,S)}catch{}throw new r(`expected ${v()} but got ${JSON.stringify(y)}`,w)}),s.extend("intersect",(y,{list:g,toString:v},w,S)=>{if(!g.length)return[y];let k;for(const j of g){const z=s.resolve(y,j,w,!0)[0];if(!be(z))if(be(k))k=z;else{if(typeof k!=typeof z)throw new r(`expected ${v()} but got ${JSON.stringify(y)}`,w);if(typeof z=="object")_(k??(k={}),z);else if(k!==z)throw new r(`expected ${v()} but got ${JSON.stringify(y)}`,w)}}return!S&&Mn(y)&&_(k,y),[k]}),s.extend("transform",(y,{inner:g,callback:v,preserve:w},S)=>{const[k,j=y]=s.resolve(y,g,S,!0);return w?[v(k)]:[v(k),v(j)]});var P={};function C(y,g,v){P[y]=v,Object.assign(s,{[y](...w){const S=new s({type:y});return g.forEach((k,j)=>{switch(k){case"sKey":S.sKey=w[j]??s.string();break;case"inner":S.inner=s.from(w[j]);break;case"list":S.list=w[j].map(s.from);break;case"dict":S.dict=It(w[j],s.from);break;case"bits":{S.bits={};for(const z in w[j])typeof w[j][z]=="number"&&(S.bits[z]=w[j][z]);break}case"callback":{const z=S.callback=w[j];z.toJSON||(z.toJSON=()=>z.toString());break}case"constructor":{const z=S.constructor=w[j];typeof z=="function"&&(z.toJSON||(z.toJSON=()=>z.name));break}default:S[k]=w[j]}}),y==="object"||y==="dict"?S.meta.default={}:y==="array"||y==="tuple"?S.meta.default=[]:y==="bitset"&&(S.meta.default=0),S}})}Z(C,"defineMethod"),C("is",["constructor"],({constructor:y})=>typeof y=="function"?y.name:y),C("any",[],()=>"any"),C("never",[],()=>"never"),C("const",["value"],({value:y})=>typeof y=="string"?JSON.stringify(y):y),C("string",[],()=>"string"),C("number",[],()=>"number"),C("boolean",[],()=>"boolean"),C("bitset",["bits"],()=>"bitset"),C("function",[],()=>"function"),C("array",["inner"],({inner:y})=>`${y.toString(!0)}[]`),C("dict",["inner","sKey"],({inner:y,sKey:g})=>`{ [key: ${g.toString()}]: ${y.toString()} }`),C("tuple",["list"],({list:y})=>`[${y.map(g=>g.toString()).join(", ")}]`),C("object",["dict"],({dict:y})=>Object.keys(y).length===0?"{}":`{ ${Object.entries(y).map(([g,v])=>`${g}${v.meta.required?"":"?"}: ${v.toString()}`).join(", ")} }`),C("union",["list"],({list:y},g)=>{const v=y.map(({toString:w})=>w()).join(" | ");return g?`(${v})`:v}),C("intersect",["list"],({list:y})=>`${y.map(g=>g.toString(!0)).join(" & ")}`),C("transform",["inner","callback","preserve"],({inner:y},g)=>y.toString(g)),e.exports=s}});const L=ld();var ls=(t=>(t[t.debug=-1]="debug",t[t.log=0]="log",t[t.info=1]="info",t[t.warn=2]="warn",t[t.error=3]="error",t[t.silent=4]="silent",t))(ls||{});const cs=globalThis||window,us=Symbol.for("__IPE_LOGGER_COLOR_MAP__");cs[us]||(cs[us]=new Map);const fs=cs[us];function Fn(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=(e>>>0)*16777619;return e>>>0}const va=[[350,360],[0,15],[15,30],[200,230],[230,250],[250,280],[280,310],[310,330],[140,160],[160,180]];function cd(t,e){const i=va.length,n=Fn(t)%i,[r,s]=va[n],o=s-r,a=Fn(t+":"+e),l=r+a%(o||1),c=Fn(t+":s"),u=Fn(t+":l");let d,h;if(e==="name")d=62+c%18,h=30+u%12;else{const p=l>=0&&l<50||l>330&&l<360,f=l>=200&&l<=300;d=55+c%20,f?h=55+u%8:p?h=48+u%6:h=50+u%8,d<60&&(d+=5)}return`hsl(${l}, ${d}%, ${h}%)`}function Bn(t,e){if(e)return fs.set(t,e),e;const i=fs.get(t);if(i)return i;const n=t.startsWith("name:")?"name":"group",r=cd(t,n);return fs.set(t,r),r}let wa=class kf{constructor(e={}){this._custom=i=>{if(!this._enabled(i.level))return _a;const[n,r]=this._prefix(i.label);return this._consoleMethod(i.method).bind(console,n,...r)},this._name=e.name,this._nameColor=e.color,this._groupPath=e._groupPath?[...e._groupPath]:[],this._dynamicLevels={...e._dynamicLevels},this._levelRef=e._levelRef??{value:e.level??1},this._name&&Bn(`name:${this._name}`,this._nameColor),this._installBuiltinLevels();for(const i of Object.keys(this._dynamicLevels))this._installLevelGetter(i,this._dynamicLevels[i]);return fd(this)}get level(){return this._levelRef.value}set level(e){this._levelRef.value=e}group(e,i){return e&&Bn(`group:${e}`,i?.color),new kf({name:this._name,color:this._nameColor,_groupPath:[...this._groupPath,e],_dynamicLevels:this._dynamicLevels,_levelRef:this._levelRef})}defineLevel(e,i){this._dynamicLevels[e]={...i},this._installLevelGetter(e,i)}get debug(){return this._method("debug")}get log(){return this._method("log")}get info(){return this._method("info")}get warn(){return this._method("warn")}get error(){return this._method("error")}_installBuiltinLevels(){}_installLevelGetter(e,i){Object.defineProperty(this,e,{configurable:!0,enumerable:!1,get:()=>this._custom(i)})}_method(e){const i=ud[e];if(!this._enabled(i.level))return _a;const[n,r]=this._prefix(i.label);return this._consoleMethod(e).bind(console,n,...r)}_consoleMethod(e){return(console[e]||console.log).bind(console)}_enabled(e){return e>=this._levelRef.value&&this._levelRef.value!==4}_prefix(e){const i=[];let n="";if(this._name){const r=Bn(`name:${this._name}`,this._nameColor);n+=`%c${this._name}%c`,i.push(`background:${r}; color:#fff; padding:1px 4px; border-radius:2px; font-weight:700;`,xa)}if(e&&(n+=` ${e}`),this._groupPath.length){const r=this._groupPath.join("/"),s=Bn(`group:${r}`);n+=` %c${r}%c`,i.push(`color:${s}; text-decoration: underline;`,xa)}return[n,i]}};const _a=()=>{},xa="color:inherit; background:transparent; text-decoration:none;",ud={debug:{level:-1,label:"",method:"debug"},log:{level:0,label:"",method:"log"},info:{level:1,label:"[I]",method:"info"},warn:{level:2,label:"[W]",method:"warn"},error:{level:3,label:"[E]",method:"error"}};function fd(t){const e=function(i,n){return t.group(i,n)};return new Proxy(e,{get(i,n,r){return t[n]},set(i,n,r){return t[n]=r,!0},apply(i,n,r){return t.group(r[0],r[1])},has(i,n){return n in t}})}function Sa(t){return new wa(t)}var Je=(t=>(t.BODY_USED="BODY_USED",t.NO_BODY_READER="NO_BODY_READER",t.TIMEOUT="TIMEOUT",t.NETWORK_ERROR="NETWORK_ERROR",t.BODY_NOT_ALLOWED="BODY_NOT_ALLOWED",t.HOOK_CONTEXT_CHANGED="HOOK_CONTEXT_CHANGED",t.ABORTED_BY_HOOK="ABORTED_BY_HOOK",t.INVALID_HOOK_CALLBACK="INVALID_HOOK_CALLBACK",t.UNEXPECTED_HOOK_RETURN="UNEXPECTED_HOOK_RETURN",t))(Je||{});let qe=class Ef extends Error{constructor(i,n,r,s){super(n,s);F(this,"name","FexiosError");this.code=i,this.context=r}static is(i){return i?.constructor===Ef}},dd=class $f extends qe{constructor(i,n,r){super(n.statusText,i,void 0,r);F(this,"name","FexiosResponseError");this.response=n}static is(i){return i?.constructor===$f}};function hd(t,e=2048){if(!(t instanceof Uint8Array))throw new TypeError("Input must be a Uint8Array");if(t.length===0)return!0;const i=Math.min(Math.max(t.length,256),e),n=t.slice(0,i);if(pd(n))return!1;const r=md(n);if(r.nullByteRatio>.05||r.highByteRatio>.95)return!1;const s=["utf-8","utf-16le","utf-16be","iso-8859-1"];let o=-1,a=!1;for(const l of s)try{const c=new TextDecoder(l,{fatal:!0}).decode(n),u=gd(c);u>o&&(o=u,a=u>.7)}catch{continue}return a}function pd(t){if(t.length<4)return!1;const e=[[137,80,78,71],[255,216,255],[71,73,70],[37,80,68,70],[80,75,3,4],[80,75,5,6],[80,75,7,8],[127,69,76,70],[77,90],[202,254,186,190],[0,0,1,0],[82,73,70,70]];for(const i of e)if(t.length>=i.length){let n=!0;for(let r=0;r<i.length;r++)if(t[r]!==i[r]){n=!1;break}if(n)return!0}return!1}function md(t){let e=0,i=0,n=0;for(const r of t)r===0&&e++,r>127&&i++,(r<32&&r!==9&&r!==10&&r!==13||r===127)&&n++;return{nullByteRatio:e/t.length,highByteRatio:i/t.length,controlCharRatio:n/t.length}}function gd(t){if(t.length===0)return 1;let e=1,i=0;for(let r=0;r<t.length;r++){const s=t[r].charCodeAt(0);s>=32&&s<=126||s===9||s===10||s===13||s===32?i++:s>127&&s<65534?!yd(s)&&!bd(s)&&i++:e-=.1}const n=i/t.length;return e*=n,vd(t)&&(e*=1.1),Math.max(0,Math.min(1,e))}function yd(t){return t>=0&&t<=31||t>=127&&t<=159}function bd(t){return t>=57344&&t<=63743||t>=983040&&t<=1048573||t>=1048576&&t<=1114109}function vd(t){return[/\b\w+\b/,/[.!?]+\s/,/\s+/,/[a-zA-Z]{3,}/,/[\u4e00-\u9fa5]+/,/\d+/].some(e=>e.test(t))}function ct(t){if(typeof t!="object"||t===null||Object.prototype.toString.call(t)!=="[object Object]")return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}const Vi=(t,...e)=>{const i=r=>{if(Array.isArray(r))return r.slice();if(ct(r)){const s={};for(const o of Reflect.ownKeys(r))s[o]=i(r[o]);return s}return r},n=i(t);for(const r of e)if(r!=null)for(const s of Reflect.ownKeys(r)){const o=r[s];if(typeof o>"u")continue;const a=n[s];ct(a)&&ct(o)?n[s]=Vi(a,o):n[s]=i(o)}return n};let Gi=class{constructor(e,i,n){F(this,"ok");F(this,"status");F(this,"statusText");F(this,"headers");this.rawResponse=e,this.data=i,this.ok=e.ok,this.status=e.status,this.statusText=e.statusText,this.headers=e.headers,Object.entries(n||{}).forEach(([r,s])=>{this[r]=s})}};async function ka(t,e,i){if(t.bodyUsed)throw new qe(Je.BODY_USED,"Response body has already been used or locked");const n=t.headers.get("content-type")||"",r=Number(t.headers.get("content-length"))||0,s=(a,l)=>l==="json"||a.startsWith("application/json"),o=(a,l,c)=>c==="blob"||a.startsWith("image/")&&!a.startsWith("image/svg")||a.startsWith("video/")||a.startsWith("audio/")||!hd(l);if((t.status===101||t.status===426||t.headers.get("upgrade"))&&typeof globalThis.WebSocket<"u"){const a=new WebSocket(t.url);return await new Promise((l,c)=>{a.onopen=l,a.onerror=c}),new Gi(t,a,{ok:!0,status:101,statusText:"Switching Protocols"})}else if(n.startsWith("text/event-stream")&&!["text","json"].includes(e||"")&&typeof globalThis.EventSource<"u"){const a=new EventSource(t.url);return await new Promise((l,c)=>{a.onopen=l,a.onerror=c}),new Gi(t,a)}else{if(e==="stream")return new Gi(t,t.body);{const a=t.clone().body?.getReader();if(!a)throw new qe(Je.NO_BODY_READER,"Failed to get ReadableStream from response body");let l=new Uint8Array;for(;;){const{done:u,value:d}=await a.read();if(u)break;if(d&&(l=new Uint8Array([...l,...d]),i&&r>0)){const h=Math.min(l.length/r,1);i(h,l)}}const c=new Gi(t,void 0);if(e==="arrayBuffer")return c.data=l.buffer,c;if(s(n,e))try{const u=new TextDecoder().decode(l);c.data=JSON.parse(u)}catch{}if(typeof c.data!="string"&&o(n,l,e)?c.data=new Blob([l],{type:t.headers.get("content-type")||void 0}):c.data=new TextDecoder().decode(l),typeof c.data=="string"&&e!=="text"){const u=c.data.trim(),d=u[0],h=u[u.length-1];if(d==="{"&&h==="}"||d==="["&&h==="]")try{c.data=JSON.parse(c.data)}catch{}}if(typeof c.data>"u"&&(c.data=l.length>0?l:void 0),c.ok)return c;throw new dd(`Request failed with status code ${t.status}`,c)}}}var qn;(t=>{t.makeSearchParams=r=>{if(!r)return new URLSearchParams;if(r instanceof URLSearchParams)return r;if(typeof r!="object"||r?.constructor!==Object)throw new TypeError("only plain object is supported");const s=new URLSearchParams,o=(c,u)=>{u!=null&&s.append(c,u)},a=(c,u)=>{u!=null&&s.set(c,u)},l=(c,u)=>{if(u!=null){if(Array.isArray(u)){for(const d of u)o(c,d?.toString());return}if(typeof u=="object"&&u.constructor===Object){for(const[d,h]of Object.entries(u)){if(h==null)continue;const p=d.endsWith("[]"),f=p?d.slice(0,-2):d,_=`${c}[${f}]`;if(p){const P=`${_}[]`;if(Array.isArray(h))for(const C of h)o(P,C?.toString());else typeof h=="object"&&h!==null&&h.constructor===Object?l(`${_}[]`,h):o(P,h?.toString())}else if(Array.isArray(h))for(const P of h)o(_,P?.toString());else typeof h=="object"&&h!==null&&h.constructor===Object?l(_,h):a(_,h?.toString())}return}a(c,u?.toString())}};for(const[c,u]of Object.entries(r))l(c,u);return s},t.makeQueryString=r=>(0,t.makeSearchParams)(r).toString(),t.makeURL=(r,s,o,a)=>{const l=typeof window<"u"&&window.location?.origin||"http://localhost",c=typeof r=="string"?new URL(r,a??l):new URL(r),u=(0,t.toQueryRecord)(c.searchParams),d=(0,t.mergeQueries)(u,s||{}),h=(0,t.makeSearchParams)(d);return c.search=h.toString(),c.hash=o||"",c},t.toQueryRecord=r=>{typeof r=="string"&&(r=(0,t.fromString)(r));const s={},o=l=>{if(!l.includes("["))return{path:[l],forceArray:!1};const c=[l.slice(0,l.indexOf("["))],u=/\[([^\]]*)\]/g;let d,h=!1,p=!1;for(;d=u.exec(l);)d[1]===""?(h=!0,p=!0):(c.push(d[1]),p=!1);return h&&p&&(c[c.length-1]=c[c.length-1]+"[]"),{path:c,forceArray:h}},a=(l,c,u,d)=>{let h=l;for(let p=0;p<c.length;p++){const f=c[p];p===c.length-1?d?h[f]===void 0?h[f]=[u]:Array.isArray(h[f])?h[f].push(u):h[f]=[h[f],u]:h[f]===void 0?h[f]=u:Array.isArray(h[f])?h[f].push(u):h[f]=[h[f],u]:((h[f]===void 0||typeof h[f]!="object"||Array.isArray(h[f]))&&(h[f]={}),h=h[f])}};for(const[l,c]of r.entries()){const{path:u,forceArray:d}=o(String(l));a(s,u,c?.toString(),d)}return s},t.fromString=r=>{const s=r.trim();if(!s)return new URLSearchParams;if(s.startsWith("?"))return new URLSearchParams(s.slice(1));const o=s.indexOf("?");if(o>=0){const a=s.indexOf("#",o+1),l=s.slice(o+1,a>=0?a:void 0);return new URLSearchParams(l)}return new URLSearchParams(s)},t.mergeQueries=(r,...s)=>{const o=e(i(r));for(const a of s)a!=null&&n(o,i(a));return o};function e(r){if(Array.isArray(r))return r.map(e);if(ct(r)){const s={};for(const[o,a]of Object.entries(r))s[o]=e(a);return s}if(r instanceof Map){const s={};for(const[o,a]of r.entries())s[o]=e(a);return s}return r}function i(r){if(!r)return{};if(r instanceof URLSearchParams||r instanceof FormData||r instanceof Map)return(0,t.toQueryRecord)(r);if(typeof r=="string")return(0,t.toQueryRecord)((0,t.fromString)(r));if(ct(r))return r;throw new TypeError(`unsupported type transformation, got: ${Object.prototype.toString.call(r)}`)}function n(r,s){for(const[o,a]of Object.entries(s)){if(a===void 0)continue;if(a===null){delete r[o];continue}const l=r[o];ct(l)&&ct(a)?n(l,a):r[o]=e(a)}}})(qn||(qn={}));const Ea=function(t){const e=this.constructor.prototype,i=Reflect.get(e,t,e);function n(...r){return Reflect.apply(i,n,r)}Reflect.setPrototypeOf(n,e);for(const r of Reflect.ownKeys(i)){const s=Reflect.getOwnPropertyDescriptor(i,r);s&&Reflect.defineProperty(n,r,s)}return n};Ea.prototype=Object.create(Function.prototype);var Yi;(t=>{t.makeHeaders=e=>{if(!e)return new Headers;if(e instanceof Headers)return new Headers(e);const i=new Headers;if(e instanceof Map){for(const[n,r]of e.entries())if(r!=null)if(Array.isArray(r))for(const s of r)s!=null&&i.append(n,String(s));else i.append(n,String(r));return i}if(ct(e)){for(const[n,r]of Object.entries(e))if(r!=null)if(Array.isArray(r))for(const s of r)s!=null&&i.append(n,String(s));else i.append(n,String(r));return i}throw new TypeError("only plain object, Map/ReadonlyMap, or Headers is supported")},t.toHeaderRecord=e=>{if(e instanceof Headers){const i={};return e.forEach((n,r)=>{i[r]=i[r]?[...i[r],n]:[n]}),i}if(e instanceof Map){const i={};for(const[n,r]of e.entries())if(r!=null)if(Array.isArray(r)){const s=r.filter(o=>o!=null).map(o=>String(o));s.length&&(i[n]=(i[n]??[]).concat(s))}else{const s=String(r);i[n]=i[n]?[...i[n],s]:[s]}return i}throw new TypeError(`unsupported type transformation, got: ${Object.prototype.toString.call(e)}`)},t.mergeHeaders=(e,...i)=>{const n=e instanceof Headers?new Headers(e):(0,t.makeHeaders)(e),r=s=>{for(const[o,a]of Object.entries(s))if(a!==void 0){if(a===null){n.delete(o);continue}if(Array.isArray(a)){n.delete(o);for(const l of a)l!=null&&n.append(o,String(l))}else n.set(o,String(a))}};for(const s of i){if(s==null)continue;if(s instanceof Headers){s.forEach((a,l)=>{n.set(l,a)});continue}if(ct(s)){r(s);continue}const o=(0,t.toHeaderRecord)(s);for(const[a,l]of Object.entries(o)){n.delete(a);for(const c of l)n.append(a,c)}}return n}})(Yi||(Yi={}));let ds=(fe=class extends Ea{constructor(i={}){super("request");F(this,"baseConfigs");F(this,"hooks",[]);F(this,"mergeQueries",qn.mergeQueries);F(this,"mergeHeaders",Yi.mergeHeaders);F(this,"interceptors",{request:this.createInterceptor("beforeRequest"),response:this.createInterceptor("afterResponse")});F(this,"create",fe.create);F(this,"_plugins",new Map);F(this,"checkIsPlainObject",ct);F(this,"mergeQuery",this.mergeQueries);this.baseConfigs=Vi(fe.DEFAULT_CONFIGS,i),fe.ALL_METHODS.forEach(n=>this.createMethodShortcut(n.toLowerCase()))}async request(i,n){let r=n=n||{};if(typeof i=="string"||i instanceof URL?r.url=i.toString():typeof i=="object"&&(r=Vi(i,r)),r=await this.emit("beforeInit",r,{shouldAdjustRequestParams:!0,shouldHandleShortCircuitResponse:!0}),r[fe.FINAL_SYMBOL])return r;if(fe.METHODS_WITHOUT_BODY.includes(r.method?.toLocaleLowerCase())&&r.body)throw new qe(Je.BODY_NOT_ALLOWED,`Request method "${r.method}" does not allow body`);if(r=await this.emit("beforeRequest",r,{shouldAdjustRequestParams:!0,shouldHandleShortCircuitResponse:!0,preAdjust:!0,requestOptionsOverridesURLSearchParams:!0,preRequestOptionsOverridesURLSearchParams:!0,postRequestOptionsOverridesURLSearchParams:!0}),r[fe.FINAL_SYMBOL])return r;let s;const o={};if(typeof r.body<"u"&&r.body!==null&&(r.body instanceof Blob||r.body instanceof FormData||r.body instanceof URLSearchParams?s=r.body:typeof r.body=="object"&&r.body!==null?(s=JSON.stringify(r.body),r.headers=this.mergeHeaders(r.headers,{"Content-Type":"application/json"})):s=r.body),!Yi.makeHeaders(n.headers||{}).get("content-type")&&s&&(s instanceof FormData||s instanceof URLSearchParams?o["content-type"]=null:typeof s=="string"&&typeof r.body=="object"?o["content-type"]="application/json":s instanceof Blob&&(o["content-type"]=s.type||"application/octet-stream")),r.body=s,r=await this.emit("afterBodyTransformed",r,{shouldAdjustRequestParams:!0,shouldHandleShortCircuitResponse:!0,preAdjust:!0,postRequestOptionsOverridesURLSearchParams:!0}),r[fe.FINAL_SYMBOL])return r;const a=r.abortController||globalThis.AbortController?new AbortController:void 0,l=r.baseURL||this.baseConfigs.baseURL||globalThis.location?.href||"http://localhost",c=new URL(r.url.toString(),l),u=qn.makeURL(c,r.query,c.hash).toString(),d=new Request(u,{method:r.method||"GET",credentials:r.credentials,cache:r.cache,mode:r.mode,headers:Yi.mergeHeaders(this.baseConfigs.headers,r.headers||{},o),body:r.body,signal:a?.signal});if(r.rawRequest=d,r=await this.emit("beforeActualFetch",r,{shouldHandleShortCircuitResponse:!0}),r[fe.FINAL_SYMBOL])return r;const h=r.timeout||this.baseConfigs.timeout||60*1e3;if(r.url.startsWith("ws"))try{const f=new WebSocket(r.url);return await new Promise((_,P)=>{const C=setTimeout(()=>{P(new qe(Je.TIMEOUT,`WebSocket connection timed out after ${h}ms`,r))},h);f.onopen=()=>{clearTimeout(C),_()},f.onerror=R=>{clearTimeout(C),P(new qe(Je.NETWORK_ERROR,"WebSocket connection failed",r))},f.onclose=R=>{R.code!==1e3&&(clearTimeout(C),P(new qe(Je.NETWORK_ERROR,`WebSocket closed with code ${R.code}`,r)))}}),r.rawResponse=new Response,r.response=new Gi(r.rawResponse,f,{ok:!0,status:101,statusText:"Switching Protocols"}),r.data=f,r.headers=new Headers,this.emit("afterResponse",r)}catch(f){throw f instanceof qe?f:new qe(Je.NETWORK_ERROR,`WebSocket creation failed: ${f}`,r)}let p;try{a&&(p=setTimeout(()=>{a.abort()},h));const f=await(n.fetch||this.baseConfigs.fetch||globalThis.fetch)(r.rawRequest).catch(_=>{throw p&&clearTimeout(p),a?.signal.aborted?new qe(Je.TIMEOUT,`Request timed out after ${h}ms`,r):new qe(Je.NETWORK_ERROR,_.message,r)});return p&&clearTimeout(p),r.rawResponse=f,r.response=await ka(f,r.responseType,(_,P)=>{n?.onProgress?.(_,P)}),r.data=r.response.data,r.headers=r.response.headers,this.emit("afterResponse",r)}catch(f){throw p&&clearTimeout(p),f}}normalizeContext(i,n={}){const r=i,s=r.baseURL||this.baseConfigs.baseURL||globalThis.location?.href||"http://localhost",o=new URL(s,globalThis.location?.href||"http://localhost"),a=new URL(r.url.toString(),o),l=!!r[fe.NORMALIZED_SYMBOL];r.baseURL=o?o.origin:a.origin;let c;l?c=n.requestOptionsOverridesURLSearchParams?this.mergeQueries({},a.search,r.query):this.mergeQueries({},r.query,a.search):(c=n.requestOptionsOverridesURLSearchParams?this.mergeQueries(o?.search||"",this.baseConfigs.query,a.search,r.query):this.mergeQueries(o?.search||"",this.baseConfigs.query,r.query,a.search),r[fe.NORMALIZED_SYMBOL]=!0),r.query=c;const u=new URL(a);return u.search="",r.url=u.toString(),r}async emit(i,n,r={}){const s=this.hooks.filter(o=>o.event===i);if(r?.shouldAdjustRequestParams&&r?.preAdjust)try{n=this.normalizeContext(n,{requestOptionsOverridesURLSearchParams:r.preRequestOptionsOverridesURLSearchParams})}catch{}try{let o=0;for(const a of s){const l=`${i}#${a.action.name||`anonymous#${o}`}`,c=Symbol("FEXIOS_HOOK_CONTEXT");n[c]=c;const u=n.url;let d="";try{const p=this.mergeQueries({},n.query||{});d=JSON.stringify(p)}catch{}let h=await a.action.call(this,n);if(h===void 0&&(h=n),h===!1)throw new qe(Je.ABORTED_BY_HOOK,`Request aborted by hook "${l}"`,n);if(h instanceof Response){const p=h,f={...n,rawResponse:p},_=await ka(p,n.responseType,(P,C)=>{n.onProgress?.(P,C)});if(f.response=_,f.data=_.data,f.headers=_.headers,i!=="afterResponse"){const P=await this.emit("afterResponse",f);return P[fe.FINAL_SYMBOL]=!0,P}else return f[fe.FINAL_SYMBOL]=!0,f}else if(typeof h=="object"&&h[c]===c)n=h;else{const p=globalThis["".concat("console")];try{throw new qe(Je.HOOK_CONTEXT_CHANGED,`Hook "${l}" should return the original FexiosContext or return false to abort the request, but got "${h}".`)}catch(f){p.warn(f.stack||f)}}if(r?.shouldAdjustRequestParams)try{const p=n.baseURL||this.baseConfigs.baseURL||globalThis.location?.href||"http://localhost",f=new URL(n.url.toString(),p);let _={};if(d)try{_=JSON.parse(d)}catch{}const P=n.query||{},C=this.mergeQueries(_,f.search,P);n.query=C;const R=new URL(f);R.search="",n.url=R.toString()}catch{}delete n[c],o++}}catch(o){return Promise.reject(o)}return n}on(i,n,r=!1){if(typeof n!="function")throw new qe(Je.INVALID_HOOK_CALLBACK,`Hook should be a function, but got "${typeof n}"`);return this.hooks[r?"unshift":"push"]({event:i,action:n}),this}off(i,n){return i==="*"||!i?this.hooks=this.hooks.filter(r=>r.action!==n):this.hooks=this.hooks.filter(r=>r.event!==i||r.action!==n),this}createInterceptor(i){return{handlers:()=>this.hooks.filter(n=>n.event===i).map(n=>n.action),use:(n,r=!1)=>this.on(i,n,r),clear:()=>{this.hooks=this.hooks.filter(n=>n.event!==i)}}}createMethodShortcut(i){return Reflect.defineProperty(this,i,{get:()=>(n,r,s)=>(fe.METHODS_WITHOUT_BODY.includes(i.toLocaleLowerCase())?s=r:(s=s||{},s.body=r),this.request(n,{...s,method:i}))}),this}extends(i){const n=new fe(Vi(this.baseConfigs,i));return n.hooks=[...this.hooks],n._plugins=new Map(this._plugins),n._plugins.forEach(async r=>{await n.plugin(r)}),n}static create(i){return new fe(i)}async plugin(i){if(typeof i?.name=="string"&&typeof i?.install=="function"){if(this._plugins.has(i.name))return this;const n=await i.install(this);if(this._plugins.set(i.name,i),n instanceof fe)return n}return this}},F(fe,"FINAL_SYMBOL",Symbol("FEXIOS_FINAL_CONTEXT")),F(fe,"NORMALIZED_SYMBOL",Symbol("FEXIOS_NORMALIZED_QUERY")),F(fe,"DEFAULT_CONFIGS",{baseURL:"",timeout:60*1e3,credentials:"same-origin",headers:{},query:{},responseType:void 0,fetch:globalThis.fetch}),F(fe,"ALL_METHODS",["get","post","put","patch","delete","head","options","trace"]),F(fe,"METHODS_WITHOUT_BODY",["get","head","options","trace"]),fe);const wd=ds.create,$a=wd();typeof globalThis<"u"?globalThis.fexios=$a:typeof window<"u"&&(window.fexios=$a);var Hn;(t=>{function e(n){return Array.isArray(n)?n.join("|"):typeof n=="boolean"||n===null?n?"1":void 0:typeof n=="number"?""+n:n}t.normalizeParamValue=e;function i(n){const r=o=>o&&(o instanceof URLSearchParams||o instanceof FormData);if(n==null)return;const s=new FormData;if(r(n))return n.forEach((o,a)=>{const l=e(o);l!=null&&s.append(a,l)}),s;if(ct(n))return Object.entries(n).forEach(([o,a])=>{const l=e(a);l!=null&&s.append(o,l)}),s}t.normalizeBody=i})(Hn||(Hn={}));var Qi=(t=>(t.HTTP_ERROR="HTTP_ERROR",t.LOGIN_FAILED="LOGIN_FAILED",t.LOGIN_RETRY_LIMIT_EXCEEDED="LOGIN_RETRY_LIMIT_EXCEEDED",t.TOKEN_RETRY_LIMIT_EXCEEDED="TOKEN_RETRY_LIMIT_EXCEEDED",t))(Qi||{});let He=class extends Error{constructor(e,i="",n){super(),this.code=e,this.message=i,this.cause=n,this.name="WikiSaikouError"}static is(e,i){return e instanceof this&&(i===void 0||e.code===i)}},bi=class Pf extends Error{constructor(e,i){super(),this.errors=e,this.cause=i,this.name="MediaWikiApiError",this.errors=Pf.normalizeErrors(e),this.message=e.map(n=>n.text).filter(Boolean).join(`
|
|
4
|
-
`),this.code=this.isBadTokenError()?"badtoken":this.errors[0]?.code||"Unknown Error"}get firstError(){return this.errors[0]}isBadTokenError(){return this.errors.some(e=>e.code==="badtoken")||["NeedToken","WrongToken"].includes(this.cause?.data?.login?.result)}toString(){return`[${this.name} ${this.code}]`}static is(e){return e instanceof this}static normalizeErrors(e){return Array.isArray(e)===!1?[]:e.filter(i=>typeof i=="object"&&!!i?.code).map(i=>i.text?i:i.info?{...i,text:i.info}:i["*"]?{...i,text:i["*"]}:{...i,text:""})}};(t=>{function e(s){if(s==null)return;if(s?.response?.data!==void 0)return s.response.data;if(s?.data!==void 0)return s.data;const o=s instanceof Error?s.cause:void 0;return o?.response?.data!==void 0?o.response.data:o?.data!==void 0?o.data:s||void 0}function i(s){return n(s).length>0}t.includesMediaWikiApiError=i,t.normalizeMwApiErrors=bi.normalizeErrors;function n(s){let o=e(s);if(typeof o!="object"||o===null)return[];const a=o?.error,l=o?.errors,c=[];return a&&c.push(a),Array.isArray(l)&&c.push(...l),(0,t.normalizeMwApiErrors)(c)}t.extractMediaWikiApiErrors=n;function r(s){if(bi.is(s))return s.isBadTokenError();{const o=n(s);return new bi(o).isBadTokenError()}}t.isBadTokenError=r})(He||(He={}));const Pa=Symbol.for("__FEXIOS_SAIKOU__");function Ca(t){const e=t instanceof ds?t:new ds({baseURL:t instanceof URL?t.toString():String(t),responseType:"json"});return e[Pa]||(Reflect.defineProperty(e,Pa,{get:()=>!0,enumerable:!1,configurable:!1}),e._tokens=new Map,e.on("afterResponse",i=>{const{data:n,rawRequest:r}=i,s=r?.headers.get("x-mw-token-name");s&&He.isBadTokenError(n)&&e._tokens.delete(s);const o=n?.query?.tokens;o&&typeof o=="object"&&Object.entries(o).forEach(([l,c])=>{typeof c=="string"&&e._tokens.set(l.replace(/token$/i,"").toLowerCase(),c)});const a=n?.login?.token;return typeof a=="string"&&e._tokens.set("login",a),i}),e.on("beforeInit",i=>{if(i.method?.toLowerCase()!=="post")return i;if(i.body===void 0||i.body===null)return i.body=void 0,i;const n=i.body=Hn.normalizeBody(i.body),r=new URLSearchParams(i.query);return n.has("format")&&r.delete("format"),n.has("formatversion")&&r.delete("formatversion"),n.has("action")&&r.delete("action"),n.has("origin")&&(r.set("origin",""+n.get("origin")),n.delete("origin")),i.query=Object.fromEntries(r.entries()),i}),e.on("beforeInit",i=>(i.query=Hn.normalizeBody(i.query)||{},i)),e.on("beforeRequest",i=>{const n=new URL(i.url),r=n.searchParams;if(globalThis.location&&(!r.has("origin")&&location.origin!==n.origin?(r.set("origin",location.origin),e.baseConfigs.credentials="include",e.baseConfigs.mode="cors"):location.origin===n.origin&&(r.delete("origin"),e.baseConfigs.credentials=void 0,e.baseConfigs.mode=void 0)),n.searchParams.has("origin")){const s=encodeURIComponent(n.searchParams.get("origin")||"").replace(/\./g,"%2E");i.query={},n.searchParams.delete("origin"),i.url=`${n}${n.search?"&":"?"}origin=${s}`}return i})),e}const ei=(t,...e)=>{const i=s=>Object.prototype.toString.call(s)==="[object Object]",n=s=>{if(Array.isArray(s))return s.slice();if(i(s)){const o={};for(const a of Reflect.ownKeys(s))o[a]=n(s[a]);return o}return s},r=n(t);for(const s of e)if(s!=null)for(const o of Reflect.ownKeys(s)){const a=s[o];if(typeof a>"u")continue;const l=r[o];i(l)&&i(a)?r[o]=ei(l,a):r[o]=n(a)}return r},_d=(t,e,i)=>{let n={...Ra.DEFAULT_CONFIGS};if(typeof t=="string"?n=ei(n,{baseURL:t,fexiosConfigs:e||{},defaultParams:i||{}}):typeof t=="object"&&t!==null&&(n=ei(n,t)),!n.baseURL&&typeof window=="object"&&window.mediaWiki){const{wgServer:r,wgScriptPath:s}=window.mediaWiki?.config?.get(["wgServer","wgScriptPath"])||{};typeof r=="string"&&typeof s=="string"&&(n.baseURL=`${r}${s}/api.php`)}if(typeof n.baseURL!="string")throw new Error("baseURL is required");return n},xd=()=>{},Sd=async(t,e)=>{let i=0;const{retry:n=3,onRetry:r=xd,shouldRetry:s=()=>!0}=e;let o;do try{return await t()}catch(a){if(o=a,s(a,i))r(a,i),i++;else throw a}while(i<n);throw o||new Error("Retry failed")};const Ji=class{constructor(e,i,n){this.version="7.1.2",this.token=this.getToken;const r=this.config=_d(e,i,n);this.request=Ca(r.baseURL)}setBaseURL(e){return this.config.baseURL=e,this.request.baseConfigs.baseURL=e,this}async get(e,i){return this.runRequestWithApiErrorMapping(()=>this.request.get("",ei({},this.config.fexiosConfigs,{query:ei(this.config.defaultParams,e)},i)))}async post(e,i){return this.runRequestWithApiErrorMapping(()=>this.request.post("",e,ei({},this.config.fexiosConfigs,{query:this.config.defaultParams},i)))}async runRequestWithApiErrorMapping(e){try{const i=await e();return this.handleApiResponse(i)}catch(i){throw this.config.throwOnApiError&&He.includesMediaWikiApiError(i)?new bi(He.extractMediaWikiApiErrors(i),i):i}}throwIfApiError(e){const i=He.extractMediaWikiApiErrors(e);if(i.length>0)throw new bi(i,e)}handleApiResponse(e){return this.config.throwOnApiError&&this.throwIfApiError(e.data),e}get tokens(){return this.request._tokens}async fetchTokens(e=["csrf"]){return this.config.fexiosConfigs.credentials="include",await this.get({action:"query",meta:"tokens",type:e}),this.tokens}async getToken(e="csrf",i=!1){return(!this.tokens.get(e)||i)&&(this.tokens.delete(e),await this.fetchTokens([e])),this.tokens.get(e)}badToken(e){return this.tokens.delete(e),this.tokens}async postWithToken(e,i,n){const{tokenName:r="token",retry:s=3,noCache:o=!1,fexiosOptions:a}=n||{};if(s<1)throw new He(Qi.TOKEN_RETRY_LIMIT_EXCEEDED,"The limit of the number of times to automatically re-acquire the token has been exceeded");let l=0;return Sd(async()=>{const c=await this.getToken(e,o||l>0);try{const u=await this.post({[r]:c,...i},ei(a||{},{headers:{"x-mw-token-name":e}}));if(He.isBadTokenError(u.data))throw u;return u}catch(u){throw He.isBadTokenError(u)||u?.ok===!1||bi.is(u)?u:new He(Qi.HTTP_ERROR,"Network/transport or SDK-internal error (not a MediaWiki API error)",u)}},{retry:s,onRetry:(c,u)=>{l=u+1},shouldRetry:c=>He.isBadTokenError(c)||c?.ok===!1}).catch(c=>{throw He.isBadTokenError(c)||c?.ok===!1?new He(Qi.TOKEN_RETRY_LIMIT_EXCEEDED,"Retry attempts for acquiring/using token exhausted",c):c})}postWithEditToken(e){return this.postWithToken("csrf",e)}get baseURL(){return this.config.baseURL}get defaultParams(){return this.config.defaultParams}get defaultOptions(){return this.config.fexiosConfigs}};Ji.INIT_DEFAULT_PARAMS={action:"query",errorformat:"plaintext",format:"json",formatversion:2},Ji.DEFAULT_CONFIGS={baseURL:void 0,fexiosConfigs:{responseType:"json"},defaultParams:Ji.INIT_DEFAULT_PARAMS,throwOnApiError:!1},Ji.createRequestHandler=Ca;let Ra=Ji;let kd=class extends Ra{async clientLogin(e,i,n){n||(n={}),!n.logincontinue&&!n.loginreturnurl&&(n.loginreturnurl=location?.origin);const r=await this.postWithToken("login",{action:"clientlogin",username:e,password:i,...n},{tokenName:"logintoken"});if(r?.data?.clientlogin?.status==="PASS")return r.data.clientlogin;throw new He(Qi.LOGIN_FAILED,r.data.clientlogin.message,r)}};class Ed{constructor(e,i={}){this.ctx=e,location?.href&&i?.baseURL?.toString()?.startsWith("/")&&(i.baseURL=new URL(i.baseURL,location.origin));const n=new kd({baseURL:i.baseURL.toString(),fexiosConfigs:{headers:{"x-api-user-agent":`InPageEdit-NEXT ${e.version}`,...i.headers},...i},throwOnApiError:!0});e.set("api",n)}}var $d=Object.create,hs=Object.defineProperty,Pd=Object.getOwnPropertyDescriptor,Aa=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ia=t=>{throw TypeError(t)},Cd=(t,e,i)=>e in t?hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Rd=(t,e)=>hs(t,"name",{value:e,configurable:!0}),Ad=t=>[,,,$d(t?.[Aa("metadata")]??null)],Id=["class","method","getter","setter","accessor","field","value","get","set"],Oa=t=>t!==void 0&&typeof t!="function"?Ia("Function expected"):t,Od=(t,e,i,n,r)=>({kind:Id[t],name:e,metadata:n,addInitializer:s=>i._?Ia("Already initialized"):r.push(Oa(s||null))}),Td=(t,e)=>Cd(e,Aa("metadata"),t[3]),Ld=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},Nd=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Pd(r,i));Rd(r,i);for(var f=n.length-1;f>=0;f--)l=Od(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,Oa(o)&&(r=o);return Td(t,r),p&&hs(r,i,p),u?c^4?s:p:r},Ta,ps,La;Ta=[$e(["wiki","wikiTitle"])];class zn extends(La=Ot){constructor(i){super(i,"currentPage",!1);Hi(this,Ve);this.ctx=i,this.url=new URL(window.location.href),this.isMainPage=void 0,this.wikiTitle=void 0}get logger(){return this.ctx.logger("CURRENT_PAGE")}async start(){await lt(this,Ve,oa).call(this),lt(this,Ve,Cf).call(this),window.addEventListener("popstate",lt(this,Ve,aa).bind(this)),this.logger.info("initialized",this.wikiTitle)}stop(){window.removeEventListener("popstate",lt(this,Ve,aa).bind(this))}get params(){return this.url.searchParams}get canonicalUrl(){const i=document.querySelector('link[rel="canonical"]')?.href;let n=null;return i&&(n=new URL(i,location.origin)),Reflect.defineProperty(this,"canonicalUrl",{get:()=>n}),n}get wikiAction(){return this.params.get("action")||"view"}}Ve=new WeakSet,oa=async function(){await lt(this,Ve,Af).call(this),await lt(this,Ve,Rf).call(this)},Cf=function(){const i=Symbol.for("InPageEdit.CurrentPageService.UrlChangeListenerInstalled");if(window[i])return;const n=history.pushState,r=history.replaceState;history.pushState=function(s,o,a){n.apply(this,[s,o,a]),window.dispatchEvent(new PopStateEvent("popstate",{state:s}))},history.replaceState=function(s,o,a){r.apply(this,[s,o,a]),window.dispatchEvent(new PopStateEvent("popstate",{state:s}))},window[i]=!0},aa=async function(i){const n=this.url,r=new URL(window.location.href);this.url=r,(n.pathname!==r.pathname||n.searchParams.get("title")!==r.searchParams.get("title")||n.searchParams.get("curid")!==r.searchParams.get("curid"))&&(await lt(this,Ve,oa).call(this),this.logger.info("location changed",r,this.wikiTitle))},Rf=async function(){const n=this.wikiTitle?.getMainDBKey()===this.ctx.wiki.mainPageName;return Reflect.defineProperty(this,"isMainPage",{get:()=>n}),n},Af=async function(){let i=null;return this.canonicalUrl?i=await this.ctx.wikiTitle.newTitleFromUrl(this.canonicalUrl):i=await this.ctx.wikiTitle.newTitleFromUrl(this.url),Object.freeze(i),Reflect.defineProperty(this,"wikiTitle",{get:()=>i}),i},ps=Ad(La),zn=Nd(ps,0,"CurrentPageService",Ta,zn),Ld(ps,1,zn);class Md extends Ot{constructor(e){super(e,"resourceLoader",!0),this.ctx=e}stop(){this.removeAll()}loadScript(e,i){if(!e)return Promise.resolve(null);const n=`script:${e}`,r=document.querySelector(`[data-ipe="${n}"]`);return r?Promise.resolve(r):new Promise((o,a)=>{const l=document.createElement("script");l.src=e,l.dataset.ipe=n,i&&Object.entries(i).forEach(([c,u])=>{typeof u>"u"||u===!1||u===null?l.removeAttribute(c):l.setAttribute(c,u)}),document.body.appendChild(l),l.onload=()=>o(l),l.onerror=c=>a(c)})}loadStyle(e,i){if(!e)return Promise.resolve(null);const n=`style:${e}`,r=document.querySelector(`[data-ipe="${n}"]`);return r?Promise.resolve(r):new Promise((o,a)=>{const l=document.createElement("link");l.rel="stylesheet",l.href=e,l.dataset.ipe=n,i&&Object.entries(i).forEach(([u,d])=>{typeof d>"u"||d===!1||d===null?l.removeAttribute(u):l.setAttribute(u,d)}),(document.querySelector('meta[name="ipe-styles"]')||(()=>{const u=document.createElement("meta");return u.id="ipe-styles",u.name="ipe-styles",document.head.insertAdjacentElement("afterbegin",u),u})()).before(l),l.onload=()=>o(l),l.onerror=u=>a(u)})}removeStyle(e){const i=`style:${e}`,n=document.querySelector(`[data-ipe="${i}"]`);n&&n.remove()}removeScript(e){const i=`script:${e}`,n=document.querySelector(`[data-ipe="${i}"]`);n&&n.remove()}removeAll(){document.querySelectorAll("[data-ipe]").forEach(e=>{e.remove()})}resolveImportPath(e){if(e.startsWith("http")||e.startsWith("//"))return e;const i=document.currentScript?.src;if(!i)return`https://unpkg.com/mediawiki-inpageedit@latest/dist/${e}`;const n=new URL(i);return n.pathname.endsWith(".js")||(n.pathname=n.pathname+"/"),new URL(e,n.toString()).toString()}}const Kn=Object.keys;function Dd(t){return typeof t=="boolean"}function jd(t){return t&&typeof t.nodeType=="number"}function Wn(t){return typeof t=="string"}function Na(t){return typeof t=="number"}function ti(t){return typeof t=="object"?t!==null:Xi(t)}function Xi(t){return typeof t=="function"}function Ud(t){return!!(t&&t.isComponent)}function Fd(t){return ti(t)&&typeof t.length=="number"&&typeof t.nodeType!="number"}function ms(t,e){if(t)for(const i of Kn(t))e(t[i],i)}function Bd(t){return ti(t)&&"current"in t}const gs={animationIterationCount:0,borderImageOutset:0,borderImageSlice:0,borderImageWidth:0,boxFlex:0,boxFlexGroup:0,boxOrdinalGroup:0,columnCount:0,columns:0,flex:0,flexGrow:0,flexPositive:0,flexShrink:0,flexNegative:0,flexOrder:0,gridArea:0,gridRow:0,gridRowEnd:0,gridRowSpan:0,gridRowStart:0,gridColumn:0,gridColumnEnd:0,gridColumnSpan:0,gridColumnStart:0,fontWeight:0,lineClamp:0,lineHeight:0,opacity:0,order:0,orphans:0,tabSize:0,widows:0,zIndex:0,zoom:0,fillOpacity:0,floodOpacity:0,stopOpacity:0,strokeDasharray:0,strokeDashoffset:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0};function qd(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)}const Hd=["Webkit","ms","Moz","O"];Kn(gs).forEach(t=>{Hd.forEach(e=>{gs[qd(e,t)]=0})});const zd=Symbol.for("jsx-dom:type");var Ma=(function(t){return t.ShadowRoot="ShadowRoot",t})(Ma||{});function Kd(t){return t!=null&&t[zd]===Ma.ShadowRoot}const Wd="http://www.w3.org/2000/svg",Vd="http://www.w3.org/1999/xlink",Gd="http://www.w3.org/XML/1998/namespace";function Da(t){return!Dd(t)&&t!=null}function ys(t){return Array.isArray(t)?t.map(ys).filter(Boolean).join(" "):ti(t)?Symbol.iterator in t?ys(Array.from(t)):Kn(t).filter(e=>t[e]).join(" "):Da(t)?""+t:""}const Yd={animate:0,circle:0,clipPath:0,defs:0,desc:0,ellipse:0,feBlend:0,feColorMatrix:0,feComponentTransfer:0,feComposite:0,feConvolveMatrix:0,feDiffuseLighting:0,feDisplacementMap:0,feDistantLight:0,feFlood:0,feFuncA:0,feFuncB:0,feFuncG:0,feFuncR:0,feGaussianBlur:0,feImage:0,feMerge:0,feMergeNode:0,feMorphology:0,feOffset:0,fePointLight:0,feSpecularLighting:0,feSpotLight:0,feTile:0,feTurbulence:0,filter:0,foreignObject:0,g:0,image:0,line:0,linearGradient:0,marker:0,mask:0,metadata:0,path:0,pattern:0,polygon:0,polyline:0,radialGradient:0,rect:0,stop:0,svg:0,switch:0,symbol:0,text:0,textPath:0,tspan:0,use:0,view:0},Qd=/^(a(ll|t|u)|base[FP]|c(al|lipPathU|on)|di|ed|ex|filter[RU]|g(lyphR|r)|ke|l(en|im)|ma(rker[HUW]|s)|n|pat|pr|point[^e]|re[^n]|s[puy]|st[^or]|ta|textL|vi|xC|y|z)/;function vi(t){const e=document.createDocumentFragment();return Vn(t.children,e),e}function Jd(t,e,i){e={...e,children:i};const n=new t(e),r=n.render();return"ref"in e&&bs(e.ref,n),r}function m(t,e){let{children:i,...n}=e;!n.namespaceURI&&Yd[t]===0&&(n={...n,namespaceURI:Wd});let r;if(Wn(t)){if(r=n.namespaceURI?document.createElementNS(n.namespaceURI,t):document.createElement(t),eh(n,r),Vn(i,r),r instanceof window.HTMLSelectElement&&n.value!=null)if(n.multiple===!0&&Array.isArray(n.value)){const s=n.value.map(o=>String(o));r.querySelectorAll("option").forEach(o=>o.selected=s.includes(o.value))}else r.value=n.value;bs(n.ref,r)}else if(Xi(t))ti(t.defaultProps)&&(n={...t.defaultProps,...n}),r=Ud(t)?Jd(t,n,i):t({...n,children:i});else throw new TypeError(`Invalid JSX element type: ${t}`);return r}function Zi(t,e){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return(Wn(e)||Array.isArray(e))&&(n.unshift(e),e={}),e=e||{},e.children!=null&&!n.length&&({children:n,...e}=e),m(t,{...e,children:n},e.key)}function bs(t,e){Bd(t)?t.current=e:Xi(t)&&t(e)}function Vn(t,e){if(Fd(t))Xd(t,e);else if(Wn(t)||Na(t))vs(document.createTextNode(t),e);else if(t===null)vs(document.createComment(""),e);else if(jd(t))vs(t,e);else if(Kd(t)){const i=e.attachShadow(t.attr);Vn(t.children,i),bs(t.ref,i)}}function Xd(t,e){for(const i of[...t])Vn(i,e);return e}function vs(t,e){e instanceof window.HTMLTemplateElement?e.content.appendChild(t):e.appendChild(t)}function Gn(t,e){return t.replace(/[A-Z]/g,i=>e+i.toLowerCase())}function ja(t,e){e==null||e===!1||(Array.isArray(e)?e.forEach(i=>ja(t,i)):Wn(e)?t.setAttribute("style",e):ti(e)&&ms(e,(i,n)=>{n.indexOf("-")===0?t.style.setProperty(n,i):Na(i)&&gs[n]!==0?t.style[n]=i+"px":t.style[n]=i}))}function Zd(t,e,i){switch(t){case"xlinkActuate":case"xlinkArcrole":case"xlinkHref":case"xlinkRole":case"xlinkShow":case"xlinkTitle":case"xlinkType":Ua(i,Vd,Gn(t,":"),e);return;case"xmlnsXlink":wi(i,Gn(t,":"),e);return;case"xmlBase":case"xmlLang":case"xmlSpace":Ua(i,Gd,Gn(t,":"),e);return}switch(t){case"htmlFor":wi(i,"for",e);return;case"dataset":ms(e,(n,r)=>{n!=null&&(i.dataset[r]=n)});return;case"innerHTML":case"innerText":case"textContent":Da(e)&&(i[t]=e);return;case"dangerouslySetInnerHTML":ti(e)&&(i.innerHTML=e.__html);return;case"value":if(e==null||i instanceof window.HTMLSelectElement)return;if(i instanceof window.HTMLTextAreaElement){i.value=e;return}break;case"spellCheck":i.spellcheck=e;return;case"class":case"className":Xi(e)?e(i):wi(i,"class",ys(e));return;case"ref":case"namespaceURI":return;case"style":ja(i,e);return;case"on":case"onCapture":ms(e,(n,r)=>{i.addEventListener(r,n,t==="onCapture")});return}if(Xi(e)){if(t[0]==="o"&&t[1]==="n"){let n=t.toLowerCase();const r=n.endsWith("capture");if(n==="ondoubleclick"?n="ondblclick":r&&n==="ondoubleclickcapture"&&(n="ondblclickcapture"),!r&&i[n]===null)i[n]=e;else if(r)i.addEventListener(n.substring(2,n.length-7),e,!0);else{let s;n in window?s=n.substring(2):s=n[2]+t.slice(3),i.addEventListener(s,e)}}}else ti(e)?i[t]=e:e===!0?wi(i,t,""):e!==!1&&e!=null&&(i instanceof SVGElement&&!Qd.test(t)?wi(i,Gn(t,"-"),e):wi(i,t,e))}function wi(t,e,i){t.setAttribute(e,i)}function Ua(t,e,i,n){t.setAttributeNS(e,i,n)}function eh(t,e){for(const i of Kn(t))Zd(i,t[i],e);return e}const Yn=Object.keys;function th(t){return typeof t=="boolean"}function ih(t){return t&&typeof t.nodeType=="number"}function ws(t){return typeof t=="string"}function Fa(t){return typeof t=="number"}function ii(t){return typeof t=="object"?t!==null:en(t)}function en(t){return typeof t=="function"}function nh(t){return!!(t&&t.isComponent)}function rh(t){return ii(t)&&typeof t.length=="number"&&typeof t.nodeType!="number"}function _s(t,e){if(t)for(const i of Yn(t))e(t[i],i)}function sh(t){return ii(t)&&"current"in t}const xs={animationIterationCount:0,borderImageOutset:0,borderImageSlice:0,borderImageWidth:0,boxFlex:0,boxFlexGroup:0,boxOrdinalGroup:0,columnCount:0,columns:0,flex:0,flexGrow:0,flexPositive:0,flexShrink:0,flexNegative:0,flexOrder:0,gridArea:0,gridRow:0,gridRowEnd:0,gridRowSpan:0,gridRowStart:0,gridColumn:0,gridColumnEnd:0,gridColumnSpan:0,gridColumnStart:0,fontWeight:0,lineClamp:0,lineHeight:0,opacity:0,order:0,orphans:0,tabSize:0,widows:0,zIndex:0,zoom:0,fillOpacity:0,floodOpacity:0,stopOpacity:0,strokeDasharray:0,strokeDashoffset:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0};function oh(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)}const ah=["Webkit","ms","Moz","O"];Yn(xs).forEach(t=>{ah.forEach(e=>{xs[oh(e,t)]=0})});const lh=Symbol.for("jsx-dom:type");var Ba=(function(t){return t.ShadowRoot="ShadowRoot",t})(Ba||{});function ch(t){return t!=null&&t[lh]===Ba.ShadowRoot}const uh="http://www.w3.org/2000/svg",fh="http://www.w3.org/1999/xlink",dh="http://www.w3.org/XML/1998/namespace";function qa(t){return!th(t)&&t!=null}function Ss(t){return Array.isArray(t)?t.map(Ss).filter(Boolean).join(" "):ii(t)?Symbol.iterator in t?Ss(Array.from(t)):Yn(t).filter(e=>t[e]).join(" "):qa(t)?""+t:""}const hh={animate:0,circle:0,clipPath:0,defs:0,desc:0,ellipse:0,feBlend:0,feColorMatrix:0,feComponentTransfer:0,feComposite:0,feConvolveMatrix:0,feDiffuseLighting:0,feDisplacementMap:0,feDistantLight:0,feFlood:0,feFuncA:0,feFuncB:0,feFuncG:0,feFuncR:0,feGaussianBlur:0,feImage:0,feMerge:0,feMergeNode:0,feMorphology:0,feOffset:0,fePointLight:0,feSpecularLighting:0,feSpotLight:0,feTile:0,feTurbulence:0,filter:0,foreignObject:0,g:0,image:0,line:0,linearGradient:0,marker:0,mask:0,metadata:0,path:0,pattern:0,polygon:0,polyline:0,radialGradient:0,rect:0,stop:0,svg:0,switch:0,symbol:0,text:0,textPath:0,tspan:0,use:0,view:0},ph=/^(a(ll|t|u)|base[FP]|c(al|lipPathU|on)|di|ed|ex|filter[RU]|g(lyphR|r)|ke|l(en|im)|ma(rker[HUW]|s)|n|pat|pr|point[^e]|re[^n]|s[puy]|st[^or]|ta|textL|vi|xC|y|z)/;function mh(t){const e=document.createDocumentFragment();return Qn(t.children,e),e}function gh(t,e,i){e={...e,children:i};const n=new t(e),r=n.render();return"ref"in e&&ks(e.ref,n),r}function ye(t,e){let{children:i,...n}=e;!n.namespaceURI&&hh[t]===0&&(n={...n,namespaceURI:uh});let r;if(ws(t)){if(r=n.namespaceURI?document.createElementNS(n.namespaceURI,t):document.createElement(t),vh(n,r),Qn(i,r),r instanceof window.HTMLSelectElement&&n.value!=null)if(n.multiple===!0&&Array.isArray(n.value)){const s=n.value.map(o=>String(o));r.querySelectorAll("option").forEach(o=>o.selected=s.includes(o.value))}else r.value=n.value;ks(n.ref,r)}else if(en(t))ii(t.defaultProps)&&(n={...t.defaultProps,...n}),r=nh(t)?gh(t,n,i):t({...n,children:i});else throw new TypeError(`Invalid JSX element type: ${t}`);return r}function ks(t,e){sh(t)?t.current=e:en(t)&&t(e)}function Qn(t,e){if(rh(t))yh(t,e);else if(ws(t)||Fa(t))Es(document.createTextNode(t),e);else if(t===null)Es(document.createComment(""),e);else if(ih(t))Es(t,e);else if(ch(t)){const i=e.attachShadow(t.attr);Qn(t.children,i),ks(t.ref,i)}}function yh(t,e){for(const i of[...t])Qn(i,e);return e}function Es(t,e){e instanceof window.HTMLTemplateElement?e.content.appendChild(t):e.appendChild(t)}function Jn(t,e){return t.replace(/[A-Z]/g,i=>e+i.toLowerCase())}function Ha(t,e){e==null||e===!1||(Array.isArray(e)?e.forEach(i=>Ha(t,i)):ws(e)?t.setAttribute("style",e):ii(e)&&_s(e,(i,n)=>{n.indexOf("-")===0?t.style.setProperty(n,i):Fa(i)&&xs[n]!==0?t.style[n]=i+"px":t.style[n]=i}))}function bh(t,e,i){switch(t){case"xlinkActuate":case"xlinkArcrole":case"xlinkHref":case"xlinkRole":case"xlinkShow":case"xlinkTitle":case"xlinkType":za(i,fh,Jn(t,":"),e);return;case"xmlnsXlink":_i(i,Jn(t,":"),e);return;case"xmlBase":case"xmlLang":case"xmlSpace":za(i,dh,Jn(t,":"),e);return}switch(t){case"htmlFor":_i(i,"for",e);return;case"dataset":_s(e,(n,r)=>{n!=null&&(i.dataset[r]=n)});return;case"innerHTML":case"innerText":case"textContent":qa(e)&&(i[t]=e);return;case"dangerouslySetInnerHTML":ii(e)&&(i.innerHTML=e.__html);return;case"value":if(e==null||i instanceof window.HTMLSelectElement)return;if(i instanceof window.HTMLTextAreaElement){i.value=e;return}break;case"spellCheck":i.spellcheck=e;return;case"class":case"className":en(e)?e(i):_i(i,"class",Ss(e));return;case"ref":case"namespaceURI":return;case"style":Ha(i,e);return;case"on":case"onCapture":_s(e,(n,r)=>{i.addEventListener(r,n,t==="onCapture")});return}if(en(e)){if(t[0]==="o"&&t[1]==="n"){let n=t.toLowerCase();const r=n.endsWith("capture");if(n==="ondoubleclick"?n="ondblclick":r&&n==="ondoubleclickcapture"&&(n="ondblclickcapture"),!r&&i[n]===null)i[n]=e;else if(r)i.addEventListener(n.substring(2,n.length-7),e,!0);else{let s;n in window?s=n.substring(2):s=n[2]+t.slice(3),i.addEventListener(s,e)}}}else ii(e)?i[t]=e:e===!0?_i(i,t,""):e!==!1&&e!=null&&(i instanceof SVGElement&&!ph.test(t)?_i(i,Jn(t,"-"),e):_i(i,t,e))}function _i(t,e,i){t.setAttribute(e,i)}function za(t,e,i,n){t.setAttributeNS(e,i,n)}function vh(t,e){for(const i of Yn(t))bh(i,t[i],e);return e}var $s=(t=>(t.Init="modal.init",t.BeforeShow="modal.beforeShow",t.Show="modal.show",t.BeforeClose="modal.beforeClose",t.Close="modal.close",t.Destroy="modal.destroy",t.ToastShow="toast.show",t.ToastClose="toast.close",t))($s||{});let wh=0;const Ka=t=>`${t}-${++wh}`;function tn(t){return t instanceof Node?t:document.createTextNode(String(t))}function Tt(t,e){if(!t)throw new Error(`${e??"Element"} not found`);return t}function Wa(t){const e=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(t.querySelectorAll(e)).filter(i=>!!(i.offsetWidth||i.offsetHeight||i.getClientRects().length))}function Ne(t,e={}){const i=document.createElement(t);if(e.className&&(i.className=e.className),e.html!=null&&(i.innerHTML=e.html),e.text!=null&&(i.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))i.setAttribute(n,r);return i}const _h=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform),Va=["ctrl","alt","shift","meta"];function xh(t){if(!t)return null;const e=String(t).trim().toLowerCase().split(/[+\-\s]+/g).filter(Boolean),i=[];let n=null;const r=o=>{i.includes(o)||i.push(o)};for(const o of e){let a=o;if(a==="control"||a==="ctrl"){r("ctrl");continue}if(a==="alt"||a==="option"){r("alt");continue}if(a==="shift"){r("shift");continue}if(a==="meta"||a==="cmd"||a==="command"||a==="super"){r("meta");continue}if(a==="mod"){r(_h?"meta":"ctrl");continue}a==="esc"&&(a="escape"),a==="return"&&(a="enter"),(a==="space"||a==="spacebar")&&(a="space"),n=a}const s=Va.filter(o=>i.includes(o));return!n||n===""?s.length?s.join("+"):null:s.length?`${s.join("+")}+${n}`:n}function Sh(t){const e=[];t.ctrlKey&&e.push("ctrl"),t.altKey&&e.push("alt"),t.shiftKey&&e.push("shift"),t.metaKey&&e.push("meta");let i=t.key;i===" "&&(i="space");const n=(i.length,i.toLowerCase()),r=Va.filter(s=>e.includes(s));return r.length?`${r.join("+")}+${n}`:n}class kh{constructor(){this.zBase=1e3,this.stack=[]}push(e){this.stack.push(e),this.syncZ()}remove(e){this.stack=this.stack.filter(i=>i!==e),this.syncZ()}top(){return this.stack[this.stack.length-1]}closeAll(e,i){const n=new Set((Array.isArray(i)?i:i?[i]:[]).map(String)),r=new Set((Array.isArray(e)?e:e?[e]:[]).map(String));[...this.stack].reverse().forEach(s=>{const o=s.modalId,a=r.size?r.has(s.pluginName):!0,l=n.has(o);a&&!l&&s.close()})}removeAll(){[...this.stack].forEach(e=>e.destroy()),this.stack=[]}syncZ(){this.stack.forEach((e,i)=>e.setZIndex(this.zBase+i*2))}lockBodyScroll(){document.body.classList.add("ipe-modal-no-scroll")}unlockBodyScroll(){document.body.classList.remove("ipe-modal-no-scroll")}}const ze=new kh,Cn=class Cn{constructor(e={}){this.backdropId=Ka("ipe-modal-backdrop"),this.modalId=Ka("ipe-modal"),this.numberId=this.modalId.split("-")[1],this._isDestroyed=!1,this.pluginName="normalModal",this.buttonElsLeft=[],this.buttonElsRight=[],this.keyMap=new Map,this.isOpen=!1,this.isToast=!1,this.isDragging=!1,this.dragStartX=0,this.dragStartY=0,this.modalStartX=0,this.modalStartY=0,this.Event=$s,this._hooks=[],this.startCloseTimer=i=>{this.stopCloseTimer(),this.closeTimer=window.setTimeout(()=>this.close(),i)},this.stopCloseTimer=()=>{this.closeTimer&&window.clearTimeout(this.closeTimer),this.closeTimer=void 0},this.onDragMove=i=>{if(!this.isDragging)return;i.preventDefault();const n=i.clientX-this.dragStartX,r=i.clientY-this.dragStartY,s=this.get$modal(),o=this.modalStartX+n,a=this.modalStartY+r;s.style.left=`${o}px`,s.style.top=`${a}px`},this.onDragEnd=()=>{if(!this.isDragging)return;this.isDragging=!1,document.removeEventListener("pointermove",this.onDragMove),document.removeEventListener("pointerup",this.onDragEnd);const i=this.get$modal(),n=this.get$window();i.classList.remove("is-dragging"),n.style.animation="none",requestAnimationFrame(()=>{this.applyAnimation(!0)})},this.options={...Cn.DEFAULT_OPTIONS,...e},this.options.backdrop===!1&&e.bodyScroll===void 0&&(this.options.bodyScroll=!0)}get isDestroyed(){return this._isDestroyed}static extends(e={}){return class extends this{constructor(i={}){super({...e,...i})}}}init(){if(this.$modal)return this;const e=this.options.backdrop!==!1;let i;e&&(i=Ne("div",{className:"ipe-modal-backdrop",attrs:{id:this.backdropId,"data-modal-id":this.modalId}}));const n=Ne("div",{className:"ipe-modal-modal",attrs:{id:this.modalId,role:"dialog","aria-modal":"true",tabindex:"-1"}});if(n.modal=this,!e){n.classList.add("no-backdrop");const p=window.pageYOffset||document.documentElement.scrollTop,f=window.pageXOffset||document.documentElement.scrollLeft,_=window.innerWidth;n.style.top=`${p+60}px`,this.once("modal.show",()=>{n.style.left=`${f+_/2-n.offsetWidth/2}px`})}const r=Ne("div",{className:`ipe-modal-modal__window size--${this.options.sizeClass||"auto"} plugin--${this.pluginName}`});r.modal=this;const s=Ne("div",{className:"ipe-modal-modal__header"}),o=`${this.modalId}-title`,a=Ne("h2",{className:"ipe-modal-modal__title",attrs:{id:o,role:"heading","aria-level":"2"}});n.setAttribute("aria-labelledby",o);const l=Ne("div",{className:"ipe-modal-modal__icons"});if(this.options.closeIcon){const p=Ne("button",{className:"ipe-modal-modal__close",attrs:{type:"button","aria-label":"Close"},html:"×"});p.addEventListener("click",()=>{let f=!0;typeof this.options.onClickClose=="function"?this.options.onClickClose(this)===!1&&(f=!1):this.options.onClickClose===!1&&(f=!1),f&&this.close()}),l.appendChild(p)}s.append(a,l),this.options.draggable&&e&&(this.options.draggable=!1),this.options.draggable&&(s.style.cursor="move",s.style.userSelect="none",s.addEventListener("pointerdown",this.onDragStart.bind(this)),n.classList.add("is-draggable"));const c=Ne("div",{className:"ipe-modal-modal__content"}),u=Ne("div",{className:"ipe-modal-modal__footer"}),d=Ne("div",{className:"ipe-modal-modal__buttons ipe-modal-modal__buttons--left"}),h=Ne("div",{className:"ipe-modal-modal__buttons ipe-modal-modal__buttons--right"});return u.append(d,h),r.append(s,c,u),n.appendChild(r),this.$backdrop=i,this.$modal=n,this.$window=r,this.$header=s,this.$title=a,this.$icons=l,this.$content=c,this.$footer=u,this.$buttonsLeft=d,this.$buttonsRight=h,this.options.title&&this.setTitle(this.options.title),this.options.content&&this.setContent(this.options.content),this.options.buttons?.length?this.setButtons(this.options.buttons):u.style.display="none",this.options.center&&this.$modal.classList.add("is-centered"),this.options.fitScreen&&this.$modal.classList.add("is-fullscreen"),this.options.iconButtons&&this.$header.classList.add("has-icon-buttons"),this.options.className&&this.$window.classList.add(...this.options.className.split(/[\s\.#+]+/g).filter(Boolean)),typeof this.options.fixedHeight=="number"?this.$window.style.height=`${Math.max(0,this.options.fixedHeight)}px`:this.options.fixedHeight===!0&&this.$window.classList.add("is-fixed-height"),i&&i.addEventListener("pointerdown",p=>{this.options.outSideClose&&p.target===i&&this.close()}),this.options.draggable&&r.addEventListener("pointerdown",p=>{p.target&&r.contains(p.target)&&this.bringToFront()}),this.onKeyDown=this.onKeyDown.bind(this),this.emit("modal.init"),this}show(){if(this.$modal||this.init(),!this.$modal)throw new Error("Failed to initialize modal");if(this.isOpen)return this;{const n=this.emit("modal.beforeShow",!0),r=this.options.beforeShow?this.options.beforeShow(this)!==!1:!0;if(!n||!r)return this}this.lastFocused=document.activeElement??null,this.$backdrop&&document.body.appendChild(this.$backdrop),document.body.appendChild(this.$modal),this.shouldLockBodyOnOpen()&&ze.lockBodyScroll(),requestAnimationFrame(()=>{this.$backdrop?.classList.add("is-open"),this.$modal.classList.add("is-open"),this.applyAnimation(!0),this.focusFirst()}),document.addEventListener("keydown",this.onKeyDown),ze.push(this),this.isOpen=!0,this.options.onShow?.(this),this.emit("modal.show");const e=typeof this.options.closeAfter=="number"?this.options.closeAfter:this.options.closeAfter?.time,i=typeof this.options.closeAfter=="number"?!0:this.options.closeAfter?.resetOnHover;return e&&(this.startCloseTimer(e),i&&(this.$window?.addEventListener("mouseenter",this.stopCloseTimer),this.$window?.addEventListener("mouseleave",()=>this.startCloseTimer(e)))),this}close(){if(!this.isOpen)return this;{const s=this.emit("modal.beforeClose",!0),o=this.options.beforeClose?this.options.beforeClose(this)!==!1:!0;if(!s||!o)return this}if(this.isToast){this.applyAnimation(!1),this.emit("modal.close"),this.emit("toast.close");const s=this.isAnimationDisabled()?0:this.options.animationSpeed??200;let o=!1;const a=()=>{o||(o=!0,this.destroy(),this.options.onClose?.(this))},l=(c,u)=>{const d=()=>{c.removeEventListener(u,d),a()};c.addEventListener(u,d,{once:!0})};return s>0&&this.$window?(l(this.$window,"transitionend"),l(this.$window,"animationend"),window.setTimeout(a,s+20)):window.setTimeout(a,s),this}this.applyAnimation(!1),this.$backdrop?.classList.remove("is-open"),this.$modal?.classList.remove("is-open"),this.emit("modal.close");const e=this.isAnimationDisabled()?0:this.options.animationSpeed??200;let i=!1;const n=()=>{i||(i=!0,this.destroy(),this.options.onClose?.(this))},r=(s,o)=>{const a=()=>{s.removeEventListener(o,a),n()};s.addEventListener(o,a,{once:!0})};return e>0&&this.$window?(r(this.$window,"transitionend"),r(this.$window,"animationend"),window.setTimeout(n,e+20)):window.setTimeout(n,e),this}destroy(){if(this._isDestroyed)return this;if(this.stopCloseTimer(),document.removeEventListener("keydown",this.onKeyDown),this.isDragging&&this.onDragEnd(),this.$window?.removeEventListener("mouseenter",this.stopCloseTimer),this.isToast){this.$window?.parentElement&&this.$window.parentElement.removeChild(this.$window);const e=ni.indexOf(this);e!==-1&&ni.splice(e,1)}else this.$backdrop?.parentElement&&this.$backdrop.parentElement.removeChild(this.$backdrop),this.$modal?.parentElement&&this.$modal.parentElement.removeChild(this.$modal),ze.remove(this),this.shouldUnlockBodyOnClose()&&ze.unlockBodyScroll();return this.isOpen=!1,this.lastFocused?.focus?.(),this.emit("modal.destroy"),this._isDestroyed=!0,this}get$backdrop(){return this.$backdrop}get$modal(){return Tt(this.$modal,"modal")}get$window(){return Tt(this.$window,"window")}get$header(){return Tt(this.$header,"header")}get$title(){return Tt(this.$title,"title")}get$content(){return Tt(this.$content,"content")}get$icons(){return Tt(this.$icons,"icons")}get$buttons(e){return e==="leftButtons"?Tt(this.$buttonsLeft,"leftButtons"):e==="rightButtons"?Tt(this.$buttonsRight,"rightButtons"):Tt(this.$footer,"buttons")}setTitle(e){const i=this.get$title();return i.innerHTML="",i.append(tn(e)),this}setContent(e,i="replace"){const n=this.get$content();return i==="replace"?(n.innerHTML="",n.append(tn(e))):i==="append"?n.append(tn(e)):n.prepend(tn(e)),this}setIcons(e){const i=this.get$icons();i.innerHTML="";for(const n of e){const r=Ne("button",{className:`ipe-modal-modal__icon ${n.className}`,attrs:{type:"button"}});r.addEventListener("click",n.method),i.appendChild(r)}return this}setButtons(e,i){const n=this.$buttonsLeft,r=this.$buttonsRight;[n,r].forEach(o=>o.innerHTML=""),this.buttonElsLeft=[],this.buttonElsRight=[],this.keyMap.clear();const s=i??this.$footer;if(s===this.$footer)e.forEach(o=>this.addButton(o)),e.length===0&&(this.$footer.style.display="none");else{s.innerHTML="";for(const o of e){const a=this.generateButton(o);s.appendChild(a)}}return this}generateButton(e){const i=e.type??"button",n=i==="link"?Ne("a"):Ne("button",{attrs:{type:"button"}});e.id&&(n.id=e.id),n.className=`ipe-modal-btn ${e.className??""}`.trim();const r=tn(e.label??"OK");if(n.append(r),i==="link"&&e.href&&(n.href=e.href),e.method&&n.addEventListener("click",s=>{if(n._ipe_tmpDisabled){s.preventDefault(),s.stopPropagation();return}e.method.call(n,s,this)}),typeof e.closeAfter=="number"&&e.closeAfter>=0&&n.addEventListener("click",()=>{window.setTimeout(()=>this.close(),e.closeAfter)}),typeof e.enableAfter=="number"&&e.enableAfter>0){i==="button"&&n.setAttribute("disabled","true"),n._ipe_tmpDisabled=!0,n.setAttribute("aria-disabled","true");const s=()=>{i==="button"&&n.removeAttribute("disabled"),delete n._ipe_tmpDisabled,n.removeAttribute("aria-disabled")};window.setTimeout(s,e.enableAfter)}if(e.keyPress){const s=String(e.keyPress).split(/[\,\|]+/g).map(o=>o.trim()).filter(Boolean);for(const o of s){const a=xh(o);a&&this.keyMap.set(a,n)}}return n}addButton(e,i){this.$footer&&(this.$footer.style.display="");const n=e.side??"right",r=n==="left"?this.$buttonsLeft:this.$buttonsRight,s=n==="left"?this.buttonElsLeft:this.buttonElsRight,o=this.generateButton(e),a=Math.max(0,Math.min(i??s.length,s.length));return a>=r.children.length?r.appendChild(o):r.insertBefore(o,r.children[a]),s.splice(a,0,o),this}removeButton(e){const i=this.buttonElsLeft,n=this.buttonElsRight,r=[...i,...n];let s=null;if(e==="*")return r.forEach(a=>{this.keyMap.delete(a.id),a.parentElement?.removeChild(a)}),this.$footer&&(this.$footer.style.display="none"),this;if(typeof e=="number"?s=r[e]??null:typeof e=="string"?s=r.find(a=>a.id===e)??null:e instanceof HTMLElement&&(s=r.find(a=>a===e)??null),!s)return this;for(const[a,l]of this.keyMap.entries())l===s&&this.keyMap.delete(a);let o=i.indexOf(s);return o!==-1?(i.splice(o,1),s.parentElement?.removeChild(s)):(o=n.indexOf(s),o!==-1&&(n.splice(o,1),s.parentElement?.removeChild(s))),i.length===0&&n.length===0&&this.$footer&&(this.$footer.style.display="none"),this}changePreviewState(){return this.get$modal().classList.toggle("is-fullscreen"),this}setModalHeight(e,i="height"){const n=this.get$window(),r=Math.max(0,window.innerHeight-e);return n.style[i]=`${r}px`,r}setOptions(e,i){return typeof e=="string"?this.options[e]=i:Object.assign(this.options,e),this}setPluginName(e){return this.$window&&(this.$window.className=this.$window.className.replace(`plugin--${this.pluginName}`,`plugin--${e}`)),this.pluginName=e,this}applyAnimation(e){const i=this.get$modal(),n=this.get$window(),r=this.$backdrop,s=this.options.modalAnimation??this.options.animation,o=typeof s=="string"?s:s&&(e?s.show:s.hide),a=this.options.backdropAnimation??this.options.animation,l=typeof a=="string"?a:a&&(e?a.show:a.hide);!o||o===!1?(i.style.transition="none",n.style.animation="none",n.style.removeProperty("--ipe-modal-anim")):(i.style.removeProperty("transition"),n.style.setProperty("--ipe-modal-anim",o)),r&&(!l||l===!1?r.style.transition="none":r.style.removeProperty("transition"))}on(e,i){return this._hooks.push({type:e,listener:i}),()=>this.off(e,i)}off(e,i){return this._hooks=this._hooks.filter(n=>n.type!==e&&(i?n.listener!==i:!0)),this}once(e,i){const n=this.on(e,r=>(n(),i(r)));return n}emit(e,i){const n=this._hooks.filter(a=>a.type===e);let r=!0;for(const a of n){const l=new CustomEvent(e,{detail:this,cancelable:i}),c=a.listener(l);if(l.defaultPrevented&&(r=!1),c===!1&&(r=!1),!r)break}const s=this.$modal??document.body,o=new CustomEvent(e,{detail:this,cancelable:i});return(!s.dispatchEvent(o)||o.defaultPrevented)&&(r=!1),r}focusFirst(){const e=this.get$modal(),i=Wa(e);i.length?i[0].focus():e.focus({preventScroll:!0})}onKeyDown(e){if(ze.top()!==this)return;if(e.key==="Escape"){e.preventDefault(),this.close();return}const i=this.get$modal();if(!i.contains(document.activeElement))return;if(e.key==="Tab"){const a=Wa(i);if(!a.length)return;const l=a[0],c=a[a.length-1],u=document.activeElement;e.shiftKey&&u===l?(e.preventDefault(),c.focus()):!e.shiftKey&&u===c&&(e.preventDefault(),l.focus())}const n=e.ctrlKey||e.altKey||e.metaKey,r=e.target;if(!n&&(r&&["INPUT","TEXTAREA"].includes(r.tagName)||r.contentEditable==="true"))return;const s=Sh(e),o=this.keyMap.get(s);if(o){e.preventDefault(),o.click();return}}setZIndex(e){this.$backdrop&&(this.$backdrop.style.zIndex=String(e)),this.$modal&&(this.$modal.style.zIndex=String(e+1))}bringToFront(){return ze.remove(this),ze.push(this),this}isAnimationDisabled(){const e=this.options.modalAnimation??this.options.animation;return e===!1||e==null}shouldLockBodyOnOpen(){return this.options.backdrop===!1||this.options.bodyScroll!==!1?!1:!ze.stack.some(e=>e!==this&&e.options.backdrop!==!1&&e.options.bodyScroll===!1)}shouldUnlockBodyOnClose(){return this.options.backdrop===!1||this.options.bodyScroll!==!1?!1:!ze.stack.some(e=>e!==this&&e.options.backdrop!==!1&&e.options.bodyScroll===!1)}onDragStart(e){if(this.options.backdrop!==!1||!this.options.draggable)return;e.preventDefault(),this.isDragging=!0,this.bringToFront(),this.dragStartX=e.clientX,this.dragStartY=e.clientY;const i=this.get$modal(),n=i.getBoundingClientRect();this.modalStartX=n.left+window.pageXOffset,this.modalStartY=n.top+window.pageYOffset,i.style.transform="none",i.style.left=`${this.modalStartX}px`,i.style.top=`${this.modalStartY}px`,document.addEventListener("pointermove",this.onDragMove),document.addEventListener("pointerup",this.onDragEnd),i.classList.add("is-dragging")}showToast(e){this.$window||this.init();const i=Eh(e.position??"top right"),n=this.get$window();this.isToast=!0,n.style.pointerEvents="auto",this.applyAnimation(!0),i.appendChild(n);const r=(typeof this.options.closeAfter=="number"?this.options.closeAfter:this.options.closeAfter?.time)??3e3,s=(typeof this.options.closeAfter=="number"?!0:this.options.closeAfter?.resetOnHover)??!0;return r>0&&(this.startCloseTimer(r),s&&(n.addEventListener("mouseenter",this.stopCloseTimer),n.addEventListener("mouseleave",()=>this.startCloseTimer(r)))),this.isOpen=!0,this.options.onShow?.(this),ni.push(this),this.emit("toast.show"),this.emit("modal.show"),this}static show(e,i){return new this(e).init().show()}static createObject(e,i){return new this(e)}static close(e){if(!e){const s=ze.top();return s?.close(),s}const i=typeof e=="string"?e:e.id,n=ze.stack.find(s=>s.modalId===i);if(n)return n.close(),n;const r=ni.find(s=>s.modalId===i);return r?.close(),r}static closeAll(e,i){const n=new Set((Array.isArray(i)?i:i?[i]:[]).map(String)),r=new Set((Array.isArray(e)?e:e?[e]:[]).map(String));return ze.closeAll(e,i),[...ni].forEach(s=>{const o=s.modalId,a=r.size?r.has(s.pluginName):!0,l=n.has(o);a&&!l&&s.close()}),ze.top()??new Cn}static removeAll(){ze.removeAll(),[...ni].forEach(e=>e.destroy())}static dialog(e,i){const n=new this({sizeClass:"dialog",buttons:[{label:"OK",className:"is-primary is-ghost",method:(r,s)=>{i?.(r,s),r.defaultPrevented||n.close()},keyPress:"Enter"}],...e});return n.init().show()}static confirm(e,i){e.title??(e.title="Confirm"),e.content??(e.content="Are you sure you want to perform this action?");const n=e.okBtn??{label:"OK",className:"is-primary is-ghost"},r=e.cancelBtn??{label:"Cancel",className:"is-danger is-ghost"};return new this({sizeClass:"dialog",...e,buttons:[{label:r.label,className:r.className,keyPress:"n",method:(s,o)=>{i?.(!1,o,s),o.close()}},{label:n.label,className:n.className,keyPress:"y",method:(s,o)=>{i?.(!0,o,s),s.defaultPrevented||o.close()}}]}).init().show()}static getDefaultNotifyIcon(e){switch(e){case"success":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-circle-check",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M17 3.34a10 10 0 1 1 -14.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 14.995 -8.336zm-1.293 5.953a1 1 0 0 0 -1.32 -.083l-.094 .083l-3.293 3.292l-1.293 -1.292l-.094 -.083a1 1 0 0 0 -1.403 1.403l.083 .094l2 2l.094 .083a1 1 0 0 0 1.226 0l.094 -.083l4 -4l.083 -.094a1 1 0 0 0 -.083 -1.32z"})]});case"error":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-alert-triangle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 1.67c.955 0 1.845 .467 2.39 1.247l.105 .16l8.114 13.548a2.914 2.914 0 0 1 -2.307 4.363l-.195 .008h-16.225a2.914 2.914 0 0 1 -2.582 -4.2l.099 -.185l8.11 -13.538a2.914 2.914 0 0 1 2.491 -1.403zm.01 13.33l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007zm-.01 -7a1 1 0 0 0 -.993 .883l-.007 .117v4l.007 .117a1 1 0 0 0 1.986 0l.007 -.117v-4l-.007 -.117a1 1 0 0 0 -.993 -.883z"})]});case"warning":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-alert-circle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 2c5.523 0 10 4.477 10 10a10 10 0 0 1 -19.995 .324l-.005 -.324l.004 -.28c.148 -5.393 4.566 -9.72 9.996 -9.72zm.01 13l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007zm-.01 -8a1 1 0 0 0 -.993 .883l-.007 .117v4l.007 .117a1 1 0 0 0 1.986 0l.007 -.117v-4l-.007 -.117a1 1 0 0 0 -.993 -.883z"})]});case"info":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-info-circle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 2c5.523 0 10 4.477 10 10a10 10 0 0 1 -19.995 .324l-.005 -.324l.004 -.28c.148 -5.393 4.566 -9.72 9.996 -9.72zm0 9h-1l-.117 .007a1 1 0 0 0 0 1.986l.117 .007v3l.007 .117a1 1 0 0 0 .876 .876l.117 .007h1l.117 -.007a1 1 0 0 0 .876 -.876l.007 -.117l-.007 -.117a1 1 0 0 0 -.764 -.857l-.112 -.02l-.117 -.006v-3l-.007 -.117a1 1 0 0 0 -.876 -.876l-.117 -.007zm.01 -3l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007z"})]});case"dialog":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"icon icon-tabler icons-tabler-outline icon-tabler-message-dots",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 11v.01"}),ye("path",{d:"M8 11v.01"}),ye("path",{d:"M16 11v.01"}),ye("path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3z"})]});case"confirm":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-copy-check",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M18.333 6a3.667 3.667 0 0 1 3.667 3.667v8.666a3.667 3.667 0 0 1 -3.667 3.667h-8.666a3.667 3.667 0 0 1 -3.667 -3.667v-8.666a3.667 3.667 0 0 1 3.667 -3.667zm-3.333 -4c1.094 0 1.828 .533 2.374 1.514a1 1 0 1 1 -1.748 .972c-.221 -.398 -.342 -.486 -.626 -.486h-10c-.548 0 -1 .452 -1 1v9.998c0 .32 .154 .618 .407 .805l.1 .065a1 1 0 1 1 -.99 1.738a3 3 0 0 1 -1.517 -2.606v-10c0 -1.652 1.348 -3 3 -3zm1.293 9.293l-3.293 3.292l-1.293 -1.292a1 1 0 0 0 -1.414 1.414l2 2a1 1 0 0 0 1.414 0l4 -4a1 1 0 0 0 -1.414 -1.414"})]});default:return null}}static notify(e,i,n){var a,l,c,u;if(i?.overrideOther&&[...ni].forEach(d=>d.close()),typeof i.title>"u"){const d=e||"Notification";i.title=d[0].toUpperCase()+d.slice(1).toLowerCase()}const r=i.icon??this.getDefaultNotifyIcon(e);r&&(r instanceof Element&&r.classList.add("ipe-modal-notify-icon"),i.title=ye(mh,{children:[r,i.title]})),e==="confirm"&&(typeof i.closeAfter>"u"&&(i.closeAfter=0),i.okBtn||(i.okBtn={label:"OK"})),i.okBtn&&(typeof i.okBtn!="object"&&(i.okBtn={label:"OK"}),(a=i.okBtn).label??(a.label="OK"),(l=i.okBtn).className??(l.className="is-primary is-text ok-btn"),i.okBtn.method=(d,h)=>{n?.(!0,h,d),h.close()}),i.cancelBtn&&(typeof i.cancelBtn!="object"&&(i.cancelBtn={label:"Cancel"}),(c=i.cancelBtn).label??(c.label="Cancel"),(u=i.cancelBtn).className??(u.className="is-danger is-text cancel-btn"),i.cancelBtn.method=(d,h)=>{n?.(!1,h,d),h.close()}),i.buttons=[i.cancelBtn,i.okBtn,...i.buttons??[]].filter(Boolean);const s=`is-notify type-${e||"default"} ${i.className??""}`,o=new this({...i,className:s,sizeClass:"auto",center:!1,fitScreen:!1,closeIcon:!0,outSideClose:!1,bodyScroll:!0,buttons:i.buttons??[]});return o.setPluginName("toast"),o.showToast({position:i.position??"top right"})}};Cn.DEFAULT_OPTIONS={className:"",sizeClass:"auto",center:!0,fitScreen:!1,closeIcon:!0,bodyScroll:!1,outSideClose:!0,backdrop:!0,animation:{show:"ipe-modal-fade-in",hide:"ipe-modal-fade-out"},animationSpeed:200};let Ps=Cn;const ni=[];function Eh(t="top right"){const e="ipe-modal-toast-container",i=`${e}-${t.replace(/[\s-\.|\/]+/g,"-")}`;let n=document.getElementById(i);return n||(n=Ne("div",{className:`${e} ${t}`,attrs:{id:i,"data-position":t}}),document.body.appendChild(n)),n}const $h={ipe_progress:"_ipe_progress_so6hn_1"},ri=t=>{const e=t.indeterminate??!0,i=m("div",{class:`${$h.ipe_progress}`,"data-indeterminate":`${e}`,style:{width:"100%","--progress":t.progress?`${t.progress}%`:"0%"},...t});return i.setProgress=n=>{typeof n=="number"?(i.dataset.indeterminate="false",i.style.setProperty("--progress",`${n}%`)):(i.dataset.indeterminate="true",i.style.setProperty("--progress","0%"))},i};class Pe extends Ps{constructor(e={}){e.className||(e.className=""),e.className+=" theme-ipe",e.modalAnimation||(e.modalAnimation={show:"ipe-modal-fade-in",hide:"ipe-modal-fade-out"}),super(e)}setLoadingState(e){if(this.get$window().classList.toggle("loading",e),e){const i=this.get$window().querySelectorAll("input:not([disabled]),button:not([disabled])");this._tmpDisabledActiveInputs=i,i.forEach(n=>{n.disabled=!0}),this.get$content().append(m("div",{id:"ipe-modalLoadingWrapper",style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"rgba(255, 255, 255, 0.5)",zIndex:2e3},children:m(ri,{style:{width:"80%",maxWidth:"800px"}})}))}else{this.get$window().querySelector("#ipe-modalLoadingWrapper")?.remove();const i=this._tmpDisabledActiveInputs;i&&i.forEach(n=>{n.disabled=!1})}}}class Ph{constructor(e){this.ctx=e,this.IPEModal=Pe,this.IPEModalEvent=$s,this.show=Pe.show.bind(Pe),this.createObject=Pe.createObject.bind(Pe),this.close=Pe.close.bind(Pe),this.closeAll=Pe.closeAll.bind(Pe),this.removeAll=Pe.removeAll.bind(Pe),this.dialog=Pe.dialog.bind(Pe),this.confirm=Pe.confirm.bind(Pe),this.notify=Pe.notify.bind(Pe),e.set("modal",this),e.on("dispose",()=>{Pe.closeAll()})}}const Ga=t=>{if(!t)return new URLSearchParams;if(t instanceof URLSearchParams)return t;if(typeof t!="object"||t?.constructor!==Object)throw new TypeError("only plain object is supported");const e=new URLSearchParams;for(const[i,n]of Object.entries(t))if(n!=null){if(Array.isArray(n)){for(const r of n)e.append(i,r?.toString());continue}if(typeof n=="object"&&n!==null&&n.constructor===Object){for(const[r,s]of Object.entries(n))s!=null&&e.set(`${i}[${r}]`,s?.toString());continue}e.set(i,n?.toString())}return e},Ya=(t,e,i)=>{const n=typeof t=="string"?new URL(t,window?.location?.origin):new URL(t),r=new URLSearchParams(n.search),s=Ga(e);for(const[o,a]of s.entries())r.set(o,a);return n.search=r.toString(),n.hash="",n};var Ch=Object.create,Cs=Object.defineProperty,Rh=Object.getOwnPropertyDescriptor,Qa=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ja=t=>{throw TypeError(t)},Ah=(t,e,i)=>e in t?Cs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ih=(t,e)=>Cs(t,"name",{value:e,configurable:!0}),Oh=t=>[,,,Ch(t?.[Qa("metadata")]??null)],Th=["class","method","getter","setter","accessor","field","value","get","set"],Xa=t=>t!==void 0&&typeof t!="function"?Ja("Function expected"):t,Lh=(t,e,i,n,r)=>({kind:Th[t],name:e,metadata:n,addInitializer:s=>i._?Ja("Already initialized"):r.push(Xa(s||null))}),Nh=(t,e)=>Ah(e,Qa("metadata"),t[3]),Mh=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},Dh=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Rh(r,i));Ih(r,i);for(var f=n.length-1;f>=0;f--)l=Lh(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,Xa(o)&&(r=o);return Nh(t,r),p&&Cs(r,i,p),u?c^4?s:p:r},Za,Rs,el;Za=[$e(["api","storage"])];class Xn extends(el=Ot){constructor(e){super(e,"wiki",!1),this.ctx=e,this._data={},this.CACHE_VERSION=3,this.CACHE_TTL={siteinfo:1e3*60*60*24*3,userinfo:1e3*60*30},this.QUERY_DATA={siteinfo:{meta:"siteinfo",siprop:"general|specialpagealiases|namespacealiases|namespaces|magicwords"},userinfo:{meta:"userinfo",uiprop:"groups|rights|blockinfo|options"}},this.CACHE_DB=void 0,this.mwConfig={get:((i,n)=>window?.mw?.config?.get?.(i,n)??n),has:(i=>window?.mw?.config?.exists?.(i)??!1),get values(){return window?.mw?.config?.values||{}}},this.CACHE_DB=e.storage.createDatabase("wiki-metadata",1/0,this.CACHE_VERSION)}get logger(){return this.ctx.logger("WIKI_METADATA")}get api(){return this.ctx.api}async start(){await Promise.all(Object.keys(this.QUERY_DATA).map(e=>this.initData(e))),this.ctx.set("getUrl",this.getUrl.bind(this)),this.ctx.set("getSciprtUrl",this.getSciprtUrl.bind(this)),this.ctx.set("getMainpageUrl",this.getMainpageUrl.bind(this)),this.ctx.inject(["preferences"],e=>{e.preferences.registerCustomConfig("WikiMetadataService",L.object({WikiMetadataService:L.const(m("div",{children:[m("h3",{children:"Wiki Informations"}),m("ul",{children:[m("li",{children:[m("strong",{children:"Site:"})," ",this.general.sitename," (",this.landingPageUrl,")"]}),m("li",{children:[m("strong",{children:"User"}),": ",this.userInfo.name," (ID: ",this.userInfo.id,")"]}),m("li",{children:[m("strong",{children:"Groups"}),": ",this.userGroups.join(", ")||"None"]})]}),m("div",{children:[m("p",{style:{fontStyle:"italic"},children:"If the information shown above is incorrect (for example, the user is not you), click the button below."}),m("button",{className:"btn danger",onClick:i=>{i.preventDefault(),Promise.all(Object.keys(this.QUERY_DATA).map(n=>this.invalidateCache(n))).then(()=>{window.location.reload()})},children:"🧹 Clear caches & Reload"})]})]})).role("raw-html")}).description("WikiMetadataService"),"about")}),this.logger.info("All initialized",this._data)}async initData(e,i=!1){const n=i?null:await this.fetchFromCache(e);if(n)return this._data[e]=n,this.logger.debug("Using cached",e,n),n;{const r=await this.fetchFromApi(e);return this.saveToCache(e,r),this._data[e]=r,this.logger.debug("Fetched from API",e,r),r}}getCacheKey(e){return`${e}:${new URL(this.ctx.api.config.baseURL).pathname.replace(/^\//,"")}`}async fetchFromApi(e){return this.api.get({action:"query",...this.QUERY_DATA[e]}).then(({data:i})=>{if(typeof i?.query!="object"||i.query===null)throw new Error("Invalid query data",{cause:i});return e==="siteinfo"?i.query:i.query?.[e]||i.query}).catch(i=>(this.logger.error("Failed to fetch",i),Promise.reject(i)))}async fetchFromCache(e){const i=this.getCacheKey(e);return await this.CACHE_DB.get(i,this.CACHE_TTL[e])}async saveToCache(e,i){const n=this.getCacheKey(e);return this.CACHE_DB.set(n,i)}async invalidateCache(e){const i=this.getCacheKey(e);return this.CACHE_DB.delete(i)}get _raw(){return this._data}get siteInfo(){return this._data.siteinfo}get general(){return this.siteInfo.general}get specialPageAliases(){return this.siteInfo.specialpagealiases}get namespaceAliases(){return this.siteInfo.namespacealiases}get namespaces(){return this.siteInfo.namespaces}get namespaceMap(){const e=Object.values(this.namespaces).map(i=>({id:i.id,canonical:i.canonical,aliases:this.namespaceAliases.filter(n=>n.id===i.id).map(n=>n.alias)})).sort((i,n)=>i.id-n.id);return Reflect.defineProperty(this,"namespaceMap",{get:()=>e}),e}get magicWords(){return this.siteInfo.magicwords}get userInfo(){return this._data.userinfo}get userOptions(){return this.userInfo.options}get isUserBlocked(){return this.userInfo.blockedbyid&&this.userInfo.blockexpiry&&new Date(this.userInfo.blockexpiry).getTime()>Date.now()}get userGroups(){return this.userInfo.groups}get userRights(){return this.userInfo.rights}get baseUrl(){const e=this.general.server;return e.startsWith("//")?`${window?.location?.protocol||"https:"}//${e.slice(2)}`:e}get landingPageUrl(){return this.general.base}get mainPageName(){return this.general.mainpage}get mainPageUrl(){return this.getUrl(this.mainPageName)}get articlePath(){return this.general.articlepath}get scriptPath(){return this.general.scriptpath}get articleBaseUrl(){return`${this.baseUrl}${this.articlePath}`}get scriptBaseUrl(){return`${this.baseUrl}${this.scriptPath}`}getSciprtUrl(e="index"){return`${this.scriptBaseUrl}/${e.replace(/\.php$/,"")}.php`}getMainpageUrl(e){return Ya(this.siteInfo.general.base,e).toString()}getUrl(e,i){const n=Ga(i);let r;return typeof e=="string"&&e!==""?r=new URL(`${this.articleBaseUrl.replace("$1",e)}`):typeof e=="number"?(n.set("curid",e.toString()),r=new URL(this.getSciprtUrl("index"))):r=new URL(this.getSciprtUrl("index")),r.search=n.toString(),r.toString()}hasRight(e){return this.userRights.includes(e)}hasAnyRight(...e){return e.some(i=>this.hasRight(i))}hasEveryRights(...e){return e.every(i=>this.hasRight(i))}inGroup(e){return this.userGroups.includes(e)}inAnyGroup(...e){return this.userGroups.some(i=>e.includes(i))}getBlockInfo(){return this.isUserBlocked?{blockid:this.userInfo.blockid,blockedby:this.userInfo.blockedbyid,blockedbyid:this.userInfo.blockedbyid,blockreason:this.userInfo.blockreason,blockedtimestamp:this.userInfo.blockedtimestamp,blockexpiry:this.userInfo.blockexpiry}:null}}Rs=Oh(el),Xn=Dh(Rs,0,"WikiMetadataService",Za,Xn),Mh(Rs,1,Xn);class jh{constructor(){this.values={}}get length(){return Object.keys(this.values).length}clear(){this.values={}}getItem(e){return this.values[e]??null}setItem(e,i){this.values[e]=typeof i=="string"?i:String(i)}removeItem(e){delete this.values[e]}key(e){return Object.keys(this.values)[e]??null}}const Uh=()=>new Proxy(new jh,{set(t,e,i){return typeof e=="string"&&t.setItem(e,i),!0},get(t,e){return typeof e=="string"&&!(e in t)?t.getItem(e):Reflect.get(t,e)}}),Fh=(()=>{const t=Symbol.for("IPE.GlobalMemoryStorage");return t in globalThis||(globalThis[t]=Uh()),globalThis[t]})();class Bh{constructor(e,i,n=1/0,r,s="localStorage"){this.dbName=e,this.storeName=i,this.ttl=n,this.version=r,this.engine=s,typeof n!="number"&&(this.ttl=Number(n)),(isNaN(this.ttl)||this.ttl<=0)&&(this.ttl=1/0),this.engine==="localStorage"&&"localStorage"in window?this.db=window.localStorage:this.engine==="sessionStorage"&&"sessionStorage"in window?this.db=window.sessionStorage:this.db=Fh}makeKey(e){return`${this.dbName?this.dbName+":":""}${this.storeName?this.storeName+"/":""}${e}`}load(e){const i=this.getRaw(e);if(i===null)return null;let n;try{n=JSON.parse(i)}catch{return this.deleteSync(e),null}const r=n;return typeof r.time!="number"||!("value"in r)?(this.deleteSync(e),null):typeof this.version=="number"&&r.version!==this.version?(this.deleteSync(e),null):r}getRaw(e){const i=this.makeKey(e);return this.db.getItem(i)}setRaw(e,i){const n=this.makeKey(e);try{this.db.setItem(n,i)}catch{}}deleteSync(e){const i=this.makeKey(e);this.db.removeItem(i)}isExpired(e,i=this.ttl){return e?Date.now()-e.time>i:!1}async get(e,i=this.ttl,n){const r=this.load(e),s=this.isExpired(r,i);if(!r||s){if(typeof n=="function"){const o=await n();return await this.set(e,o),o}return null}return r.value}async set(e,i){const n=Date.now();if(typeof e=="string"){const o=e,a=i;if(a===null||typeof a>"u"){await this.delete(o);return}const l={time:n,value:a,version:this.version};return this.setRaw(o,JSON.stringify(l)),l}const r=e,s={};for(const[o,a]of Object.entries(r)){if(a===null||typeof a>"u"){this.deleteSync(o);continue}const l={time:n,value:a,version:this.version};this.setRaw(o,JSON.stringify(l)),s[o]=l}return s}async has(e,i=this.ttl){const n=this.load(e);return n!==null&&!this.isExpired(n,i)}async delete(e){this.deleteSync(e)}async updatedAt(e){const i=this.load(e);return i?i.time:0}async clear(){const e=this.makeKey(""),i=[];for(let n=0;n<this.db.length;n++){const r=this.db.key(n);r&&r.startsWith(e)&&i.push(r)}for(const n of i)this.db.removeItem(n);return this}async*keys(){const e=this.makeKey("");for(let i=0;i<this.db.length;i++){const n=this.db.key(i);n&&n.startsWith(e)&&(yield n.slice(e.length))}}async*values(){for await(const e of this.keys()){const i=this.load(e);if(i){if(this.isExpired(i)){this.deleteSync(e);continue}yield i}}}async*entries(){for await(const e of this.keys()){const i=this.load(e);if(i){if(this.isExpired(i)){this.deleteSync(e);continue}yield[e,i]}}}}var we;(t=>{t.cache=new Map,t.defaults=Object.freeze({iterBatch:100,retry:{attempts:3,baseDelayMs:16}}),t.sleep=c=>new Promise(u=>setTimeout(u,c));function e(c){const u=c?.name??"";return u==="AbortError"||u==="InvalidStateError"||u==="TransactionInactiveError"||u==="UnknownError"}t.shouldReconnect=e;async function i(c,u,d){const h=Math.max(1,c.attempts);for(let p=0;p<h;p++)try{return await u(p)}catch(f){if(p===h-1)throw f;await d?.(f,p);const _=c.baseDelayMs*Math.pow(2,p)+Math.floor(Math.random()*10);await(0,t.sleep)(_)}throw new Error("withRetry exhausted unexpectedly")}t.withRetry=i;function n(c,u,d){return new Promise((h,p)=>{const f=indexedDB.open(c,u);f.onupgradeneeded=()=>{try{const _=f.result,P=f.transaction;d?.(_,P)}catch(_){p(_)}},f.onerror=()=>p(f.error),f.onblocked=()=>{},f.onsuccess=()=>{const _=f.result;_.onversionchange=()=>{try{_.close()}finally{t.cache.delete(c)}},h(_)}})}async function r(c,u,d){let h=!c.objectStoreNames.contains(u),p=[];if(!h&&d?.indexes?.length){const P=c.transaction(u,"readonly"),C=P.objectStore(u),R=new Set(Array.from(C.indexNames));p=(d.indexes||[]).filter(y=>!R.has(y.name)),await new Promise((y,g)=>{P.oncomplete=()=>y(),P.onabort=()=>g(P.error),P.onerror=()=>g(P.error)})}if(!h&&p.length===0)return c;const f=c.version+1;c.close();const _=await n(c.name,f,(P,C)=>{let R;P.objectStoreNames.contains(u)?R=C.objectStore(u):R=P.createObjectStore(u,{keyPath:d?.keyPath??void 0,autoIncrement:!!d?.autoIncrement});for(const y of p)R.indexNames.contains(y.name)||R.createIndex(y.name,y.keyPath,y.options)});return _.onversionchange=()=>{try{_.close()}finally{t.cache.delete(_.name)}},_}async function s(c,u,d){let h=t.cache.get(c);return h?(h=h.then(p=>r(p,u,d)),t.cache.set(c,h)):(h=(async()=>{const p=await n(c);return r(p,u,d)})(),t.cache.set(c,h)),h}t.getDB=s;async function o(c){const u=t.cache.get(c);if(t.cache.delete(c),u)try{(await u).close()}catch{}}t.closeConnection=o;function a(c){return new Promise((u,d)=>{c.onsuccess=()=>u(c.result),c.onerror=()=>d(c.error)})}t.asyncRequest=a;function l(c){return new Promise((u,d)=>{c.oncomplete=()=>u(),c.onabort=()=>d(c.error??new DOMException("Aborted","AbortError")),c.onerror=()=>d(c.error??new DOMException("TransactionError","UnknownError"))})}t.waitTx=l})(we||(we={}));let qh=class{constructor(e,i,n={}){this.dbName=e,this.storeName=i,this.options=n}get _iterBatch(){return this.options.iterBatch??we.defaults.iterBatch}get _retryCfg(){const e=this.options.retry??we.defaults.retry;return{attempts:e.attempts??3,baseDelayMs:e.baseDelayMs??16}}async _withStore(e,i){const n=this._retryCfg;return we.withRetry(n,async()=>{const r=await we.getDB(this.dbName,this.storeName,this.options.ensure);try{const s=r.transaction(this.storeName,e),o=s.objectStore(this.storeName),a=await i(o);return await we.waitTx(s),a}catch(s){throw s}},async r=>{we.shouldReconnect(r)&&await we.closeConnection(this.dbName)})}async get(e){return this._withStore("readonly",async i=>{const n=await we.asyncRequest(i.get(e));return n===void 0?void 0:n})}async set(e,i){return await this._withStore("readwrite",async n=>{const r=this.options.ensure?.keyPath!=null?n.put(i):n.put(i,e);await we.asyncRequest(r)}),this}async delete(e){return this._withStore("readwrite",async i=>{const n=await we.asyncRequest(i.get(e))!==void 0;return await we.asyncRequest(i.delete(e)),n})}async clear(){await this._withStore("readwrite",async e=>{await we.asyncRequest(e.clear())})}async has(e){return await this.get(e)!==void 0}async count(){return this._withStore("readonly",async e=>await we.asyncRequest(e.count())??0)}async*_iterateEntries(){let e=null,i=!1;const n=Math.max(1,this._iterBatch);for(;!i;){const r=await this._withStore("readonly",async s=>{const o=[],a=e===null?void 0:IDBKeyRange.lowerBound(e,!0);return await new Promise((l,c)=>{const u=s.openCursor(a);u.onerror=()=>c(u.error),u.onsuccess=()=>{const d=u.result;if(!d){i=!0,l();return}o.push([d.key,d.value]),e=d.key,o.length>=n?l():d.continue()}}),o});for(const s of r)yield s;if(r.length===0)break}}entries(){return this._iterateEntries()}async*keys(){for await(const[e]of this.entries())yield e}async*values(){for await(const[,e]of this.entries())yield e}[Symbol.asyncIterator](){return this.entries()[Symbol.asyncIterator]()}async forEach(e){for await(const[i,n]of this.entries())await e(n,i,this)}async getMany(e){const i=new Map;for await(const n of e)i.set(n,void 0);return await this._withStore("readonly",async n=>{await Promise.all(i.keys().map(async r=>{const s=await we.asyncRequest(n.get(r));i.set(r,s===void 0?void 0:s)}))}),i}async setMany(e){const i=this.options.ensure?.keyPath!=null;return await this._withStore("readwrite",async n=>{for await(const[r,s]of e){const o=i?n.put(s):n.put(s,r);await we.asyncRequest(o)}}),this}async deleteMany(e){let i=0;return await this._withStore("readwrite",async n=>{for await(const r of e)await we.asyncRequest(n.get(r))!==void 0&&i++,await we.asyncRequest(n.delete(r))}),i}async disconnect(){await we.closeConnection(this.dbName)}};class Hh{constructor(e,i,n=1/0,r){this.dbName=e,this.storeName=i,this.ttl=n,this.version=r,this.db=new qh(e,i),this.keys=this.db.keys.bind(this.db),this.values=this.db.values.bind(this.db),this.entries=this.db.entries.bind(this.db),typeof this.ttl!="number"&&(this.ttl=Number(this.ttl)),(isNaN(this.ttl)||this.ttl<=0)&&(this.ttl=1/0),this._clearExpiredEntries().catch(()=>{})}async _clearExpiredEntries(){if(this.ttl===1/0)return;const e=Date.now(),i=[];for await(const[n,r]of this.db.entries())typeof r.time=="number"&&e-r.time>this.ttl&&i.push(n);i.length>0&&await this.db.deleteMany(i)}async get(e,i=this.ttl,n){const r=await this.loadFromDB(e),s=this.checkIfExpired(r,i);if(!r||s){if(typeof n=="function"){const o=await n();return await this.set(e,o),o}return null}return r.value}async set(e,i){const n=Date.now();if(typeof e=="string"){const l=e,c=i;if(c===null||typeof c>"u")return this.delete(l);const u={time:n,value:c,version:this.version};return await this.db.set(l,u),u}const r=e,s=[],o=[],a={};for(const[l,c]of Object.entries(r))if(c===null||typeof c>"u")o.push(l);else{const u={time:n,value:c,version:this.version};s.push([l,u]),a[l]=u}return s.length>0&&await this.db.setMany(s),o.length>0&&await this.db.deleteMany(o),a}async has(e,i=this.ttl){const n=await this.loadFromDB(e),r=this.checkIfExpired(n,i);return n!==null&&!r}async delete(e){await this.db.delete(e)}async updatedAt(e){const i=await this.loadFromDB(e);return i?i.time:0}async loadFromDB(e){const i=await this.db.get(e);if(i===void 0)return null;if(typeof i.time!="number"||typeof i.value>"u"){try{await this.delete(e)}catch{}return null}if(typeof this.version=="number"&&i.version!==this.version){try{await this.delete(e)}catch{}return null}return i}checkIfExpired(e,i=this.ttl){return e?Date.now()-e.time>i:!1}async clear(){return await this.db.clear(),this}}class zh extends Ot{constructor(e,i){super(e,"storage",!1),this.config=i,this.kv=this.createDatabase("key-val",0,1,"indexedDB"),this.simpleKV=this.createDatabase("~",0,1,"localStorage"),this.memoryKV=this.createDatabase("~",0,1,"memory")}createDatabase(e,i,n,r="indexedDB"){const s="indexedDB"in window&&window.indexedDB!==null;switch(r==="indexedDB"&&!s&&(r="localStorage"),r){case"indexedDB":return new Hh(this.config.dbName,e,i,n);case"localStorage":case"sessionStorage":case"memory":return new Bh(this.config.dbName,e,i,n,r);default:throw new Error(`Unsupported storage engine: ${r}`)}}}var rt=(t=>(t.preferences="preferences",t.watch="watch",t.unwatch="unwatch",t.nochange="nochange",t))(rt||{});function Kh(t){const i=class i{constructor(r,s=!0){this._loaded=s,this.api=t,r.revisions?.forEach(o=>{typeof o?.slots?.main=="object"&&Object.assign(o,o.slots.main)}),this.pageInfo={...i.DEFAULT_PAGE_INFO,...r}}static async newFromApi(r){const{data:s}=await this.api.get({...i.DEFAULT_QUERY_PARAMS,...r}),o=s?.query?.pages?.[0];if(!o||!o.title)throw new Error("Invalid page info",{cause:s});return new i(o,!0)}static newBlankPage(r={}){return new i(r,!1)}static async newFromAnyKind(r){const{title:s,pageId:o,revisionId:a}=r||{};return a?this.newFromApi({revids:parseInt(a.toString(),10)}):o?this.newFromApi({pageids:parseInt(o.toString(),10)}):s?this.newFromApi({titles:s.toString()}):null}static async newBatchFromApi(r){const{titles:s,pageids:o,revids:a,...l}=r||{},{data:c}=await this.api.post({...i.DEFAULT_QUERY_PARAMS,titles:s?.join("|")??void 0,pageids:o?.join("|")??void 0,revids:a?.join("|")??void 0,...l});return c?.query?.pages?.map(u=>new i(u,!0))||[]}async parse(r){return this.api.post({action:"parse",page:this.pageInfo.title,prop:"text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties|parsewarnings",...r})}async preview(r,s){return this.parse({action:"parse",page:void 0,title:this.title,text:r,pst:1,preview:1,disableeditsection:1,disablelimitreport:1,...s})}async edit(r,s){const{text:o,prependtext:a,appendtext:l,summary:c="",watchlist:u=rt.preferences,section:d}=r;return this.api.postWithEditToken({action:"edit",title:this.title,starttimestamp:this.pageInfo.touched,basetimestamp:this.revisions[0]?.timestamp,text:o,prependtext:a,appendtext:l,summary:c,watchlist:u,section:d,...s})}async createOnly(r,s){return this.edit(r,{createonly:1,...s})}async delete(r,s){return this.api.postWithEditToken({action:"delete",title:this.pageInfo.title||void 0,pageid:this.pageInfo.pageid||void 0,reason:r,deletetalk:s?.deletetalk,...s})}async moveTo(r,s,o){return this.api.postWithEditToken({action:"move",from:this.pageInfo.title,to:r,reason:s,movetalk:1,movesubpages:1,...o})}userCan(r){return!!this.pageInfo?.actions?.[r]}userCanEdit(){return this.userCan("edit")}async reloadSelfInfo(){const r=await i.newFromApi({pageids:this.pageInfo.pageid,titles:this.pageInfo.title}),s=(this.pageInfo.revisions||[]).concat(r.revisions||[]).sort((o,a)=>o.revid-a.revid).reduce((o,a)=>(o.find(l=>l.revid===a.revid)||o.push(a),o),[]);return this.pageInfo=r.pageInfo,this.pageInfo.revisions=s,this._loaded=!0,this}get pageid(){return this.pageInfo.pageid}get title(){return this.pageInfo.title}get ns(){return this.pageInfo.ns}get contentmodel(){return this.pageInfo.contentmodel}get fullurl(){return this.pageInfo.fullurl}get canonicalurl(){return this.pageInfo.canonicalurl}get editurl(){return this.pageInfo.editurl}get revisions(){return this.pageInfo.revisions||[]}get lastrevid(){return this.pageInfo.lastrevid}get templates(){return this.pageInfo.templates||[]}get images(){return this.pageInfo.images||[]}};i.api=t,i.DEFAULT_QUERY_PARAMS={action:"query",prop:"info|templates|transcludedin|images|pageimages|revisions",inprop:"protection|url|varianttitles",intestactions:"edit|move|delete",tllimit:"max",tilimit:"max",imlimit:"max",piprop:"thumbnail|name|original",pithumbsize:"200",pilimit:"max",rvprop:"ids|timestamp|flags|comment|user|content",rvslots:"main"},i.DEFAULT_PAGE_INFO={pageid:0,ns:0,title:"",contentmodel:"wikitext",pagelanguage:"",pagelanguagehtmlcode:"",pagelanguagedir:"ltr",touched:new Date().toISOString(),lastrevid:0,length:0,protection:[],restrictiontypes:[],fullurl:"",canonicalurl:"",editurl:"",varianttitles:{},actions:{edit:!0,move:!1,delete:!1},revisions:[],templates:[],images:[]};let e=i;return e}const na=class na extends Ot{constructor(e){super(e,"wikiPage",!0),this.ctx=e,this.WikiPage=Kh(this.ctx.api)}async createInstance(e,i=!1){return await this.WikiPage.newFromApi(e)}async newFromTitle(e,i=!1,n,r=!1){return this.createInstance({titles:e.toString(),converttitles:i,rvsection:n},r)}async newFromPageId(e,i,n=!1){return this.createInstance({pageids:e,rvsection:i},n)}async newFromRevision(e,i,n=!1){return await this.createInstance({revids:e,rvsection:i},n)}newBlankPage(e={}){return this.WikiPage.newBlankPage(e)}};na.inject=["api"];let As=na;const tl=new WeakMap,bt={toDBKey:t=>t.replace(/ /g,"_"),toNormalText:t=>t.replace(/_/g," "),ensureCase:(t,e)=>e==="first-letter"?t.charAt(0).toUpperCase()+t.slice(1):t},xi={normalizeSpecialPageName:t=>t.toLowerCase(),buildSpecialPageIndex:t=>{const e=new Map,i=new Map,n=new Map;for(const r of t.specialpagealiases){const s=r.realname;e.set(s,s);const o=xi.normalizeSpecialPageName(s);n.set(o,s);for(const a of r.aliases){i.set(a,s);const l=xi.normalizeSpecialPageName(a);n.set(l,s)}}return{byRealName:e,byAlias:i,byNormalized:n}},findSpecialPageRealName:(t,e)=>{const i=t.split("/")[0];let n=e.byRealName.get(i)??e.byAlias.get(i);if(n!==void 0)return n;const r=xi.normalizeSpecialPageName(i);return e.byNormalized.get(r)??null}},ut={normalizeNamespaceText:t=>t.replace(/[_\s]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),buildIndex:t=>{const e=new Map,i=new Map,n=new Map,r=new Map;for(const[s,o]of Object.entries(t.namespaces)){const a=parseInt(s);e.set(o.name,a),i.set(o.canonical??"",a);const l=ut.normalizeNamespaceText(o.name),c=ut.normalizeNamespaceText(o.canonical??"");r.set(l,a),r.set(c,a)}for(const s of t.namespacealiases){n.set(s.alias,s.id);const o=ut.normalizeNamespaceText(s.alias);r.set(o,s.id)}return{byName:e,byCanonical:i,byAlias:n,byNormalized:r}},findNamespaceId:(t,e)=>{let i=e.byName.get(t)??e.byCanonical.get(t)??e.byAlias.get(t);if(i!==void 0)return i;const n=ut.normalizeNamespaceText(t);return e.byNormalized.get(n)??null},isTalkPage:t=>t%2===1&&t>0,getDefaultNamespaceInfo:t=>({id:t,name:"",canonical:"",case:"first-letter",content:!1,nonincludable:!1,subpages:!1})};function Wh(t){var s,o;const e=tl.get(t);if(e)return e;const i=ut.buildIndex(t),n=xi.buildSpecialPageIndex(t),a=class a{constructor(c,u){Hi(this,s);Hi(this,o);if(this.newTitle=a.create.bind(a),this.toText=this.getPrefixedText.bind(this),this.toString=this.getPrefixedDBKey.bind(this),Qe(this,s,c||""),Qe(this,o,u??0),u===void 0?this.fixNSByTitle():this.stripNamespaceFromTitle(),this.getMainText()==="")throw new Error("Invalid title")}static create(c,u){return new a(c,u)}fixNSByTitle(){const c=X(this,s).indexOf(":");if(c===-1)return;if(c===0){Qe(this,s,X(this,s).substring(1));return}const u=X(this,s).substring(0,c),d=X(this,s).substring(c+1),h=ut.findNamespaceId(u,a._namespaceIndex);h!==null&&(Qe(this,s,d),Qe(this,o,h))}stripNamespaceFromTitle(){const c=X(this,s).indexOf(":");if(c===-1)return;if(c===0){Qe(this,s,X(this,s).substring(1));return}const u=X(this,s).substring(0,c),d=X(this,s).substring(c+1);ut.findNamespaceId(u,a._namespaceIndex)!==null&&Qe(this,s,d)}getNamespaceInfo(){return a._meta.namespaces[X(this,o)]??ut.getDefaultNamespaceInfo(X(this,o))}getMainDBKey(){const c=this.getNamespaceInfo();if(X(this,o)===-1){const u=xi.findSpecialPageRealName(X(this,s),a._specialPageIndex);if(u){const d=X(this,s).includes("/")?X(this,s).substring(X(this,s).indexOf("/")):"",h=u+d;return bt.ensureCase(bt.toDBKey(h),c.case)}}return bt.ensureCase(bt.toDBKey(X(this,s)),c.case)}getMainText(){const c=this.getNamespaceInfo();if(X(this,o)===-1){const u=xi.findSpecialPageRealName(X(this,s),a._specialPageIndex);if(u){const d=X(this,s).includes("/")?X(this,s).substring(X(this,s).indexOf("/")):"",h=u+d;return bt.ensureCase(bt.toNormalText(h),c.case)}}return bt.ensureCase(bt.toNormalText(X(this,s)),c.case)}getMainRootText(){return this.getMainText().split("/")[0]}getPrefixedDBKey(){return X(this,o)===0?this.getMainDBKey():`${this.getNamespaceDBKey()}:${this.getMainDBKey()}`}getPrefixedText(){return X(this,o)===0?this.getMainText():`${this.getNamespaceText()}:${this.getMainText()}`}getNamespaceId(){return X(this,o)}getNamespaceText(){return this.getNamespaceInfo().name??""}getNamespaceDBKey(){const c=this.getNamespaceInfo();return bt.ensureCase(bt.toDBKey(this.getNamespaceText()),c.case)}getSubjectPage(){if(ut.isTalkPage(X(this,o))){const c=X(this,o)-1;return new a(X(this,s),c)}return this}getTalkPage(){if(ut.isTalkPage(X(this,o)))return this;if(X(this,o)<0)return null;const c=X(this,o)+1;return a._meta.namespaces[c.toString()]?new a(X(this,s),c):null}getURL(c){const u=a._meta.general.articlepath,d=this.getPrefixedDBKey(),h=u.replace("$1",d),p=new URL(h,location.origin);return c&&(c instanceof URLSearchParams?c:new URLSearchParams(c)).forEach((_,P)=>{p.searchParams.set(P,_)}),p}setTitle(c){return Qe(this,s,c),Qe(this,o,0),this.fixNSByTitle(),this}setMainText(c){return Qe(this,s,c),this}setNamespaceText(c){const u=ut.findNamespaceId(c,a._namespaceIndex);return u!==null&&Qe(this,o,u),this}setNamespaceId(c){return Qe(this,o,c),this}equals(c){return typeof c=="string"&&(c=new a(c)),this.getPrefixedDBKey()===c.getPrefixedDBKey()}isSpecial(c){if(X(this,o)!==-1)return!1;const u=new a(c,-1);return this.getMainRootText()===u.getMainRootText()}toJSON(){return{ns:X(this,o),text:this.getMainText(),title:this.getPrefixedText(),url:this.getURL().toString(),isSpecial:X(this,o)<0}}};s=new WeakMap,o=new WeakMap,a._meta=t,a._namespaceIndex=i,a._specialPageIndex=n;let r=a;return tl.set(t,r),r}const Rn=class Rn extends Ot{constructor(e){super(e,"wikiTitle",!0),this.ctx=e,this.logger=this.ctx.logger("WikiTitleService"),this._cachedTitles=new Map,this.wiki=this.ctx.wiki,this.wikiBaseUrl=this.wiki.baseUrl,this.wikiArticlePath=this.wiki.articlePath.replace("$1",""),this.wikiArticleBaseUrl=this.wiki.articleBaseUrl.replace("$1",""),this.wikiIndexPhpUrl=this.wiki.getSciprtUrl("index.php"),this.Title=Wh(this.ctx.wiki.siteInfo)}newTitle(e,i){return new this.Title(e,i)}newMainPageTitle(){return this.newTitle(this.ctx.wiki.mainPageName)}async newTitleFromUrl(e){const i=this.parseWikiLink(e);return i?.title?i.title:i?.pageId?this.newTitleFromPageId(i.pageId):null}async newTitleFromAnyId(e,i=!1){const{title:n,pageId:r,revId:s}=e??{};if(typeof n=="string")return this.newTitle(n);let o,a;if(s?(o=parseInt(s.toString(),10),a="revid"):r&&(o=parseInt(r.toString(),10),a="pageid"),!o||!a||isNaN(o)||o<=0)throw new Error("Invalid id or kind",{cause:e});if(!i&&this._cachedTitles.has(`${a}:${o}`))return await this._cachedTitles.get(`${a}:${o}`);const{promise:l,resolve:c,reject:u}=re();this._cachedTitles.set(`${a}:${o}`,l);try{const{wikiPage:d}=this.ctx;let h=null;if(a==="pageid")h=await d.newFromPageId(o);else if(a==="revid")h=await d.newFromRevision(o);else throw new Error(`Invalid kind: ${a}`);c(this.newTitle(h.title))}catch(d){this._cachedTitles.delete(`${a}:${o}`),u(d)}return l}async newTitleFromPageId(e){return this.newTitleFromAnyId({pageId:e})}async newTitleFromRevision(e){return this.newTitleFromAnyId({revId:e})}resolveSpecialPageTarget(e){const i=typeof e=="string"?this.newTitle(e):e;if(!i||i.getNamespaceId()!==-1)return null;let n,r,s="view";const o=i.getMainDBKey().split("/").slice(1).join("/")||"";if(i.isSpecial("edit")&&o)n=o,s="edit";else if(i.isSpecial("talkpage")&&o){const a=i.newTitle(o).getTalkPage();if(!a)return null;n=a.getPrefixedDBKey()}else if(i.isSpecial("mypage"))n=i.newTitle(this.ctx.wiki.userInfo.name,2).getPrefixedDBKey()+(o?`/${o}`:"");else if(i.isSpecial("mytalk"))n=i.newTitle(this.ctx.wiki.userInfo.name,3).getPrefixedDBKey()+(o?`/${o}`:"");else if(i.isSpecial("newsection")&&o)n=o,r="new",s="edit";else return null;return{title:new this.Title(n),section:r,action:s}}isWikiLink(e){return e.startsWith(this.wikiArticleBaseUrl)||e.startsWith(this.wikiIndexPhpUrl)||e.startsWith(`${this.wikiBaseUrl}/?`)||e===this.ctx.wiki.landingPageUrl}validateHrefAttr(e){return typeof e!="string"?!1:!Rn.REG_SKIPPED_HREF.test(e)}parseWikiLink(e){if(!e||typeof e=="string"&&!this.validateHrefAttr(e))return null;const i=Ya(e);if(!this.isWikiLink(i.toString()))return null;const n=i.searchParams,r=i.hash.replace("#",""),s=n.get("action")||"view",o=n.get("title")||"",a=parseInt(n.get("curid")||"0",10),l=parseInt(n.get("oldid")||"0",10);let c=o||(()=>{try{return decodeURIComponent(i.pathname.substring(this.wikiArticlePath.length))}catch(p){return this.logger.error("parseLink",i,p),""}})();c.endsWith("index.php")&&(c="");let u,d,h;if(l)h=l;else if(a)d=a;else if(c)u=this.newTitle(c);else if(i.origin+i.pathname===this.ctx.wiki.landingPageUrl)u=this.newMainPageTitle();else return null;return{title:u,pageId:d,revId:h,url:i,params:n,hash:r,action:s}}};Rn.inject=["wiki","wikiPage"],Rn.REG_SKIPPED_HREF=/^(#|javascript:|vbscript:|file:)/i;let Is=Rn;const Vh=t=>typeof t=="function";async function Gh(t){return Vh(t)?await t():t}var Yh=Object.create,Os=Object.defineProperty,Qh=Object.getOwnPropertyDescriptor,il=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),nl=t=>{throw TypeError(t)},Jh=(t,e,i)=>e in t?Os(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Xh=(t,e)=>Os(t,"name",{value:e,configurable:!0}),Zh=t=>[,,,Yh(t?.[il("metadata")]??null)],ep=["class","method","getter","setter","accessor","field","value","get","set"],rl=t=>t!==void 0&&typeof t!="function"?nl("Function expected"):t,tp=(t,e,i,n,r)=>({kind:ep[t],name:e,metadata:n,addInitializer:s=>i._?nl("Already initialized"):r.push(rl(s||null))}),ip=(t,e)=>Jh(e,il("metadata"),t[3]),np=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},rp=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Qh(r,i));Xh(r,i);for(var f=n.length-1;f>=0;f--)l=tp(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,rl(o)&&(r=o);return ip(t,r),p&&Os(r,i,p),u?c^4?s:p:r},sl,Ts,ol;sl=[$e(["storage","wiki"])];class Zn extends(ol=Ot){constructor(e){super(e,"preferences",!0),this.ctx=e,this.db=void 0,this.customRegistries=[],this.categoryDefinitions=[],this._defaultPreferences={},e.set("prefs",this),this.db=e.storage.createDatabase(`preferences:${e.wiki.userInfo.id}`,1/0);try{this._migrageFromLegacyMasterDB()}catch{}}get logger(){return this.ctx.logger("PREFERENCES")}async start(){this.defineCategory({name:"general",label:"General",description:"General settings",autoGenerateForm:!0}),this.defineCategory({name:"editor",label:"Editor",description:"Settings related to editing content",autoGenerateForm:!0})}async get(e,i){if(!e)return this.getAll();i??(i=()=>{const r=this.defaultOf(e);return this.logger.debug(e,`(fallback value: ${r})`),r});const n=await this.db.get(e,void 0);return n!==null?n:await Gh(i)}async getAll(){const e=this.loadDefaultConfigs();for await(const[i,n]of this.db.entries())i!=="_touched"&&i in e&&(e[i]=n.value);return e}async set(e,i){return(await this.setMany({[e]:i}))[e]}async setMany(e){const i=this.loadDefaultConfigs(),n={};for(const[r,s]of Object.entries(e))s===i[r]||s===void 0?n[r]=void 0:n[r]=s;return await this.db.set(n),this.ctx.emit("preferences/changed",{ctx:this.ctx,input:e,changes:n}),n}defaultOf(e){var i;return(i=this._defaultPreferences)[e]??(i[e]=this.loadDefaultConfigs()[e])}async getExportableRecord(e){e??(e=await this.getAll());const i=this.loadDefaultConfigs(),n={};return Object.entries(i).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{const o=e[r];o!==void 0&&o!==s&&(n[r]=o)}),n}loadDefaultConfigs(){const e={};return this.getConfigRegistries().forEach(i=>{try{const n=i.schema({});Object.entries(n).forEach(([r,s])=>{e[r]=s})}catch{}}),Object.entries(e).forEach(([i,n])=>{this._defaultPreferences[i]=n}),e}registerCustomConfig(e,i,n){return this.customRegistries.push({name:e,schema:i,category:n||"general"}),this}getConfigRegistries(e){return Array.from(this.ctx.registry.entries()).map(([i])=>i===null?{name:"@root",schema:Si?.PreferencesSchema||null}:{name:i.name,schema:i?.PreferencesSchema||null}).filter(i=>i.schema!==null).map(i=>({...i,category:i.schema.meta.category||"general"})).concat(this.customRegistries).filter(i=>!e||i.category===e)}getAllSchema(){return new L(L.intersect(this.getConfigRegistries().map(e=>e.schema)))}defineCategory(e){const i=this.categoryDefinitions.findIndex(n=>n.name===e.name);return i<0?this.categoryDefinitions.push(e):this.categoryDefinitions[i]=e,this.categoryDefinitions.sort((n,r)=>(n.index??0)-(r.index??0)),this}getConfigCategories(){return this.categoryDefinitions}async _migrageFromLegacyMasterDB(){const e=this.ctx.storage.createDatabase("preferences",1/0);let i=0;for await(const[n,r]of e.entries())n!=="_touched"&&(await this.db.set(n,r.value),i++);return i&&this.logger.info(`Migrated ${i} preferences from master DB`),await e.clear(),await e?.db?.disconnect?.(),i}}Ts=Zh(ol),Zn=rp(Ts,0,"PreferencesService",sl,Zn),np(Ts,1,Zn);var Lt=(t=>(t.ANALYTICS_API_BASE="https://analytics.ipe.wiki/api/v6",t.ANALYTICS_DASH_URL="https://analytics.ipe.wiki",t.GITHUB_URL="https://github.com/inpageedit/inpageedit-next",t.HOME_URL="https://www.ipe.wiki/",t.UPDATE_LOGS_URL="https://www.ipe.wiki/changelogs/",t.PLUGIN_REGISTRY_URL="https://registry.ipe.wiki/registry.v1.json",t))(Lt||{});const An=class An extends Be{constructor(i){super({name:"InPageEdit"});Hi(this,$t);this.version="0.13.0-alpha.1",this.Endpoints=Lt,this.schema=L,this.config=Vi(An.DEFAULT_CONFIG,i),this.logger=Sa({name:"IPE",color:"#33aaff",level:this.config.logLevel}),lt(this,$t,If).call(this),this.config.autoInstallCorePlugins&<(this,$t,Tf).call(this),lt(this,$t,Lf).call(this)}async withInject(i){const{promise:n,resolve:r}=re();return this.inject(i,s=>{r(s)}),n}};$t=new WeakSet,If=async function(){this.plugin(Ed,this.config.apiConfigs),this.plugin(zn),this.plugin(Md),this.plugin(Ph),this.plugin(Zn),this.plugin(zh,{dbName:this.config.storageNamespace}),this.plugin(Xn),this.plugin(As),this.plugin(Is),lt(this,$t,Of).call(this,["api","currentPage","resourceLoader","modal","preferences","storage","wikiPage","wikiTitle","wiki","getUrl","getSciprtUrl","getMainpageUrl"])},Of=function(i){if(typeof i=="string"&&(i=[i]),!Array.isArray(i)||i.length===0)return this;for(const n of i){const r=this[An.internal][n];r?.type==="service"&&(r.builtin=!0)}return this},Tf=async function(){[Promise.resolve().then(()=>vp).then(({PluginAnalytics:n})=>n),Promise.resolve().then(()=>Ap).then(({PluginInArticleLinks:n})=>n),Promise.resolve().then(()=>dy).then(({PluginPluginStore:n})=>n),Promise.resolve().then(()=>Uy).then(({PluginPreferencesUI:n})=>n),Promise.resolve().then(()=>eb).then(({PluginQuickEdit:n})=>n),Promise.resolve().then(()=>fb).then(({PluginQuickMove:n})=>n),Promise.resolve().then(()=>xb).then(({PluginQuickPreview:n})=>n),Promise.resolve().then(()=>Ub).then(({PluginQuickDiff:n})=>n),Promise.resolve().then(()=>Fb).then(({PluginQuickRedirect:n})=>n),Promise.resolve().then(()=>Jb).then(({PluginToolbox:n})=>n)].forEach(async n=>{this.plugin(await n)})},Lf=async function(){this.inject(["resourceLoader"],i=>{})},An.DEFAULT_CONFIG={apiConfigs:{},legacyPreferences:{},logLevel:ls.info,storageNamespace:"InPageEdit",autoloadStyles:!0,autoInstallCorePlugins:!0};let Si=An;function al(t){return t.charAt(0).toLowerCase()+t.slice(1)}function sp(t){return al(t).replace(/_/g,"-").replace(/.[A-Z]+/g,e=>e[0]+"-"+e.slice(1).toLowerCase())}function op(t){return al(t).replace(/-/g,"_").replace(/.[A-Z]+/g,e=>e[0]+"_"+e.slice(1).toLowerCase())}const Vr=class Vr{constructor(e,i=void 0,n){Hi(this,In);this.ctx=e,this.disposeHandlers=[],this.name=n||"",this.config=i||{};const{promise:r,resolve:s,reject:o}=Promise.withResolvers();queueMicrotask(()=>{this.name||(this.name=this.constructor.name);try{const a=this.start();a&&typeof a.then=="function"?a.then(()=>s()).catch(l=>{this.logger.error("start() returns a rejected promise",l),o(l)}):s()}catch(a){this.logger.error("start() threw synchronously",a),o(a)}r.then(()=>{this.logger.debug("started")}),r.catch(a=>{this.logger.error("start failed",a),this.ctx.scope.dispose()})}),this.ctx.once("dispose",()=>{this.disposeHandlers.forEach(a=>a(this.ctx)),this.stop(),this.logger.debug("disposed")})}start(){}stop(){}addDisposeHandler(e){this.disposeHandlers.push(e)}removeDisposeHandler(e){this.disposeHandlers=this.disposeHandlers.filter(i=>i!==e)}set name(e){Qe(this,In,op(e).toUpperCase())}get name(){return X(this,In)}get logger(){return this.ctx.logger(this.name)}};In=new WeakMap,Vr.inject=[],Vr.reusable=!1;let Xe=Vr;function si(t){return function(e){return e.PreferencesSchema=t,e}}window.RLQ||(window.RLQ=[]),window.__IPE_MODULES__||(window.__IPE_MODULES__=[]),lp("InPageEdit#autoload",()=>{const t=ll();t&&ap({baseURL:t,InPageEdit:Si})});async function ap(t={baseURL:ll(),InPageEdit:Si}){const{baseURL:e,InPageEdit:i}=t;typeof window?.ipe?.stop=="function"&&await window.ipe.stop();const n=window.InPageEdit||{},r=new i({apiConfigs:{baseURL:e},legacyPreferences:n?.myPreferences||{}});if(window.ipe=r,await r.start(),window.RLQ.push(()=>{mw.hook("InPageEdit.ready").fire(r)}),Array.isArray(window.__IPE_MODULES__)){const s=[];for(;window.__IPE_MODULES__.length;)try{const o=window.__IPE_MODULES__.shift();typeof o=="function"&&o?.(r),s.push(o)}catch{}window.__IPE_MODULES__={push:o=>{typeof o=="function"&&o(r),s.push(o)}},r.on("dispose",()=>{window.__IPE_MODULES__=s})}r.logger("AUTOLOAD").info(`
|
|
4
|
+
`),this.code=this.isBadTokenError()?"badtoken":this.errors[0]?.code||"Unknown Error"}get firstError(){return this.errors[0]}isBadTokenError(){return this.errors.some(e=>e.code==="badtoken")||["NeedToken","WrongToken"].includes(this.cause?.data?.login?.result)}toString(){return`[${this.name} ${this.code}]`}static is(e){return e instanceof this}static normalizeErrors(e){return Array.isArray(e)===!1?[]:e.filter(i=>typeof i=="object"&&!!i?.code).map(i=>i.text?i:i.info?{...i,text:i.info}:i["*"]?{...i,text:i["*"]}:{...i,text:""})}};(t=>{function e(s){if(s==null)return;if(s?.response?.data!==void 0)return s.response.data;if(s?.data!==void 0)return s.data;const o=s instanceof Error?s.cause:void 0;return o?.response?.data!==void 0?o.response.data:o?.data!==void 0?o.data:s||void 0}function i(s){return n(s).length>0}t.includesMediaWikiApiError=i,t.normalizeMwApiErrors=bi.normalizeErrors;function n(s){let o=e(s);if(typeof o!="object"||o===null)return[];const a=o?.error,l=o?.errors,c=[];return a&&c.push(a),Array.isArray(l)&&c.push(...l),(0,t.normalizeMwApiErrors)(c)}t.extractMediaWikiApiErrors=n;function r(s){if(bi.is(s))return s.isBadTokenError();{const o=n(s);return new bi(o).isBadTokenError()}}t.isBadTokenError=r})(He||(He={}));const Pa=Symbol.for("__FEXIOS_SAIKOU__");function Ca(t){const e=t instanceof ds?t:new ds({baseURL:t instanceof URL?t.toString():String(t),responseType:"json"});return e[Pa]||(Reflect.defineProperty(e,Pa,{get:()=>!0,enumerable:!1,configurable:!1}),e._tokens=new Map,e.on("afterResponse",i=>{const{data:n,rawRequest:r}=i,s=r?.headers.get("x-mw-token-name");s&&He.isBadTokenError(n)&&e._tokens.delete(s);const o=n?.query?.tokens;o&&typeof o=="object"&&Object.entries(o).forEach(([l,c])=>{typeof c=="string"&&e._tokens.set(l.replace(/token$/i,"").toLowerCase(),c)});const a=n?.login?.token;return typeof a=="string"&&e._tokens.set("login",a),i}),e.on("beforeInit",i=>{if(i.method?.toLowerCase()!=="post")return i;if(i.body===void 0||i.body===null)return i.body=void 0,i;const n=i.body=Hn.normalizeBody(i.body),r=new URLSearchParams(i.query);return n.has("format")&&r.delete("format"),n.has("formatversion")&&r.delete("formatversion"),n.has("action")&&r.delete("action"),n.has("origin")&&(r.set("origin",""+n.get("origin")),n.delete("origin")),i.query=Object.fromEntries(r.entries()),i}),e.on("beforeInit",i=>(i.query=Hn.normalizeBody(i.query)||{},i)),e.on("beforeRequest",i=>{const n=new URL(i.url),r=n.searchParams;if(globalThis.location&&(!r.has("origin")&&location.origin!==n.origin?(r.set("origin",location.origin),e.baseConfigs.credentials="include",e.baseConfigs.mode="cors"):location.origin===n.origin&&(r.delete("origin"),e.baseConfigs.credentials=void 0,e.baseConfigs.mode=void 0)),n.searchParams.has("origin")){const s=encodeURIComponent(n.searchParams.get("origin")||"").replace(/\./g,"%2E");i.query={},n.searchParams.delete("origin"),i.url=`${n}${n.search?"&":"?"}origin=${s}`}return i})),e}const ei=(t,...e)=>{const i=s=>Object.prototype.toString.call(s)==="[object Object]",n=s=>{if(Array.isArray(s))return s.slice();if(i(s)){const o={};for(const a of Reflect.ownKeys(s))o[a]=n(s[a]);return o}return s},r=n(t);for(const s of e)if(s!=null)for(const o of Reflect.ownKeys(s)){const a=s[o];if(typeof a>"u")continue;const l=r[o];i(l)&&i(a)?r[o]=ei(l,a):r[o]=n(a)}return r},_d=(t,e,i)=>{let n={...Ra.DEFAULT_CONFIGS};if(typeof t=="string"?n=ei(n,{baseURL:t,fexiosConfigs:e||{},defaultParams:i||{}}):typeof t=="object"&&t!==null&&(n=ei(n,t)),!n.baseURL&&typeof window=="object"&&window.mediaWiki){const{wgServer:r,wgScriptPath:s}=window.mediaWiki?.config?.get(["wgServer","wgScriptPath"])||{};typeof r=="string"&&typeof s=="string"&&(n.baseURL=`${r}${s}/api.php`)}if(typeof n.baseURL!="string")throw new Error("baseURL is required");return n},xd=()=>{},Sd=async(t,e)=>{let i=0;const{retry:n=3,onRetry:r=xd,shouldRetry:s=()=>!0}=e;let o;do try{return await t()}catch(a){if(o=a,s(a,i))r(a,i),i++;else throw a}while(i<n);throw o||new Error("Retry failed")};const Ji=class{constructor(e,i,n){this.version="7.1.2",this.token=this.getToken;const r=this.config=_d(e,i,n);this.request=Ca(r.baseURL)}setBaseURL(e){return this.config.baseURL=e,this.request.baseConfigs.baseURL=e,this}async get(e,i){return this.runRequestWithApiErrorMapping(()=>this.request.get("",ei({},this.config.fexiosConfigs,{query:ei(this.config.defaultParams,e)},i)))}async post(e,i){return this.runRequestWithApiErrorMapping(()=>this.request.post("",e,ei({},this.config.fexiosConfigs,{query:this.config.defaultParams},i)))}async runRequestWithApiErrorMapping(e){try{const i=await e();return this.handleApiResponse(i)}catch(i){throw this.config.throwOnApiError&&He.includesMediaWikiApiError(i)?new bi(He.extractMediaWikiApiErrors(i),i):i}}throwIfApiError(e){const i=He.extractMediaWikiApiErrors(e);if(i.length>0)throw new bi(i,e)}handleApiResponse(e){return this.config.throwOnApiError&&this.throwIfApiError(e.data),e}get tokens(){return this.request._tokens}async fetchTokens(e=["csrf"]){return this.config.fexiosConfigs.credentials="include",await this.get({action:"query",meta:"tokens",type:e}),this.tokens}async getToken(e="csrf",i=!1){return(!this.tokens.get(e)||i)&&(this.tokens.delete(e),await this.fetchTokens([e])),this.tokens.get(e)}badToken(e){return this.tokens.delete(e),this.tokens}async postWithToken(e,i,n){const{tokenName:r="token",retry:s=3,noCache:o=!1,fexiosOptions:a}=n||{};if(s<1)throw new He(Qi.TOKEN_RETRY_LIMIT_EXCEEDED,"The limit of the number of times to automatically re-acquire the token has been exceeded");let l=0;return Sd(async()=>{const c=await this.getToken(e,o||l>0);try{const u=await this.post({[r]:c,...i},ei(a||{},{headers:{"x-mw-token-name":e}}));if(He.isBadTokenError(u.data))throw u;return u}catch(u){throw He.isBadTokenError(u)||u?.ok===!1||bi.is(u)?u:new He(Qi.HTTP_ERROR,"Network/transport or SDK-internal error (not a MediaWiki API error)",u)}},{retry:s,onRetry:(c,u)=>{l=u+1},shouldRetry:c=>He.isBadTokenError(c)||c?.ok===!1}).catch(c=>{throw He.isBadTokenError(c)||c?.ok===!1?new He(Qi.TOKEN_RETRY_LIMIT_EXCEEDED,"Retry attempts for acquiring/using token exhausted",c):c})}postWithEditToken(e){return this.postWithToken("csrf",e)}get baseURL(){return this.config.baseURL}get defaultParams(){return this.config.defaultParams}get defaultOptions(){return this.config.fexiosConfigs}};Ji.INIT_DEFAULT_PARAMS={action:"query",errorformat:"plaintext",format:"json",formatversion:2},Ji.DEFAULT_CONFIGS={baseURL:void 0,fexiosConfigs:{responseType:"json"},defaultParams:Ji.INIT_DEFAULT_PARAMS,throwOnApiError:!1},Ji.createRequestHandler=Ca;let Ra=Ji;let kd=class extends Ra{async clientLogin(e,i,n){n||(n={}),!n.logincontinue&&!n.loginreturnurl&&(n.loginreturnurl=location?.origin);const r=await this.postWithToken("login",{action:"clientlogin",username:e,password:i,...n},{tokenName:"logintoken"});if(r?.data?.clientlogin?.status==="PASS")return r.data.clientlogin;throw new He(Qi.LOGIN_FAILED,r.data.clientlogin.message,r)}};class Ed{constructor(e,i={}){this.ctx=e,location?.href&&i?.baseURL?.toString()?.startsWith("/")&&(i.baseURL=new URL(i.baseURL,location.origin));const n=new kd({baseURL:i.baseURL.toString(),fexiosConfigs:{headers:{"x-api-user-agent":`InPageEdit-NEXT ${e.version}`,...i.headers},...i},throwOnApiError:!0});e.set("api",n)}}var $d=Object.create,hs=Object.defineProperty,Pd=Object.getOwnPropertyDescriptor,Aa=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ia=t=>{throw TypeError(t)},Cd=(t,e,i)=>e in t?hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Rd=(t,e)=>hs(t,"name",{value:e,configurable:!0}),Ad=t=>[,,,$d(t?.[Aa("metadata")]??null)],Id=["class","method","getter","setter","accessor","field","value","get","set"],Oa=t=>t!==void 0&&typeof t!="function"?Ia("Function expected"):t,Od=(t,e,i,n,r)=>({kind:Id[t],name:e,metadata:n,addInitializer:s=>i._?Ia("Already initialized"):r.push(Oa(s||null))}),Td=(t,e)=>Cd(e,Aa("metadata"),t[3]),Ld=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},Nd=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Pd(r,i));Rd(r,i);for(var f=n.length-1;f>=0;f--)l=Od(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,Oa(o)&&(r=o);return Td(t,r),p&&hs(r,i,p),u?c^4?s:p:r},Ta,ps,La;Ta=[$e(["wiki","wikiTitle"])];class zn extends(La=Ot){constructor(i){super(i,"currentPage",!1);Hi(this,Ve);this.ctx=i,this.url=new URL(window.location.href),this.isMainPage=void 0,this.wikiTitle=void 0}get logger(){return this.ctx.logger("CURRENT_PAGE")}async start(){await lt(this,Ve,oa).call(this),lt(this,Ve,Cf).call(this),window.addEventListener("popstate",lt(this,Ve,aa).bind(this)),this.logger.info("initialized",this.wikiTitle)}stop(){window.removeEventListener("popstate",lt(this,Ve,aa).bind(this))}get params(){return this.url.searchParams}get canonicalUrl(){const i=document.querySelector('link[rel="canonical"]')?.href;let n=null;return i&&(n=new URL(i,location.origin)),Reflect.defineProperty(this,"canonicalUrl",{get:()=>n}),n}get wikiAction(){return this.params.get("action")||"view"}}Ve=new WeakSet,oa=async function(){await lt(this,Ve,Af).call(this),await lt(this,Ve,Rf).call(this)},Cf=function(){const i=Symbol.for("InPageEdit.CurrentPageService.UrlChangeListenerInstalled");if(window[i])return;const n=history.pushState,r=history.replaceState;history.pushState=function(s,o,a){n.apply(this,[s,o,a]),window.dispatchEvent(new PopStateEvent("popstate",{state:s}))},history.replaceState=function(s,o,a){r.apply(this,[s,o,a]),window.dispatchEvent(new PopStateEvent("popstate",{state:s}))},window[i]=!0},aa=async function(i){const n=this.url,r=new URL(window.location.href);this.url=r,(n.pathname!==r.pathname||n.searchParams.get("title")!==r.searchParams.get("title")||n.searchParams.get("curid")!==r.searchParams.get("curid"))&&(await lt(this,Ve,oa).call(this),this.logger.info("location changed",r,this.wikiTitle))},Rf=async function(){const n=this.wikiTitle?.getMainDBKey()===this.ctx.wiki.mainPageName;return Reflect.defineProperty(this,"isMainPage",{get:()=>n}),n},Af=async function(){let i=null;return this.canonicalUrl?i=await this.ctx.wikiTitle.newTitleFromUrl(this.canonicalUrl):i=await this.ctx.wikiTitle.newTitleFromUrl(this.url),Object.freeze(i),Reflect.defineProperty(this,"wikiTitle",{get:()=>i}),i},ps=Ad(La),zn=Nd(ps,0,"CurrentPageService",Ta,zn),Ld(ps,1,zn);class Md extends Ot{constructor(e){super(e,"resourceLoader",!0),this.ctx=e}stop(){this.removeAll()}loadScript(e,i){if(!e)return Promise.resolve(null);const n=`script:${e}`,r=document.querySelector(`[data-ipe="${n}"]`);return r?Promise.resolve(r):new Promise((o,a)=>{const l=document.createElement("script");l.src=e,l.dataset.ipe=n,i&&Object.entries(i).forEach(([c,u])=>{typeof u>"u"||u===!1||u===null?l.removeAttribute(c):l.setAttribute(c,u)}),document.body.appendChild(l),l.onload=()=>o(l),l.onerror=c=>a(c)})}loadStyle(e,i){if(!e)return Promise.resolve(null);const n=`style:${e}`,r=document.querySelector(`[data-ipe="${n}"]`);return r?Promise.resolve(r):new Promise((o,a)=>{const l=document.createElement("link");l.rel="stylesheet",l.href=e,l.dataset.ipe=n,i&&Object.entries(i).forEach(([u,d])=>{typeof d>"u"||d===!1||d===null?l.removeAttribute(u):l.setAttribute(u,d)}),(document.querySelector('meta[name="ipe-styles"]')||(()=>{const u=document.createElement("meta");return u.id="ipe-styles",u.name="ipe-styles",document.head.insertAdjacentElement("afterbegin",u),u})()).before(l),l.onload=()=>o(l),l.onerror=u=>a(u)})}removeStyle(e){const i=`style:${e}`,n=document.querySelector(`[data-ipe="${i}"]`);n&&n.remove()}removeScript(e){const i=`script:${e}`,n=document.querySelector(`[data-ipe="${i}"]`);n&&n.remove()}removeAll(){document.querySelectorAll("[data-ipe]").forEach(e=>{e.remove()})}resolveImportPath(e){if(e.startsWith("http")||e.startsWith("//"))return e;const i=document.currentScript?.src;if(!i)return`https://unpkg.com/mediawiki-inpageedit@latest/dist/${e}`;const n=new URL(i);return n.pathname.endsWith(".js")||(n.pathname=n.pathname+"/"),new URL(e,n.toString()).toString()}}const Kn=Object.keys;function Dd(t){return typeof t=="boolean"}function jd(t){return t&&typeof t.nodeType=="number"}function Wn(t){return typeof t=="string"}function Na(t){return typeof t=="number"}function ti(t){return typeof t=="object"?t!==null:Xi(t)}function Xi(t){return typeof t=="function"}function Ud(t){return!!(t&&t.isComponent)}function Fd(t){return ti(t)&&typeof t.length=="number"&&typeof t.nodeType!="number"}function ms(t,e){if(t)for(const i of Kn(t))e(t[i],i)}function Bd(t){return ti(t)&&"current"in t}const gs={animationIterationCount:0,borderImageOutset:0,borderImageSlice:0,borderImageWidth:0,boxFlex:0,boxFlexGroup:0,boxOrdinalGroup:0,columnCount:0,columns:0,flex:0,flexGrow:0,flexPositive:0,flexShrink:0,flexNegative:0,flexOrder:0,gridArea:0,gridRow:0,gridRowEnd:0,gridRowSpan:0,gridRowStart:0,gridColumn:0,gridColumnEnd:0,gridColumnSpan:0,gridColumnStart:0,fontWeight:0,lineClamp:0,lineHeight:0,opacity:0,order:0,orphans:0,tabSize:0,widows:0,zIndex:0,zoom:0,fillOpacity:0,floodOpacity:0,stopOpacity:0,strokeDasharray:0,strokeDashoffset:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0};function qd(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)}const Hd=["Webkit","ms","Moz","O"];Kn(gs).forEach(t=>{Hd.forEach(e=>{gs[qd(e,t)]=0})});const zd=Symbol.for("jsx-dom:type");var Ma=(function(t){return t.ShadowRoot="ShadowRoot",t})(Ma||{});function Kd(t){return t!=null&&t[zd]===Ma.ShadowRoot}const Wd="http://www.w3.org/2000/svg",Vd="http://www.w3.org/1999/xlink",Gd="http://www.w3.org/XML/1998/namespace";function Da(t){return!Dd(t)&&t!=null}function ys(t){return Array.isArray(t)?t.map(ys).filter(Boolean).join(" "):ti(t)?Symbol.iterator in t?ys(Array.from(t)):Kn(t).filter(e=>t[e]).join(" "):Da(t)?""+t:""}const Yd={animate:0,circle:0,clipPath:0,defs:0,desc:0,ellipse:0,feBlend:0,feColorMatrix:0,feComponentTransfer:0,feComposite:0,feConvolveMatrix:0,feDiffuseLighting:0,feDisplacementMap:0,feDistantLight:0,feFlood:0,feFuncA:0,feFuncB:0,feFuncG:0,feFuncR:0,feGaussianBlur:0,feImage:0,feMerge:0,feMergeNode:0,feMorphology:0,feOffset:0,fePointLight:0,feSpecularLighting:0,feSpotLight:0,feTile:0,feTurbulence:0,filter:0,foreignObject:0,g:0,image:0,line:0,linearGradient:0,marker:0,mask:0,metadata:0,path:0,pattern:0,polygon:0,polyline:0,radialGradient:0,rect:0,stop:0,svg:0,switch:0,symbol:0,text:0,textPath:0,tspan:0,use:0,view:0},Qd=/^(a(ll|t|u)|base[FP]|c(al|lipPathU|on)|di|ed|ex|filter[RU]|g(lyphR|r)|ke|l(en|im)|ma(rker[HUW]|s)|n|pat|pr|point[^e]|re[^n]|s[puy]|st[^or]|ta|textL|vi|xC|y|z)/;function vi(t){const e=document.createDocumentFragment();return Vn(t.children,e),e}function Jd(t,e,i){e={...e,children:i};const n=new t(e),r=n.render();return"ref"in e&&bs(e.ref,n),r}function m(t,e){let{children:i,...n}=e;!n.namespaceURI&&Yd[t]===0&&(n={...n,namespaceURI:Wd});let r;if(Wn(t)){if(r=n.namespaceURI?document.createElementNS(n.namespaceURI,t):document.createElement(t),eh(n,r),Vn(i,r),r instanceof window.HTMLSelectElement&&n.value!=null)if(n.multiple===!0&&Array.isArray(n.value)){const s=n.value.map(o=>String(o));r.querySelectorAll("option").forEach(o=>o.selected=s.includes(o.value))}else r.value=n.value;bs(n.ref,r)}else if(Xi(t))ti(t.defaultProps)&&(n={...t.defaultProps,...n}),r=Ud(t)?Jd(t,n,i):t({...n,children:i});else throw new TypeError(`Invalid JSX element type: ${t}`);return r}function Zi(t,e){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return(Wn(e)||Array.isArray(e))&&(n.unshift(e),e={}),e=e||{},e.children!=null&&!n.length&&({children:n,...e}=e),m(t,{...e,children:n},e.key)}function bs(t,e){Bd(t)?t.current=e:Xi(t)&&t(e)}function Vn(t,e){if(Fd(t))Xd(t,e);else if(Wn(t)||Na(t))vs(document.createTextNode(t),e);else if(t===null)vs(document.createComment(""),e);else if(jd(t))vs(t,e);else if(Kd(t)){const i=e.attachShadow(t.attr);Vn(t.children,i),bs(t.ref,i)}}function Xd(t,e){for(const i of[...t])Vn(i,e);return e}function vs(t,e){e instanceof window.HTMLTemplateElement?e.content.appendChild(t):e.appendChild(t)}function Gn(t,e){return t.replace(/[A-Z]/g,i=>e+i.toLowerCase())}function ja(t,e){e==null||e===!1||(Array.isArray(e)?e.forEach(i=>ja(t,i)):Wn(e)?t.setAttribute("style",e):ti(e)&&ms(e,(i,n)=>{n.indexOf("-")===0?t.style.setProperty(n,i):Na(i)&&gs[n]!==0?t.style[n]=i+"px":t.style[n]=i}))}function Zd(t,e,i){switch(t){case"xlinkActuate":case"xlinkArcrole":case"xlinkHref":case"xlinkRole":case"xlinkShow":case"xlinkTitle":case"xlinkType":Ua(i,Vd,Gn(t,":"),e);return;case"xmlnsXlink":wi(i,Gn(t,":"),e);return;case"xmlBase":case"xmlLang":case"xmlSpace":Ua(i,Gd,Gn(t,":"),e);return}switch(t){case"htmlFor":wi(i,"for",e);return;case"dataset":ms(e,(n,r)=>{n!=null&&(i.dataset[r]=n)});return;case"innerHTML":case"innerText":case"textContent":Da(e)&&(i[t]=e);return;case"dangerouslySetInnerHTML":ti(e)&&(i.innerHTML=e.__html);return;case"value":if(e==null||i instanceof window.HTMLSelectElement)return;if(i instanceof window.HTMLTextAreaElement){i.value=e;return}break;case"spellCheck":i.spellcheck=e;return;case"class":case"className":Xi(e)?e(i):wi(i,"class",ys(e));return;case"ref":case"namespaceURI":return;case"style":ja(i,e);return;case"on":case"onCapture":ms(e,(n,r)=>{i.addEventListener(r,n,t==="onCapture")});return}if(Xi(e)){if(t[0]==="o"&&t[1]==="n"){let n=t.toLowerCase();const r=n.endsWith("capture");if(n==="ondoubleclick"?n="ondblclick":r&&n==="ondoubleclickcapture"&&(n="ondblclickcapture"),!r&&i[n]===null)i[n]=e;else if(r)i.addEventListener(n.substring(2,n.length-7),e,!0);else{let s;n in window?s=n.substring(2):s=n[2]+t.slice(3),i.addEventListener(s,e)}}}else ti(e)?i[t]=e:e===!0?wi(i,t,""):e!==!1&&e!=null&&(i instanceof SVGElement&&!Qd.test(t)?wi(i,Gn(t,"-"),e):wi(i,t,e))}function wi(t,e,i){t.setAttribute(e,i)}function Ua(t,e,i,n){t.setAttributeNS(e,i,n)}function eh(t,e){for(const i of Kn(t))Zd(i,t[i],e);return e}const Yn=Object.keys;function th(t){return typeof t=="boolean"}function ih(t){return t&&typeof t.nodeType=="number"}function ws(t){return typeof t=="string"}function Fa(t){return typeof t=="number"}function ii(t){return typeof t=="object"?t!==null:en(t)}function en(t){return typeof t=="function"}function nh(t){return!!(t&&t.isComponent)}function rh(t){return ii(t)&&typeof t.length=="number"&&typeof t.nodeType!="number"}function _s(t,e){if(t)for(const i of Yn(t))e(t[i],i)}function sh(t){return ii(t)&&"current"in t}const xs={animationIterationCount:0,borderImageOutset:0,borderImageSlice:0,borderImageWidth:0,boxFlex:0,boxFlexGroup:0,boxOrdinalGroup:0,columnCount:0,columns:0,flex:0,flexGrow:0,flexPositive:0,flexShrink:0,flexNegative:0,flexOrder:0,gridArea:0,gridRow:0,gridRowEnd:0,gridRowSpan:0,gridRowStart:0,gridColumn:0,gridColumnEnd:0,gridColumnSpan:0,gridColumnStart:0,fontWeight:0,lineClamp:0,lineHeight:0,opacity:0,order:0,orphans:0,tabSize:0,widows:0,zIndex:0,zoom:0,fillOpacity:0,floodOpacity:0,stopOpacity:0,strokeDasharray:0,strokeDashoffset:0,strokeMiterlimit:0,strokeOpacity:0,strokeWidth:0};function oh(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)}const ah=["Webkit","ms","Moz","O"];Yn(xs).forEach(t=>{ah.forEach(e=>{xs[oh(e,t)]=0})});const lh=Symbol.for("jsx-dom:type");var Ba=(function(t){return t.ShadowRoot="ShadowRoot",t})(Ba||{});function ch(t){return t!=null&&t[lh]===Ba.ShadowRoot}const uh="http://www.w3.org/2000/svg",fh="http://www.w3.org/1999/xlink",dh="http://www.w3.org/XML/1998/namespace";function qa(t){return!th(t)&&t!=null}function Ss(t){return Array.isArray(t)?t.map(Ss).filter(Boolean).join(" "):ii(t)?Symbol.iterator in t?Ss(Array.from(t)):Yn(t).filter(e=>t[e]).join(" "):qa(t)?""+t:""}const hh={animate:0,circle:0,clipPath:0,defs:0,desc:0,ellipse:0,feBlend:0,feColorMatrix:0,feComponentTransfer:0,feComposite:0,feConvolveMatrix:0,feDiffuseLighting:0,feDisplacementMap:0,feDistantLight:0,feFlood:0,feFuncA:0,feFuncB:0,feFuncG:0,feFuncR:0,feGaussianBlur:0,feImage:0,feMerge:0,feMergeNode:0,feMorphology:0,feOffset:0,fePointLight:0,feSpecularLighting:0,feSpotLight:0,feTile:0,feTurbulence:0,filter:0,foreignObject:0,g:0,image:0,line:0,linearGradient:0,marker:0,mask:0,metadata:0,path:0,pattern:0,polygon:0,polyline:0,radialGradient:0,rect:0,stop:0,svg:0,switch:0,symbol:0,text:0,textPath:0,tspan:0,use:0,view:0},ph=/^(a(ll|t|u)|base[FP]|c(al|lipPathU|on)|di|ed|ex|filter[RU]|g(lyphR|r)|ke|l(en|im)|ma(rker[HUW]|s)|n|pat|pr|point[^e]|re[^n]|s[puy]|st[^or]|ta|textL|vi|xC|y|z)/;function mh(t){const e=document.createDocumentFragment();return Qn(t.children,e),e}function gh(t,e,i){e={...e,children:i};const n=new t(e),r=n.render();return"ref"in e&&ks(e.ref,n),r}function ye(t,e){let{children:i,...n}=e;!n.namespaceURI&&hh[t]===0&&(n={...n,namespaceURI:uh});let r;if(ws(t)){if(r=n.namespaceURI?document.createElementNS(n.namespaceURI,t):document.createElement(t),vh(n,r),Qn(i,r),r instanceof window.HTMLSelectElement&&n.value!=null)if(n.multiple===!0&&Array.isArray(n.value)){const s=n.value.map(o=>String(o));r.querySelectorAll("option").forEach(o=>o.selected=s.includes(o.value))}else r.value=n.value;ks(n.ref,r)}else if(en(t))ii(t.defaultProps)&&(n={...t.defaultProps,...n}),r=nh(t)?gh(t,n,i):t({...n,children:i});else throw new TypeError(`Invalid JSX element type: ${t}`);return r}function ks(t,e){sh(t)?t.current=e:en(t)&&t(e)}function Qn(t,e){if(rh(t))yh(t,e);else if(ws(t)||Fa(t))Es(document.createTextNode(t),e);else if(t===null)Es(document.createComment(""),e);else if(ih(t))Es(t,e);else if(ch(t)){const i=e.attachShadow(t.attr);Qn(t.children,i),ks(t.ref,i)}}function yh(t,e){for(const i of[...t])Qn(i,e);return e}function Es(t,e){e instanceof window.HTMLTemplateElement?e.content.appendChild(t):e.appendChild(t)}function Jn(t,e){return t.replace(/[A-Z]/g,i=>e+i.toLowerCase())}function Ha(t,e){e==null||e===!1||(Array.isArray(e)?e.forEach(i=>Ha(t,i)):ws(e)?t.setAttribute("style",e):ii(e)&&_s(e,(i,n)=>{n.indexOf("-")===0?t.style.setProperty(n,i):Fa(i)&&xs[n]!==0?t.style[n]=i+"px":t.style[n]=i}))}function bh(t,e,i){switch(t){case"xlinkActuate":case"xlinkArcrole":case"xlinkHref":case"xlinkRole":case"xlinkShow":case"xlinkTitle":case"xlinkType":za(i,fh,Jn(t,":"),e);return;case"xmlnsXlink":_i(i,Jn(t,":"),e);return;case"xmlBase":case"xmlLang":case"xmlSpace":za(i,dh,Jn(t,":"),e);return}switch(t){case"htmlFor":_i(i,"for",e);return;case"dataset":_s(e,(n,r)=>{n!=null&&(i.dataset[r]=n)});return;case"innerHTML":case"innerText":case"textContent":qa(e)&&(i[t]=e);return;case"dangerouslySetInnerHTML":ii(e)&&(i.innerHTML=e.__html);return;case"value":if(e==null||i instanceof window.HTMLSelectElement)return;if(i instanceof window.HTMLTextAreaElement){i.value=e;return}break;case"spellCheck":i.spellcheck=e;return;case"class":case"className":en(e)?e(i):_i(i,"class",Ss(e));return;case"ref":case"namespaceURI":return;case"style":Ha(i,e);return;case"on":case"onCapture":_s(e,(n,r)=>{i.addEventListener(r,n,t==="onCapture")});return}if(en(e)){if(t[0]==="o"&&t[1]==="n"){let n=t.toLowerCase();const r=n.endsWith("capture");if(n==="ondoubleclick"?n="ondblclick":r&&n==="ondoubleclickcapture"&&(n="ondblclickcapture"),!r&&i[n]===null)i[n]=e;else if(r)i.addEventListener(n.substring(2,n.length-7),e,!0);else{let s;n in window?s=n.substring(2):s=n[2]+t.slice(3),i.addEventListener(s,e)}}}else ii(e)?i[t]=e:e===!0?_i(i,t,""):e!==!1&&e!=null&&(i instanceof SVGElement&&!ph.test(t)?_i(i,Jn(t,"-"),e):_i(i,t,e))}function _i(t,e,i){t.setAttribute(e,i)}function za(t,e,i,n){t.setAttributeNS(e,i,n)}function vh(t,e){for(const i of Yn(t))bh(i,t[i],e);return e}var $s=(t=>(t.Init="modal.init",t.BeforeShow="modal.beforeShow",t.Show="modal.show",t.BeforeClose="modal.beforeClose",t.Close="modal.close",t.Destroy="modal.destroy",t.ToastShow="toast.show",t.ToastClose="toast.close",t))($s||{});let wh=0;const Ka=t=>`${t}-${++wh}`;function tn(t){return t instanceof Node?t:document.createTextNode(String(t))}function Tt(t,e){if(!t)throw new Error(`${e??"Element"} not found`);return t}function Wa(t){const e=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(t.querySelectorAll(e)).filter(i=>!!(i.offsetWidth||i.offsetHeight||i.getClientRects().length))}function Ne(t,e={}){const i=document.createElement(t);if(e.className&&(i.className=e.className),e.html!=null&&(i.innerHTML=e.html),e.text!=null&&(i.textContent=e.text),e.attrs)for(const[n,r]of Object.entries(e.attrs))i.setAttribute(n,r);return i}const _h=typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform),Va=["ctrl","alt","shift","meta"];function xh(t){if(!t)return null;const e=String(t).trim().toLowerCase().split(/[+\-\s]+/g).filter(Boolean),i=[];let n=null;const r=o=>{i.includes(o)||i.push(o)};for(const o of e){let a=o;if(a==="control"||a==="ctrl"){r("ctrl");continue}if(a==="alt"||a==="option"){r("alt");continue}if(a==="shift"){r("shift");continue}if(a==="meta"||a==="cmd"||a==="command"||a==="super"){r("meta");continue}if(a==="mod"){r(_h?"meta":"ctrl");continue}a==="esc"&&(a="escape"),a==="return"&&(a="enter"),(a==="space"||a==="spacebar")&&(a="space"),n=a}const s=Va.filter(o=>i.includes(o));return!n||n===""?s.length?s.join("+"):null:s.length?`${s.join("+")}+${n}`:n}function Sh(t){const e=[];t.ctrlKey&&e.push("ctrl"),t.altKey&&e.push("alt"),t.shiftKey&&e.push("shift"),t.metaKey&&e.push("meta");let i=t.key;i===" "&&(i="space");const n=(i.length,i.toLowerCase()),r=Va.filter(s=>e.includes(s));return r.length?`${r.join("+")}+${n}`:n}class kh{constructor(){this.zBase=1e3,this.stack=[]}push(e){this.stack.push(e),this.syncZ()}remove(e){this.stack=this.stack.filter(i=>i!==e),this.syncZ()}top(){return this.stack[this.stack.length-1]}closeAll(e,i){const n=new Set((Array.isArray(i)?i:i?[i]:[]).map(String)),r=new Set((Array.isArray(e)?e:e?[e]:[]).map(String));[...this.stack].reverse().forEach(s=>{const o=s.modalId,a=r.size?r.has(s.pluginName):!0,l=n.has(o);a&&!l&&s.close()})}removeAll(){[...this.stack].forEach(e=>e.destroy()),this.stack=[]}syncZ(){this.stack.forEach((e,i)=>e.setZIndex(this.zBase+i*2))}lockBodyScroll(){document.body.classList.add("ipe-modal-no-scroll")}unlockBodyScroll(){document.body.classList.remove("ipe-modal-no-scroll")}}const ze=new kh,Cn=class Cn{constructor(e={}){this.backdropId=Ka("ipe-modal-backdrop"),this.modalId=Ka("ipe-modal"),this.numberId=this.modalId.split("-")[1],this._isDestroyed=!1,this.pluginName="normalModal",this.buttonElsLeft=[],this.buttonElsRight=[],this.keyMap=new Map,this.isOpen=!1,this.isToast=!1,this.isDragging=!1,this.dragStartX=0,this.dragStartY=0,this.modalStartX=0,this.modalStartY=0,this.Event=$s,this._hooks=[],this.startCloseTimer=i=>{this.stopCloseTimer(),this.closeTimer=window.setTimeout(()=>this.close(),i)},this.stopCloseTimer=()=>{this.closeTimer&&window.clearTimeout(this.closeTimer),this.closeTimer=void 0},this.onDragMove=i=>{if(!this.isDragging)return;i.preventDefault();const n=i.clientX-this.dragStartX,r=i.clientY-this.dragStartY,s=this.get$modal(),o=this.modalStartX+n,a=this.modalStartY+r;s.style.left=`${o}px`,s.style.top=`${a}px`},this.onDragEnd=()=>{if(!this.isDragging)return;this.isDragging=!1,document.removeEventListener("pointermove",this.onDragMove),document.removeEventListener("pointerup",this.onDragEnd);const i=this.get$modal(),n=this.get$window();i.classList.remove("is-dragging"),n.style.animation="none",requestAnimationFrame(()=>{this.applyAnimation(!0)})},this.options={...Cn.DEFAULT_OPTIONS,...e},this.options.backdrop===!1&&e.bodyScroll===void 0&&(this.options.bodyScroll=!0)}get isDestroyed(){return this._isDestroyed}static extends(e={}){return class extends this{constructor(i={}){super({...e,...i})}}}init(){if(this.$modal)return this;const e=this.options.backdrop!==!1;let i;e&&(i=Ne("div",{className:"ipe-modal-backdrop",attrs:{id:this.backdropId,"data-modal-id":this.modalId}}));const n=Ne("div",{className:"ipe-modal-modal",attrs:{id:this.modalId,role:"dialog","aria-modal":"true",tabindex:"-1"}});if(n.modal=this,!e){n.classList.add("no-backdrop");const p=window.pageYOffset||document.documentElement.scrollTop,f=window.pageXOffset||document.documentElement.scrollLeft,_=window.innerWidth;n.style.top=`${p+60}px`,this.once("modal.show",()=>{n.style.left=`${f+_/2-n.offsetWidth/2}px`})}const r=Ne("div",{className:`ipe-modal-modal__window size--${this.options.sizeClass||"auto"} plugin--${this.pluginName}`});r.modal=this;const s=Ne("div",{className:"ipe-modal-modal__header"}),o=`${this.modalId}-title`,a=Ne("h2",{className:"ipe-modal-modal__title",attrs:{id:o,role:"heading","aria-level":"2"}});n.setAttribute("aria-labelledby",o);const l=Ne("div",{className:"ipe-modal-modal__icons"});if(this.options.closeIcon){const p=Ne("button",{className:"ipe-modal-modal__close",attrs:{type:"button","aria-label":"Close"},html:"×"});p.addEventListener("click",()=>{let f=!0;typeof this.options.onClickClose=="function"?this.options.onClickClose(this)===!1&&(f=!1):this.options.onClickClose===!1&&(f=!1),f&&this.close()}),l.appendChild(p)}s.append(a,l),this.options.draggable&&e&&(this.options.draggable=!1),this.options.draggable&&(s.style.cursor="move",s.style.userSelect="none",s.addEventListener("pointerdown",this.onDragStart.bind(this)),n.classList.add("is-draggable"));const c=Ne("div",{className:"ipe-modal-modal__content"}),u=Ne("div",{className:"ipe-modal-modal__footer"}),d=Ne("div",{className:"ipe-modal-modal__buttons ipe-modal-modal__buttons--left"}),h=Ne("div",{className:"ipe-modal-modal__buttons ipe-modal-modal__buttons--right"});return u.append(d,h),r.append(s,c,u),n.appendChild(r),this.$backdrop=i,this.$modal=n,this.$window=r,this.$header=s,this.$title=a,this.$icons=l,this.$content=c,this.$footer=u,this.$buttonsLeft=d,this.$buttonsRight=h,this.options.title&&this.setTitle(this.options.title),this.options.content&&this.setContent(this.options.content),this.options.buttons?.length?this.setButtons(this.options.buttons):u.style.display="none",this.options.center&&this.$modal.classList.add("is-centered"),this.options.fitScreen&&this.$modal.classList.add("is-fullscreen"),this.options.iconButtons&&this.$header.classList.add("has-icon-buttons"),this.options.className&&this.$window.classList.add(...this.options.className.split(/[\s\.#+]+/g).filter(Boolean)),typeof this.options.fixedHeight=="number"?this.$window.style.height=`${Math.max(0,this.options.fixedHeight)}px`:this.options.fixedHeight===!0&&this.$window.classList.add("is-fixed-height"),i&&i.addEventListener("pointerdown",p=>{this.options.outSideClose&&p.target===i&&this.close()}),this.options.draggable&&r.addEventListener("pointerdown",p=>{p.target&&r.contains(p.target)&&this.bringToFront()}),this.onKeyDown=this.onKeyDown.bind(this),this.emit("modal.init"),this}show(){if(this.$modal||this.init(),!this.$modal)throw new Error("Failed to initialize modal");if(this.isOpen)return this;{const n=this.emit("modal.beforeShow",!0),r=this.options.beforeShow?this.options.beforeShow(this)!==!1:!0;if(!n||!r)return this}this.lastFocused=document.activeElement??null,this.$backdrop&&document.body.appendChild(this.$backdrop),document.body.appendChild(this.$modal),this.shouldLockBodyOnOpen()&&ze.lockBodyScroll(),requestAnimationFrame(()=>{this.$backdrop?.classList.add("is-open"),this.$modal.classList.add("is-open"),this.applyAnimation(!0),this.focusFirst()}),document.addEventListener("keydown",this.onKeyDown),ze.push(this),this.isOpen=!0,this.options.onShow?.(this),this.emit("modal.show");const e=typeof this.options.closeAfter=="number"?this.options.closeAfter:this.options.closeAfter?.time,i=typeof this.options.closeAfter=="number"?!0:this.options.closeAfter?.resetOnHover;return e&&(this.startCloseTimer(e),i&&(this.$window?.addEventListener("mouseenter",this.stopCloseTimer),this.$window?.addEventListener("mouseleave",()=>this.startCloseTimer(e)))),this}close(){if(!this.isOpen)return this;{const s=this.emit("modal.beforeClose",!0),o=this.options.beforeClose?this.options.beforeClose(this)!==!1:!0;if(!s||!o)return this}if(this.isToast){this.applyAnimation(!1),this.emit("modal.close"),this.emit("toast.close");const s=this.isAnimationDisabled()?0:this.options.animationSpeed??200;let o=!1;const a=()=>{o||(o=!0,this.destroy(),this.options.onClose?.(this))},l=(c,u)=>{const d=()=>{c.removeEventListener(u,d),a()};c.addEventListener(u,d,{once:!0})};return s>0&&this.$window?(l(this.$window,"transitionend"),l(this.$window,"animationend"),window.setTimeout(a,s+20)):window.setTimeout(a,s),this}this.applyAnimation(!1),this.$backdrop?.classList.remove("is-open"),this.$modal?.classList.remove("is-open"),this.emit("modal.close");const e=this.isAnimationDisabled()?0:this.options.animationSpeed??200;let i=!1;const n=()=>{i||(i=!0,this.destroy(),this.options.onClose?.(this))},r=(s,o)=>{const a=()=>{s.removeEventListener(o,a),n()};s.addEventListener(o,a,{once:!0})};return e>0&&this.$window?(r(this.$window,"transitionend"),r(this.$window,"animationend"),window.setTimeout(n,e+20)):window.setTimeout(n,e),this}destroy(){if(this._isDestroyed)return this;if(this.stopCloseTimer(),document.removeEventListener("keydown",this.onKeyDown),this.isDragging&&this.onDragEnd(),this.$window?.removeEventListener("mouseenter",this.stopCloseTimer),this.isToast){this.$window?.parentElement&&this.$window.parentElement.removeChild(this.$window);const e=ni.indexOf(this);e!==-1&&ni.splice(e,1)}else this.$backdrop?.parentElement&&this.$backdrop.parentElement.removeChild(this.$backdrop),this.$modal?.parentElement&&this.$modal.parentElement.removeChild(this.$modal),ze.remove(this),this.shouldUnlockBodyOnClose()&&ze.unlockBodyScroll();return this.isOpen=!1,this.lastFocused?.focus?.(),this.emit("modal.destroy"),this._isDestroyed=!0,this}get$backdrop(){return this.$backdrop}get$modal(){return Tt(this.$modal,"modal")}get$window(){return Tt(this.$window,"window")}get$header(){return Tt(this.$header,"header")}get$title(){return Tt(this.$title,"title")}get$content(){return Tt(this.$content,"content")}get$icons(){return Tt(this.$icons,"icons")}get$buttons(e){return e==="leftButtons"?Tt(this.$buttonsLeft,"leftButtons"):e==="rightButtons"?Tt(this.$buttonsRight,"rightButtons"):Tt(this.$footer,"buttons")}setTitle(e){const i=this.get$title();return i.innerHTML="",i.append(tn(e)),this}setContent(e,i="replace"){const n=this.get$content();return i==="replace"?(n.innerHTML="",n.append(tn(e))):i==="append"?n.append(tn(e)):n.prepend(tn(e)),this}setIcons(e){const i=this.get$icons();i.innerHTML="";for(const n of e){const r=Ne("button",{className:`ipe-modal-modal__icon ${n.className}`,attrs:{type:"button"}});r.addEventListener("click",n.method),i.appendChild(r)}return this}setButtons(e,i){const n=this.$buttonsLeft,r=this.$buttonsRight;[n,r].forEach(o=>o.innerHTML=""),this.buttonElsLeft=[],this.buttonElsRight=[],this.keyMap.clear();const s=i??this.$footer;if(s===this.$footer)e.forEach(o=>this.addButton(o)),e.length===0&&(this.$footer.style.display="none");else{s.innerHTML="";for(const o of e){const a=this.generateButton(o);s.appendChild(a)}}return this}generateButton(e){const i=e.type??"button",n=i==="link"?Ne("a"):Ne("button",{attrs:{type:"button"}});e.id&&(n.id=e.id),n.className=`ipe-modal-btn ${e.className??""}`.trim();const r=tn(e.label??"OK");if(n.append(r),i==="link"&&e.href&&(n.href=e.href),e.method&&n.addEventListener("click",s=>{if(n._ipe_tmpDisabled){s.preventDefault(),s.stopPropagation();return}e.method.call(n,s,this)}),typeof e.closeAfter=="number"&&e.closeAfter>=0&&n.addEventListener("click",()=>{window.setTimeout(()=>this.close(),e.closeAfter)}),typeof e.enableAfter=="number"&&e.enableAfter>0){i==="button"&&n.setAttribute("disabled","true"),n._ipe_tmpDisabled=!0,n.setAttribute("aria-disabled","true");const s=()=>{i==="button"&&n.removeAttribute("disabled"),delete n._ipe_tmpDisabled,n.removeAttribute("aria-disabled")};window.setTimeout(s,e.enableAfter)}if(e.keyPress){const s=String(e.keyPress).split(/[\,\|]+/g).map(o=>o.trim()).filter(Boolean);for(const o of s){const a=xh(o);a&&this.keyMap.set(a,n)}}return n}addButton(e,i){this.$footer&&(this.$footer.style.display="");const n=e.side??"right",r=n==="left"?this.$buttonsLeft:this.$buttonsRight,s=n==="left"?this.buttonElsLeft:this.buttonElsRight,o=this.generateButton(e),a=Math.max(0,Math.min(i??s.length,s.length));return a>=r.children.length?r.appendChild(o):r.insertBefore(o,r.children[a]),s.splice(a,0,o),this}removeButton(e){const i=this.buttonElsLeft,n=this.buttonElsRight,r=[...i,...n];let s=null;if(e==="*")return r.forEach(a=>{this.keyMap.delete(a.id),a.parentElement?.removeChild(a)}),this.$footer&&(this.$footer.style.display="none"),this;if(typeof e=="number"?s=r[e]??null:typeof e=="string"?s=r.find(a=>a.id===e)??null:e instanceof HTMLElement&&(s=r.find(a=>a===e)??null),!s)return this;for(const[a,l]of this.keyMap.entries())l===s&&this.keyMap.delete(a);let o=i.indexOf(s);return o!==-1?(i.splice(o,1),s.parentElement?.removeChild(s)):(o=n.indexOf(s),o!==-1&&(n.splice(o,1),s.parentElement?.removeChild(s))),i.length===0&&n.length===0&&this.$footer&&(this.$footer.style.display="none"),this}changePreviewState(){return this.get$modal().classList.toggle("is-fullscreen"),this}setModalHeight(e,i="height"){const n=this.get$window(),r=Math.max(0,window.innerHeight-e);return n.style[i]=`${r}px`,r}setOptions(e,i){return typeof e=="string"?this.options[e]=i:Object.assign(this.options,e),this}setPluginName(e){return this.$window&&(this.$window.className=this.$window.className.replace(`plugin--${this.pluginName}`,`plugin--${e}`)),this.pluginName=e,this}applyAnimation(e){const i=this.get$modal(),n=this.get$window(),r=this.$backdrop,s=this.options.modalAnimation??this.options.animation,o=typeof s=="string"?s:s&&(e?s.show:s.hide),a=this.options.backdropAnimation??this.options.animation,l=typeof a=="string"?a:a&&(e?a.show:a.hide);!o||o===!1?(i.style.transition="none",n.style.animation="none",n.style.removeProperty("--ipe-modal-anim")):(i.style.removeProperty("transition"),n.style.setProperty("--ipe-modal-anim",o)),r&&(!l||l===!1?r.style.transition="none":r.style.removeProperty("transition"))}on(e,i){return this._hooks.push({type:e,listener:i}),()=>this.off(e,i)}off(e,i){return this._hooks=this._hooks.filter(n=>n.type!==e&&(i?n.listener!==i:!0)),this}once(e,i){const n=this.on(e,r=>(n(),i(r)));return n}emit(e,i){const n=this._hooks.filter(a=>a.type===e);let r=!0;for(const a of n){const l=new CustomEvent(e,{detail:this,cancelable:i}),c=a.listener(l);if(l.defaultPrevented&&(r=!1),c===!1&&(r=!1),!r)break}const s=this.$modal??document.body,o=new CustomEvent(e,{detail:this,cancelable:i});return(!s.dispatchEvent(o)||o.defaultPrevented)&&(r=!1),r}focusFirst(){const e=this.get$modal(),i=Wa(e);i.length?i[0].focus():e.focus({preventScroll:!0})}onKeyDown(e){if(ze.top()!==this)return;if(e.key==="Escape"){e.preventDefault(),this.close();return}const i=this.get$modal();if(!i.contains(document.activeElement))return;if(e.key==="Tab"){const a=Wa(i);if(!a.length)return;const l=a[0],c=a[a.length-1],u=document.activeElement;e.shiftKey&&u===l?(e.preventDefault(),c.focus()):!e.shiftKey&&u===c&&(e.preventDefault(),l.focus())}const n=e.ctrlKey||e.altKey||e.metaKey,r=e.target;if(!n&&(r&&["INPUT","TEXTAREA"].includes(r.tagName)||r.contentEditable==="true"))return;const s=Sh(e),o=this.keyMap.get(s);if(o){e.preventDefault(),o.click();return}}setZIndex(e){this.$backdrop&&(this.$backdrop.style.zIndex=String(e)),this.$modal&&(this.$modal.style.zIndex=String(e+1))}bringToFront(){return ze.remove(this),ze.push(this),this}isAnimationDisabled(){const e=this.options.modalAnimation??this.options.animation;return e===!1||e==null}shouldLockBodyOnOpen(){return this.options.backdrop===!1||this.options.bodyScroll!==!1?!1:!ze.stack.some(e=>e!==this&&e.options.backdrop!==!1&&e.options.bodyScroll===!1)}shouldUnlockBodyOnClose(){return this.options.backdrop===!1||this.options.bodyScroll!==!1?!1:!ze.stack.some(e=>e!==this&&e.options.backdrop!==!1&&e.options.bodyScroll===!1)}onDragStart(e){if(this.options.backdrop!==!1||!this.options.draggable)return;e.preventDefault(),this.isDragging=!0,this.bringToFront(),this.dragStartX=e.clientX,this.dragStartY=e.clientY;const i=this.get$modal(),n=i.getBoundingClientRect();this.modalStartX=n.left+window.pageXOffset,this.modalStartY=n.top+window.pageYOffset,i.style.transform="none",i.style.left=`${this.modalStartX}px`,i.style.top=`${this.modalStartY}px`,document.addEventListener("pointermove",this.onDragMove),document.addEventListener("pointerup",this.onDragEnd),i.classList.add("is-dragging")}showToast(e){this.$window||this.init();const i=Eh(e.position??"top right"),n=this.get$window();this.isToast=!0,n.style.pointerEvents="auto",this.applyAnimation(!0),i.appendChild(n);const r=(typeof this.options.closeAfter=="number"?this.options.closeAfter:this.options.closeAfter?.time)??3e3,s=(typeof this.options.closeAfter=="number"?!0:this.options.closeAfter?.resetOnHover)??!0;return r>0&&(this.startCloseTimer(r),s&&(n.addEventListener("mouseenter",this.stopCloseTimer),n.addEventListener("mouseleave",()=>this.startCloseTimer(r)))),this.isOpen=!0,this.options.onShow?.(this),ni.push(this),this.emit("toast.show"),this.emit("modal.show"),this}static show(e,i){return new this(e).init().show()}static createObject(e,i){return new this(e)}static close(e){if(!e){const s=ze.top();return s?.close(),s}const i=typeof e=="string"?e:e.id,n=ze.stack.find(s=>s.modalId===i);if(n)return n.close(),n;const r=ni.find(s=>s.modalId===i);return r?.close(),r}static closeAll(e,i){const n=new Set((Array.isArray(i)?i:i?[i]:[]).map(String)),r=new Set((Array.isArray(e)?e:e?[e]:[]).map(String));return ze.closeAll(e,i),[...ni].forEach(s=>{const o=s.modalId,a=r.size?r.has(s.pluginName):!0,l=n.has(o);a&&!l&&s.close()}),ze.top()??new Cn}static removeAll(){ze.removeAll(),[...ni].forEach(e=>e.destroy())}static dialog(e,i){const n=new this({sizeClass:"dialog",buttons:[{label:"OK",className:"is-primary is-ghost",method:(r,s)=>{i?.(r,s),r.defaultPrevented||n.close()},keyPress:"Enter"}],...e});return n.init().show()}static confirm(e,i){e.title??(e.title="Confirm"),e.content??(e.content="Are you sure you want to perform this action?");const n=e.okBtn??{label:"OK",className:"is-primary is-ghost"},r=e.cancelBtn??{label:"Cancel",className:"is-danger is-ghost"};return new this({sizeClass:"dialog",...e,buttons:[{label:r.label,className:r.className,keyPress:"n",method:(s,o)=>{i?.(!1,o,s),o.close()}},{label:n.label,className:n.className,keyPress:"y",method:(s,o)=>{i?.(!0,o,s),s.defaultPrevented||o.close()}}]}).init().show()}static getDefaultNotifyIcon(e){switch(e){case"success":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-circle-check",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M17 3.34a10 10 0 1 1 -14.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 14.995 -8.336zm-1.293 5.953a1 1 0 0 0 -1.32 -.083l-.094 .083l-3.293 3.292l-1.293 -1.292l-.094 -.083a1 1 0 0 0 -1.403 1.403l.083 .094l2 2l.094 .083a1 1 0 0 0 1.226 0l.094 -.083l4 -4l.083 -.094a1 1 0 0 0 -.083 -1.32z"})]});case"error":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-alert-triangle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 1.67c.955 0 1.845 .467 2.39 1.247l.105 .16l8.114 13.548a2.914 2.914 0 0 1 -2.307 4.363l-.195 .008h-16.225a2.914 2.914 0 0 1 -2.582 -4.2l.099 -.185l8.11 -13.538a2.914 2.914 0 0 1 2.491 -1.403zm.01 13.33l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007zm-.01 -7a1 1 0 0 0 -.993 .883l-.007 .117v4l.007 .117a1 1 0 0 0 1.986 0l.007 -.117v-4l-.007 -.117a1 1 0 0 0 -.993 -.883z"})]});case"warning":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-alert-circle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 2c5.523 0 10 4.477 10 10a10 10 0 0 1 -19.995 .324l-.005 -.324l.004 -.28c.148 -5.393 4.566 -9.72 9.996 -9.72zm.01 13l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007zm-.01 -8a1 1 0 0 0 -.993 .883l-.007 .117v4l.007 .117a1 1 0 0 0 1.986 0l.007 -.117v-4l-.007 -.117a1 1 0 0 0 -.993 -.883z"})]});case"info":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-info-circle",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 2c5.523 0 10 4.477 10 10a10 10 0 0 1 -19.995 .324l-.005 -.324l.004 -.28c.148 -5.393 4.566 -9.72 9.996 -9.72zm0 9h-1l-.117 .007a1 1 0 0 0 0 1.986l.117 .007v3l.007 .117a1 1 0 0 0 .876 .876l.117 .007h1l.117 -.007a1 1 0 0 0 .876 -.876l.007 -.117l-.007 -.117a1 1 0 0 0 -.764 -.857l-.112 -.02l-.117 -.006v-3l-.007 -.117a1 1 0 0 0 -.876 -.876l-.117 -.007zm.01 -3l-.127 .007a1 1 0 0 0 0 1.986l.117 .007l.127 -.007a1 1 0 0 0 0 -1.986l-.117 -.007z"})]});case"dialog":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"icon icon-tabler icons-tabler-outline icon-tabler-message-dots",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M12 11v.01"}),ye("path",{d:"M8 11v.01"}),ye("path",{d:"M16 11v.01"}),ye("path",{d:"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3z"})]});case"confirm":return ye("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",class:"icon icon-tabler icons-tabler-filled icon-tabler-copy-check",children:[ye("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),ye("path",{d:"M18.333 6a3.667 3.667 0 0 1 3.667 3.667v8.666a3.667 3.667 0 0 1 -3.667 3.667h-8.666a3.667 3.667 0 0 1 -3.667 -3.667v-8.666a3.667 3.667 0 0 1 3.667 -3.667zm-3.333 -4c1.094 0 1.828 .533 2.374 1.514a1 1 0 1 1 -1.748 .972c-.221 -.398 -.342 -.486 -.626 -.486h-10c-.548 0 -1 .452 -1 1v9.998c0 .32 .154 .618 .407 .805l.1 .065a1 1 0 1 1 -.99 1.738a3 3 0 0 1 -1.517 -2.606v-10c0 -1.652 1.348 -3 3 -3zm1.293 9.293l-3.293 3.292l-1.293 -1.292a1 1 0 0 0 -1.414 1.414l2 2a1 1 0 0 0 1.414 0l4 -4a1 1 0 0 0 -1.414 -1.414"})]});default:return null}}static notify(e,i,n){var a,l,c,u;if(i?.overrideOther&&[...ni].forEach(d=>d.close()),typeof i.title>"u"){const d=e||"Notification";i.title=d[0].toUpperCase()+d.slice(1).toLowerCase()}const r=i.icon??this.getDefaultNotifyIcon(e);r&&(r instanceof Element&&r.classList.add("ipe-modal-notify-icon"),i.title=ye(mh,{children:[r,i.title]})),e==="confirm"&&(typeof i.closeAfter>"u"&&(i.closeAfter=0),i.okBtn||(i.okBtn={label:"OK"})),i.okBtn&&(typeof i.okBtn!="object"&&(i.okBtn={label:"OK"}),(a=i.okBtn).label??(a.label="OK"),(l=i.okBtn).className??(l.className="is-primary is-text ok-btn"),i.okBtn.method=(d,h)=>{n?.(!0,h,d),h.close()}),i.cancelBtn&&(typeof i.cancelBtn!="object"&&(i.cancelBtn={label:"Cancel"}),(c=i.cancelBtn).label??(c.label="Cancel"),(u=i.cancelBtn).className??(u.className="is-danger is-text cancel-btn"),i.cancelBtn.method=(d,h)=>{n?.(!1,h,d),h.close()}),i.buttons=[i.cancelBtn,i.okBtn,...i.buttons??[]].filter(Boolean);const s=`is-notify type-${e||"default"} ${i.className??""}`,o=new this({...i,className:s,sizeClass:"auto",center:!1,fitScreen:!1,closeIcon:!0,outSideClose:!1,bodyScroll:!0,buttons:i.buttons??[]});return o.setPluginName("toast"),o.showToast({position:i.position??"top right"})}};Cn.DEFAULT_OPTIONS={className:"",sizeClass:"auto",center:!0,fitScreen:!1,closeIcon:!0,bodyScroll:!1,outSideClose:!0,backdrop:!0,animation:{show:"ipe-modal-fade-in",hide:"ipe-modal-fade-out"},animationSpeed:200};let Ps=Cn;const ni=[];function Eh(t="top right"){const e="ipe-modal-toast-container",i=`${e}-${t.replace(/[\s-\.|\/]+/g,"-")}`;let n=document.getElementById(i);return n||(n=Ne("div",{className:`${e} ${t}`,attrs:{id:i,"data-position":t}}),document.body.appendChild(n)),n}const $h={ipe_progress:"_ipe_progress_so6hn_1"},ri=t=>{const e=t.indeterminate??!0,i=m("div",{class:`${$h.ipe_progress}`,"data-indeterminate":`${e}`,style:{width:"100%","--progress":t.progress?`${t.progress}%`:"0%"},...t});return i.setProgress=n=>{typeof n=="number"?(i.dataset.indeterminate="false",i.style.setProperty("--progress",`${n}%`)):(i.dataset.indeterminate="true",i.style.setProperty("--progress","0%"))},i};class Pe extends Ps{constructor(e={}){e.className||(e.className=""),e.className+=" theme-ipe",e.modalAnimation||(e.modalAnimation={show:"ipe-modal-fade-in",hide:"ipe-modal-fade-out"}),super(e)}setLoadingState(e){if(this.get$window().classList.toggle("loading",e),e){const i=this.get$window().querySelectorAll("input:not([disabled]),button:not([disabled])");this._tmpDisabledActiveInputs=i,i.forEach(n=>{n.disabled=!0}),this.get$content().append(m("div",{id:"ipe-modalLoadingWrapper",style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"rgba(255, 255, 255, 0.5)",zIndex:2e3},children:m(ri,{style:{width:"80%",maxWidth:"800px"}})}))}else{this.get$window().querySelector("#ipe-modalLoadingWrapper")?.remove();const i=this._tmpDisabledActiveInputs;i&&i.forEach(n=>{n.disabled=!1})}}}class Ph{constructor(e){this.ctx=e,this.IPEModal=Pe,this.IPEModalEvent=$s,this.show=Pe.show.bind(Pe),this.createObject=Pe.createObject.bind(Pe),this.close=Pe.close.bind(Pe),this.closeAll=Pe.closeAll.bind(Pe),this.removeAll=Pe.removeAll.bind(Pe),this.dialog=Pe.dialog.bind(Pe),this.confirm=Pe.confirm.bind(Pe),this.notify=Pe.notify.bind(Pe),e.set("modal",this),e.on("dispose",()=>{Pe.closeAll()})}}const Ga=t=>{if(!t)return new URLSearchParams;if(t instanceof URLSearchParams)return t;if(typeof t!="object"||t?.constructor!==Object)throw new TypeError("only plain object is supported");const e=new URLSearchParams;for(const[i,n]of Object.entries(t))if(n!=null){if(Array.isArray(n)){for(const r of n)e.append(i,r?.toString());continue}if(typeof n=="object"&&n!==null&&n.constructor===Object){for(const[r,s]of Object.entries(n))s!=null&&e.set(`${i}[${r}]`,s?.toString());continue}e.set(i,n?.toString())}return e},Ya=(t,e,i)=>{const n=typeof t=="string"?new URL(t,window?.location?.origin):new URL(t),r=new URLSearchParams(n.search),s=Ga(e);for(const[o,a]of s.entries())r.set(o,a);return n.search=r.toString(),n.hash="",n};var Ch=Object.create,Cs=Object.defineProperty,Rh=Object.getOwnPropertyDescriptor,Qa=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ja=t=>{throw TypeError(t)},Ah=(t,e,i)=>e in t?Cs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ih=(t,e)=>Cs(t,"name",{value:e,configurable:!0}),Oh=t=>[,,,Ch(t?.[Qa("metadata")]??null)],Th=["class","method","getter","setter","accessor","field","value","get","set"],Xa=t=>t!==void 0&&typeof t!="function"?Ja("Function expected"):t,Lh=(t,e,i,n,r)=>({kind:Th[t],name:e,metadata:n,addInitializer:s=>i._?Ja("Already initialized"):r.push(Xa(s||null))}),Nh=(t,e)=>Ah(e,Qa("metadata"),t[3]),Mh=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},Dh=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Rh(r,i));Ih(r,i);for(var f=n.length-1;f>=0;f--)l=Lh(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,Xa(o)&&(r=o);return Nh(t,r),p&&Cs(r,i,p),u?c^4?s:p:r},Za,Rs,el;Za=[$e(["api","storage"])];class Xn extends(el=Ot){constructor(e){super(e,"wiki",!1),this.ctx=e,this._data={},this.CACHE_VERSION=3,this.CACHE_TTL={siteinfo:1e3*60*60*24*3,userinfo:1e3*60*30},this.QUERY_DATA={siteinfo:{meta:"siteinfo",siprop:"general|specialpagealiases|namespacealiases|namespaces|magicwords"},userinfo:{meta:"userinfo",uiprop:"groups|rights|blockinfo|options"}},this.CACHE_DB=void 0,this.mwConfig={get:((i,n)=>window?.mw?.config?.get?.(i,n)??n),has:(i=>window?.mw?.config?.exists?.(i)??!1),get values(){return window?.mw?.config?.values||{}}},this.CACHE_DB=e.storage.createDatabase("wiki-metadata",1/0,this.CACHE_VERSION)}get logger(){return this.ctx.logger("WIKI_METADATA")}get api(){return this.ctx.api}async start(){await Promise.all(Object.keys(this.QUERY_DATA).map(e=>this.initData(e))),this.ctx.set("getUrl",this.getUrl.bind(this)),this.ctx.set("getSciprtUrl",this.getSciprtUrl.bind(this)),this.ctx.set("getMainpageUrl",this.getMainpageUrl.bind(this)),this.ctx.inject(["preferences"],e=>{e.preferences.registerCustomConfig("WikiMetadataService",L.object({WikiMetadataService:L.const(m("div",{children:[m("h3",{children:"Wiki Informations"}),m("ul",{children:[m("li",{children:[m("strong",{children:"Site:"})," ",this.general.sitename," (",this.landingPageUrl,")"]}),m("li",{children:[m("strong",{children:"User"}),": ",this.userInfo.name," (ID: ",this.userInfo.id,")"]}),m("li",{children:[m("strong",{children:"Groups"}),": ",this.userGroups.join(", ")||"None"]})]}),m("div",{children:[m("p",{style:{fontStyle:"italic"},children:"If the information shown above is incorrect (for example, the user is not you), click the button below."}),m("button",{className:"btn danger",onClick:i=>{i.preventDefault(),Promise.all(Object.keys(this.QUERY_DATA).map(n=>this.invalidateCache(n))).then(()=>{window.location.reload()})},children:"🧹 Clear caches & Reload"})]})]})).role("raw-html")}).description("WikiMetadataService"),"about")}),this.logger.info("All initialized",this._data)}async initData(e,i=!1){const n=i?null:await this.fetchFromCache(e);if(n)return this._data[e]=n,this.logger.debug("Using cached",e,n),n;{const r=await this.fetchFromApi(e);return this.saveToCache(e,r),this._data[e]=r,this.logger.debug("Fetched from API",e,r),r}}getCacheKey(e){return`${e}:${new URL(this.ctx.api.config.baseURL).pathname.replace(/^\//,"")}`}async fetchFromApi(e){return this.api.get({action:"query",...this.QUERY_DATA[e]}).then(({data:i})=>{if(typeof i?.query!="object"||i.query===null)throw new Error("Invalid query data",{cause:i});return e==="siteinfo"?i.query:i.query?.[e]||i.query}).catch(i=>(this.logger.error("Failed to fetch",i),Promise.reject(i)))}async fetchFromCache(e){const i=this.getCacheKey(e);return await this.CACHE_DB.get(i,this.CACHE_TTL[e])}async saveToCache(e,i){const n=this.getCacheKey(e);return this.CACHE_DB.set(n,i)}async invalidateCache(e){const i=this.getCacheKey(e);return this.CACHE_DB.delete(i)}get _raw(){return this._data}get siteInfo(){return this._data.siteinfo}get general(){return this.siteInfo.general}get specialPageAliases(){return this.siteInfo.specialpagealiases}get namespaceAliases(){return this.siteInfo.namespacealiases}get namespaces(){return this.siteInfo.namespaces}get namespaceMap(){const e=Object.values(this.namespaces).map(i=>({id:i.id,canonical:i.canonical,aliases:this.namespaceAliases.filter(n=>n.id===i.id).map(n=>n.alias)})).sort((i,n)=>i.id-n.id);return Reflect.defineProperty(this,"namespaceMap",{get:()=>e}),e}get magicWords(){return this.siteInfo.magicwords}get userInfo(){return this._data.userinfo}get userOptions(){return this.userInfo.options}get isUserBlocked(){return this.userInfo.blockedbyid&&this.userInfo.blockexpiry&&new Date(this.userInfo.blockexpiry).getTime()>Date.now()}get userGroups(){return this.userInfo.groups}get userRights(){return this.userInfo.rights}get baseUrl(){const e=this.general.server;return e.startsWith("//")?`${window?.location?.protocol||"https:"}//${e.slice(2)}`:e}get landingPageUrl(){return this.general.base}get mainPageName(){return this.general.mainpage}get mainPageUrl(){return this.getUrl(this.mainPageName)}get articlePath(){return this.general.articlepath}get scriptPath(){return this.general.scriptpath}get articleBaseUrl(){return`${this.baseUrl}${this.articlePath}`}get scriptBaseUrl(){return`${this.baseUrl}${this.scriptPath}`}getSciprtUrl(e="index"){return`${this.scriptBaseUrl}/${e.replace(/\.php$/,"")}.php`}getMainpageUrl(e){return Ya(this.siteInfo.general.base,e).toString()}getUrl(e,i){const n=Ga(i);let r;return typeof e=="string"&&e!==""?r=new URL(`${this.articleBaseUrl.replace("$1",e)}`):typeof e=="number"?(n.set("curid",e.toString()),r=new URL(this.getSciprtUrl("index"))):r=new URL(this.getSciprtUrl("index")),r.search=n.toString(),r.toString()}hasRight(e){return this.userRights.includes(e)}hasAnyRight(...e){return e.some(i=>this.hasRight(i))}hasEveryRights(...e){return e.every(i=>this.hasRight(i))}inGroup(e){return this.userGroups.includes(e)}inAnyGroup(...e){return this.userGroups.some(i=>e.includes(i))}getBlockInfo(){return this.isUserBlocked?{blockid:this.userInfo.blockid,blockedby:this.userInfo.blockedbyid,blockedbyid:this.userInfo.blockedbyid,blockreason:this.userInfo.blockreason,blockedtimestamp:this.userInfo.blockedtimestamp,blockexpiry:this.userInfo.blockexpiry}:null}}Rs=Oh(el),Xn=Dh(Rs,0,"WikiMetadataService",Za,Xn),Mh(Rs,1,Xn);class jh{constructor(){this.values={}}get length(){return Object.keys(this.values).length}clear(){this.values={}}getItem(e){return this.values[e]??null}setItem(e,i){this.values[e]=typeof i=="string"?i:String(i)}removeItem(e){delete this.values[e]}key(e){return Object.keys(this.values)[e]??null}}const Uh=()=>new Proxy(new jh,{set(t,e,i){return typeof e=="string"&&t.setItem(e,i),!0},get(t,e){return typeof e=="string"&&!(e in t)?t.getItem(e):Reflect.get(t,e)}}),Fh=(()=>{const t=Symbol.for("IPE.GlobalMemoryStorage");return t in globalThis||(globalThis[t]=Uh()),globalThis[t]})();class Bh{constructor(e,i,n=1/0,r,s="localStorage"){this.dbName=e,this.storeName=i,this.ttl=n,this.version=r,this.engine=s,typeof n!="number"&&(this.ttl=Number(n)),(isNaN(this.ttl)||this.ttl<=0)&&(this.ttl=1/0),this.engine==="localStorage"&&"localStorage"in window?this.db=window.localStorage:this.engine==="sessionStorage"&&"sessionStorage"in window?this.db=window.sessionStorage:this.db=Fh}makeKey(e){return`${this.dbName?this.dbName+":":""}${this.storeName?this.storeName+"/":""}${e}`}load(e){const i=this.getRaw(e);if(i===null)return null;let n;try{n=JSON.parse(i)}catch{return this.deleteSync(e),null}const r=n;return typeof r.time!="number"||!("value"in r)?(this.deleteSync(e),null):typeof this.version=="number"&&r.version!==this.version?(this.deleteSync(e),null):r}getRaw(e){const i=this.makeKey(e);return this.db.getItem(i)}setRaw(e,i){const n=this.makeKey(e);try{this.db.setItem(n,i)}catch{}}deleteSync(e){const i=this.makeKey(e);this.db.removeItem(i)}isExpired(e,i=this.ttl){return e?Date.now()-e.time>i:!1}async get(e,i=this.ttl,n){const r=this.load(e),s=this.isExpired(r,i);if(!r||s){if(typeof n=="function"){const o=await n();return await this.set(e,o),o}return null}return r.value}async set(e,i){const n=Date.now();if(typeof e=="string"){const o=e,a=i;if(a===null||typeof a>"u"){await this.delete(o);return}const l={time:n,value:a,version:this.version};return this.setRaw(o,JSON.stringify(l)),l}const r=e,s={};for(const[o,a]of Object.entries(r)){if(a===null||typeof a>"u"){this.deleteSync(o);continue}const l={time:n,value:a,version:this.version};this.setRaw(o,JSON.stringify(l)),s[o]=l}return s}async has(e,i=this.ttl){const n=this.load(e);return n!==null&&!this.isExpired(n,i)}async delete(e){this.deleteSync(e)}async updatedAt(e){const i=this.load(e);return i?i.time:0}async clear(){const e=this.makeKey(""),i=[];for(let n=0;n<this.db.length;n++){const r=this.db.key(n);r&&r.startsWith(e)&&i.push(r)}for(const n of i)this.db.removeItem(n);return this}async*keys(){const e=this.makeKey("");for(let i=0;i<this.db.length;i++){const n=this.db.key(i);n&&n.startsWith(e)&&(yield n.slice(e.length))}}async*values(){for await(const e of this.keys()){const i=this.load(e);if(i){if(this.isExpired(i)){this.deleteSync(e);continue}yield i}}}async*entries(){for await(const e of this.keys()){const i=this.load(e);if(i){if(this.isExpired(i)){this.deleteSync(e);continue}yield[e,i]}}}}var we;(t=>{t.cache=new Map,t.defaults=Object.freeze({iterBatch:100,retry:{attempts:3,baseDelayMs:16}}),t.sleep=c=>new Promise(u=>setTimeout(u,c));function e(c){const u=c?.name??"";return u==="AbortError"||u==="InvalidStateError"||u==="TransactionInactiveError"||u==="UnknownError"}t.shouldReconnect=e;async function i(c,u,d){const h=Math.max(1,c.attempts);for(let p=0;p<h;p++)try{return await u(p)}catch(f){if(p===h-1)throw f;await d?.(f,p);const _=c.baseDelayMs*Math.pow(2,p)+Math.floor(Math.random()*10);await(0,t.sleep)(_)}throw new Error("withRetry exhausted unexpectedly")}t.withRetry=i;function n(c,u,d){return new Promise((h,p)=>{const f=indexedDB.open(c,u);f.onupgradeneeded=()=>{try{const _=f.result,P=f.transaction;d?.(_,P)}catch(_){p(_)}},f.onerror=()=>p(f.error),f.onblocked=()=>{},f.onsuccess=()=>{const _=f.result;_.onversionchange=()=>{try{_.close()}finally{t.cache.delete(c)}},h(_)}})}async function r(c,u,d){let h=!c.objectStoreNames.contains(u),p=[];if(!h&&d?.indexes?.length){const P=c.transaction(u,"readonly"),C=P.objectStore(u),R=new Set(Array.from(C.indexNames));p=(d.indexes||[]).filter(y=>!R.has(y.name)),await new Promise((y,g)=>{P.oncomplete=()=>y(),P.onabort=()=>g(P.error),P.onerror=()=>g(P.error)})}if(!h&&p.length===0)return c;const f=c.version+1;c.close();const _=await n(c.name,f,(P,C)=>{let R;P.objectStoreNames.contains(u)?R=C.objectStore(u):R=P.createObjectStore(u,{keyPath:d?.keyPath??void 0,autoIncrement:!!d?.autoIncrement});for(const y of p)R.indexNames.contains(y.name)||R.createIndex(y.name,y.keyPath,y.options)});return _.onversionchange=()=>{try{_.close()}finally{t.cache.delete(_.name)}},_}async function s(c,u,d){let h=t.cache.get(c);return h?(h=h.then(p=>r(p,u,d)),t.cache.set(c,h)):(h=(async()=>{const p=await n(c);return r(p,u,d)})(),t.cache.set(c,h)),h}t.getDB=s;async function o(c){const u=t.cache.get(c);if(t.cache.delete(c),u)try{(await u).close()}catch{}}t.closeConnection=o;function a(c){return new Promise((u,d)=>{c.onsuccess=()=>u(c.result),c.onerror=()=>d(c.error)})}t.asyncRequest=a;function l(c){return new Promise((u,d)=>{c.oncomplete=()=>u(),c.onabort=()=>d(c.error??new DOMException("Aborted","AbortError")),c.onerror=()=>d(c.error??new DOMException("TransactionError","UnknownError"))})}t.waitTx=l})(we||(we={}));let qh=class{constructor(e,i,n={}){this.dbName=e,this.storeName=i,this.options=n}get _iterBatch(){return this.options.iterBatch??we.defaults.iterBatch}get _retryCfg(){const e=this.options.retry??we.defaults.retry;return{attempts:e.attempts??3,baseDelayMs:e.baseDelayMs??16}}async _withStore(e,i){const n=this._retryCfg;return we.withRetry(n,async()=>{const r=await we.getDB(this.dbName,this.storeName,this.options.ensure);try{const s=r.transaction(this.storeName,e),o=s.objectStore(this.storeName),a=await i(o);return await we.waitTx(s),a}catch(s){throw s}},async r=>{we.shouldReconnect(r)&&await we.closeConnection(this.dbName)})}async get(e){return this._withStore("readonly",async i=>{const n=await we.asyncRequest(i.get(e));return n===void 0?void 0:n})}async set(e,i){return await this._withStore("readwrite",async n=>{const r=this.options.ensure?.keyPath!=null?n.put(i):n.put(i,e);await we.asyncRequest(r)}),this}async delete(e){return this._withStore("readwrite",async i=>{const n=await we.asyncRequest(i.get(e))!==void 0;return await we.asyncRequest(i.delete(e)),n})}async clear(){await this._withStore("readwrite",async e=>{await we.asyncRequest(e.clear())})}async has(e){return await this.get(e)!==void 0}async count(){return this._withStore("readonly",async e=>await we.asyncRequest(e.count())??0)}async*_iterateEntries(){let e=null,i=!1;const n=Math.max(1,this._iterBatch);for(;!i;){const r=await this._withStore("readonly",async s=>{const o=[],a=e===null?void 0:IDBKeyRange.lowerBound(e,!0);return await new Promise((l,c)=>{const u=s.openCursor(a);u.onerror=()=>c(u.error),u.onsuccess=()=>{const d=u.result;if(!d){i=!0,l();return}o.push([d.key,d.value]),e=d.key,o.length>=n?l():d.continue()}}),o});for(const s of r)yield s;if(r.length===0)break}}entries(){return this._iterateEntries()}async*keys(){for await(const[e]of this.entries())yield e}async*values(){for await(const[,e]of this.entries())yield e}[Symbol.asyncIterator](){return this.entries()[Symbol.asyncIterator]()}async forEach(e){for await(const[i,n]of this.entries())await e(n,i,this)}async getMany(e){const i=new Map;for await(const n of e)i.set(n,void 0);return await this._withStore("readonly",async n=>{await Promise.all(i.keys().map(async r=>{const s=await we.asyncRequest(n.get(r));i.set(r,s===void 0?void 0:s)}))}),i}async setMany(e){const i=this.options.ensure?.keyPath!=null;return await this._withStore("readwrite",async n=>{for await(const[r,s]of e){const o=i?n.put(s):n.put(s,r);await we.asyncRequest(o)}}),this}async deleteMany(e){let i=0;return await this._withStore("readwrite",async n=>{for await(const r of e)await we.asyncRequest(n.get(r))!==void 0&&i++,await we.asyncRequest(n.delete(r))}),i}async disconnect(){await we.closeConnection(this.dbName)}};class Hh{constructor(e,i,n=1/0,r){this.dbName=e,this.storeName=i,this.ttl=n,this.version=r,this.db=new qh(e,i),this.keys=this.db.keys.bind(this.db),this.values=this.db.values.bind(this.db),this.entries=this.db.entries.bind(this.db),typeof this.ttl!="number"&&(this.ttl=Number(this.ttl)),(isNaN(this.ttl)||this.ttl<=0)&&(this.ttl=1/0),this._clearExpiredEntries().catch(()=>{})}async _clearExpiredEntries(){if(this.ttl===1/0)return;const e=Date.now(),i=[];for await(const[n,r]of this.db.entries())typeof r.time=="number"&&e-r.time>this.ttl&&i.push(n);i.length>0&&await this.db.deleteMany(i)}async get(e,i=this.ttl,n){const r=await this.loadFromDB(e),s=this.checkIfExpired(r,i);if(!r||s){if(typeof n=="function"){const o=await n();return await this.set(e,o),o}return null}return r.value}async set(e,i){const n=Date.now();if(typeof e=="string"){const l=e,c=i;if(c===null||typeof c>"u")return this.delete(l);const u={time:n,value:c,version:this.version};return await this.db.set(l,u),u}const r=e,s=[],o=[],a={};for(const[l,c]of Object.entries(r))if(c===null||typeof c>"u")o.push(l);else{const u={time:n,value:c,version:this.version};s.push([l,u]),a[l]=u}return s.length>0&&await this.db.setMany(s),o.length>0&&await this.db.deleteMany(o),a}async has(e,i=this.ttl){const n=await this.loadFromDB(e),r=this.checkIfExpired(n,i);return n!==null&&!r}async delete(e){await this.db.delete(e)}async updatedAt(e){const i=await this.loadFromDB(e);return i?i.time:0}async loadFromDB(e){const i=await this.db.get(e);if(i===void 0)return null;if(typeof i.time!="number"||typeof i.value>"u"){try{await this.delete(e)}catch{}return null}if(typeof this.version=="number"&&i.version!==this.version){try{await this.delete(e)}catch{}return null}return i}checkIfExpired(e,i=this.ttl){return e?Date.now()-e.time>i:!1}async clear(){return await this.db.clear(),this}}class zh extends Ot{constructor(e,i){super(e,"storage",!1),this.config=i,this.kv=this.createDatabase("key-val",0,1,"indexedDB"),this.simpleKV=this.createDatabase("~",0,1,"localStorage"),this.memoryKV=this.createDatabase("~",0,1,"memory")}createDatabase(e,i,n,r="indexedDB"){const s="indexedDB"in window&&window.indexedDB!==null;switch(r==="indexedDB"&&!s&&(r="localStorage"),r){case"indexedDB":return new Hh(this.config.dbName,e,i,n);case"localStorage":case"sessionStorage":case"memory":return new Bh(this.config.dbName,e,i,n,r);default:throw new Error(`Unsupported storage engine: ${r}`)}}}var rt=(t=>(t.preferences="preferences",t.watch="watch",t.unwatch="unwatch",t.nochange="nochange",t))(rt||{});function Kh(t){const i=class i{constructor(r,s=!0){this._loaded=s,this.api=t,r.revisions?.forEach(o=>{typeof o?.slots?.main=="object"&&Object.assign(o,o.slots.main)}),this.pageInfo={...i.DEFAULT_PAGE_INFO,...r}}static async newFromApi(r){const{data:s}=await this.api.get({...i.DEFAULT_QUERY_PARAMS,...r}),o=s?.query?.pages?.[0];if(!o||!o.title)throw new Error("Invalid page info",{cause:s});return new i(o,!0)}static newBlankPage(r={}){return new i(r,!1)}static async newFromAnyKind(r){const{title:s,pageId:o,revisionId:a}=r||{};return a?this.newFromApi({revids:parseInt(a.toString(),10)}):o?this.newFromApi({pageids:parseInt(o.toString(),10)}):s?this.newFromApi({titles:s.toString()}):null}static async newBatchFromApi(r){const{titles:s,pageids:o,revids:a,...l}=r||{},{data:c}=await this.api.post({...i.DEFAULT_QUERY_PARAMS,titles:s?.join("|")??void 0,pageids:o?.join("|")??void 0,revids:a?.join("|")??void 0,...l});return c?.query?.pages?.map(u=>new i(u,!0))||[]}async parse(r){return this.api.post({action:"parse",page:this.pageInfo.title,prop:"text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties|parsewarnings",...r})}async preview(r,s){return this.parse({action:"parse",page:void 0,title:this.title,text:r,pst:1,preview:1,disableeditsection:1,disablelimitreport:1,...s})}async edit(r,s){const{text:o,prependtext:a,appendtext:l,summary:c="",watchlist:u=rt.preferences,section:d}=r;return this.api.postWithEditToken({action:"edit",title:this.title,starttimestamp:this.pageInfo.touched,basetimestamp:this.revisions[0]?.timestamp,text:o,prependtext:a,appendtext:l,summary:c,watchlist:u,section:d,...s})}async createOnly(r,s){return this.edit(r,{createonly:1,...s})}async delete(r,s){return this.api.postWithEditToken({action:"delete",title:this.pageInfo.title||void 0,pageid:this.pageInfo.pageid||void 0,reason:r,deletetalk:s?.deletetalk,...s})}async moveTo(r,s,o){return this.api.postWithEditToken({action:"move",from:this.pageInfo.title,to:r,reason:s,movetalk:1,movesubpages:1,...o})}userCan(r){return!!this.pageInfo?.actions?.[r]}userCanEdit(){return this.userCan("edit")}async reloadSelfInfo(){const r=await i.newFromApi({pageids:this.pageInfo.pageid,titles:this.pageInfo.title}),s=(this.pageInfo.revisions||[]).concat(r.revisions||[]).sort((o,a)=>o.revid-a.revid).reduce((o,a)=>(o.find(l=>l.revid===a.revid)||o.push(a),o),[]);return this.pageInfo=r.pageInfo,this.pageInfo.revisions=s,this._loaded=!0,this}get pageid(){return this.pageInfo.pageid}get title(){return this.pageInfo.title}get ns(){return this.pageInfo.ns}get contentmodel(){return this.pageInfo.contentmodel}get fullurl(){return this.pageInfo.fullurl}get canonicalurl(){return this.pageInfo.canonicalurl}get editurl(){return this.pageInfo.editurl}get revisions(){return this.pageInfo.revisions||[]}get lastrevid(){return this.pageInfo.lastrevid}get templates(){return this.pageInfo.templates||[]}get images(){return this.pageInfo.images||[]}};i.api=t,i.DEFAULT_QUERY_PARAMS={action:"query",prop:"info|templates|transcludedin|images|pageimages|revisions",inprop:"protection|url|varianttitles",intestactions:"edit|move|delete",tllimit:"max",tilimit:"max",imlimit:"max",piprop:"thumbnail|name|original",pithumbsize:"200",pilimit:"max",rvprop:"ids|timestamp|flags|comment|user|content",rvslots:"main"},i.DEFAULT_PAGE_INFO={pageid:0,ns:0,title:"",contentmodel:"wikitext",pagelanguage:"",pagelanguagehtmlcode:"",pagelanguagedir:"ltr",touched:new Date().toISOString(),lastrevid:0,length:0,protection:[],restrictiontypes:[],fullurl:"",canonicalurl:"",editurl:"",varianttitles:{},actions:{edit:!0,move:!1,delete:!1},revisions:[],templates:[],images:[]};let e=i;return e}const na=class na extends Ot{constructor(e){super(e,"wikiPage",!0),this.ctx=e,this.WikiPage=Kh(this.ctx.api)}async createInstance(e,i=!1){return await this.WikiPage.newFromApi(e)}async newFromTitle(e,i=!1,n,r=!1){return this.createInstance({titles:e.toString(),converttitles:i,rvsection:n},r)}async newFromPageId(e,i,n=!1){return this.createInstance({pageids:e,rvsection:i},n)}async newFromRevision(e,i,n=!1){return await this.createInstance({revids:e,rvsection:i},n)}newBlankPage(e={}){return this.WikiPage.newBlankPage(e)}};na.inject=["api"];let As=na;const tl=new WeakMap,bt={toDBKey:t=>t.replace(/ /g,"_"),toNormalText:t=>t.replace(/_/g," "),ensureCase:(t,e)=>e==="first-letter"?t.charAt(0).toUpperCase()+t.slice(1):t},xi={normalizeSpecialPageName:t=>t.toLowerCase(),buildSpecialPageIndex:t=>{const e=new Map,i=new Map,n=new Map;for(const r of t.specialpagealiases){const s=r.realname;e.set(s,s);const o=xi.normalizeSpecialPageName(s);n.set(o,s);for(const a of r.aliases){i.set(a,s);const l=xi.normalizeSpecialPageName(a);n.set(l,s)}}return{byRealName:e,byAlias:i,byNormalized:n}},findSpecialPageRealName:(t,e)=>{const i=t.split("/")[0];let n=e.byRealName.get(i)??e.byAlias.get(i);if(n!==void 0)return n;const r=xi.normalizeSpecialPageName(i);return e.byNormalized.get(r)??null}},ut={normalizeNamespaceText:t=>t.replace(/[_\s]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),buildIndex:t=>{const e=new Map,i=new Map,n=new Map,r=new Map;for(const[s,o]of Object.entries(t.namespaces)){const a=parseInt(s);e.set(o.name,a),i.set(o.canonical??"",a);const l=ut.normalizeNamespaceText(o.name),c=ut.normalizeNamespaceText(o.canonical??"");r.set(l,a),r.set(c,a)}for(const s of t.namespacealiases){n.set(s.alias,s.id);const o=ut.normalizeNamespaceText(s.alias);r.set(o,s.id)}return{byName:e,byCanonical:i,byAlias:n,byNormalized:r}},findNamespaceId:(t,e)=>{let i=e.byName.get(t)??e.byCanonical.get(t)??e.byAlias.get(t);if(i!==void 0)return i;const n=ut.normalizeNamespaceText(t);return e.byNormalized.get(n)??null},isTalkPage:t=>t%2===1&&t>0,getDefaultNamespaceInfo:t=>({id:t,name:"",canonical:"",case:"first-letter",content:!1,nonincludable:!1,subpages:!1})};function Wh(t){var s,o;const e=tl.get(t);if(e)return e;const i=ut.buildIndex(t),n=xi.buildSpecialPageIndex(t),a=class a{constructor(c,u){Hi(this,s);Hi(this,o);if(this.newTitle=a.create.bind(a),this.toText=this.getPrefixedText.bind(this),this.toString=this.getPrefixedDBKey.bind(this),Qe(this,s,c||""),Qe(this,o,u??0),u===void 0?this.fixNSByTitle():this.stripNamespaceFromTitle(),this.getMainText()==="")throw new Error("Invalid title")}static create(c,u){return new a(c,u)}fixNSByTitle(){const c=X(this,s).indexOf(":");if(c===-1)return;if(c===0){Qe(this,s,X(this,s).substring(1));return}const u=X(this,s).substring(0,c),d=X(this,s).substring(c+1),h=ut.findNamespaceId(u,a._namespaceIndex);h!==null&&(Qe(this,s,d),Qe(this,o,h))}stripNamespaceFromTitle(){const c=X(this,s).indexOf(":");if(c===-1)return;if(c===0){Qe(this,s,X(this,s).substring(1));return}const u=X(this,s).substring(0,c),d=X(this,s).substring(c+1);ut.findNamespaceId(u,a._namespaceIndex)!==null&&Qe(this,s,d)}getNamespaceInfo(){return a._meta.namespaces[X(this,o)]??ut.getDefaultNamespaceInfo(X(this,o))}getMainDBKey(){const c=this.getNamespaceInfo();if(X(this,o)===-1){const u=xi.findSpecialPageRealName(X(this,s),a._specialPageIndex);if(u){const d=X(this,s).includes("/")?X(this,s).substring(X(this,s).indexOf("/")):"",h=u+d;return bt.ensureCase(bt.toDBKey(h),c.case)}}return bt.ensureCase(bt.toDBKey(X(this,s)),c.case)}getMainText(){const c=this.getNamespaceInfo();if(X(this,o)===-1){const u=xi.findSpecialPageRealName(X(this,s),a._specialPageIndex);if(u){const d=X(this,s).includes("/")?X(this,s).substring(X(this,s).indexOf("/")):"",h=u+d;return bt.ensureCase(bt.toNormalText(h),c.case)}}return bt.ensureCase(bt.toNormalText(X(this,s)),c.case)}getMainRootText(){return this.getMainText().split("/")[0]}getPrefixedDBKey(){return X(this,o)===0?this.getMainDBKey():`${this.getNamespaceDBKey()}:${this.getMainDBKey()}`}getPrefixedText(){return X(this,o)===0?this.getMainText():`${this.getNamespaceText()}:${this.getMainText()}`}getNamespaceId(){return X(this,o)}getNamespaceText(){return this.getNamespaceInfo().name??""}getNamespaceDBKey(){const c=this.getNamespaceInfo();return bt.ensureCase(bt.toDBKey(this.getNamespaceText()),c.case)}getSubjectPage(){if(ut.isTalkPage(X(this,o))){const c=X(this,o)-1;return new a(X(this,s),c)}return this}getTalkPage(){if(ut.isTalkPage(X(this,o)))return this;if(X(this,o)<0)return null;const c=X(this,o)+1;return a._meta.namespaces[c.toString()]?new a(X(this,s),c):null}getURL(c){const u=a._meta.general.articlepath,d=this.getPrefixedDBKey(),h=u.replace("$1",d),p=new URL(h,location.origin);return c&&(c instanceof URLSearchParams?c:new URLSearchParams(c)).forEach((_,P)=>{p.searchParams.set(P,_)}),p}setTitle(c){return Qe(this,s,c),Qe(this,o,0),this.fixNSByTitle(),this}setMainText(c){return Qe(this,s,c),this}setNamespaceText(c){const u=ut.findNamespaceId(c,a._namespaceIndex);return u!==null&&Qe(this,o,u),this}setNamespaceId(c){return Qe(this,o,c),this}equals(c){return typeof c=="string"&&(c=new a(c)),this.getPrefixedDBKey()===c.getPrefixedDBKey()}isSpecial(c){if(X(this,o)!==-1)return!1;const u=new a(c,-1);return this.getMainRootText()===u.getMainRootText()}toJSON(){return{ns:X(this,o),text:this.getMainText(),title:this.getPrefixedText(),url:this.getURL().toString(),isSpecial:X(this,o)<0}}};s=new WeakMap,o=new WeakMap,a._meta=t,a._namespaceIndex=i,a._specialPageIndex=n;let r=a;return tl.set(t,r),r}const Rn=class Rn extends Ot{constructor(e){super(e,"wikiTitle",!0),this.ctx=e,this.logger=this.ctx.logger("WikiTitleService"),this._cachedTitles=new Map,this.wiki=this.ctx.wiki,this.wikiBaseUrl=this.wiki.baseUrl,this.wikiArticlePath=this.wiki.articlePath.replace("$1",""),this.wikiArticleBaseUrl=this.wiki.articleBaseUrl.replace("$1",""),this.wikiIndexPhpUrl=this.wiki.getSciprtUrl("index.php"),this.Title=Wh(this.ctx.wiki.siteInfo)}newTitle(e,i){return new this.Title(e,i)}newMainPageTitle(){return this.newTitle(this.ctx.wiki.mainPageName)}async newTitleFromUrl(e){const i=this.parseWikiLink(e);return i?.title?i.title:i?.pageId?this.newTitleFromPageId(i.pageId):null}async newTitleFromAnyId(e,i=!1){const{title:n,pageId:r,revId:s}=e??{};if(typeof n=="string")return this.newTitle(n);let o,a;if(s?(o=parseInt(s.toString(),10),a="revid"):r&&(o=parseInt(r.toString(),10),a="pageid"),!o||!a||isNaN(o)||o<=0)throw new Error("Invalid id or kind",{cause:e});if(!i&&this._cachedTitles.has(`${a}:${o}`))return await this._cachedTitles.get(`${a}:${o}`);const{promise:l,resolve:c,reject:u}=re();this._cachedTitles.set(`${a}:${o}`,l);try{const{wikiPage:d}=this.ctx;let h=null;if(a==="pageid")h=await d.newFromPageId(o);else if(a==="revid")h=await d.newFromRevision(o);else throw new Error(`Invalid kind: ${a}`);c(this.newTitle(h.title))}catch(d){this._cachedTitles.delete(`${a}:${o}`),u(d)}return l}async newTitleFromPageId(e){return this.newTitleFromAnyId({pageId:e})}async newTitleFromRevision(e){return this.newTitleFromAnyId({revId:e})}resolveSpecialPageTarget(e){const i=typeof e=="string"?this.newTitle(e):e;if(!i||i.getNamespaceId()!==-1)return null;let n,r,s="view";const o=i.getMainDBKey().split("/").slice(1).join("/")||"";if(i.isSpecial("edit")&&o)n=o,s="edit";else if(i.isSpecial("talkpage")&&o){const a=i.newTitle(o).getTalkPage();if(!a)return null;n=a.getPrefixedDBKey()}else if(i.isSpecial("mypage"))n=i.newTitle(this.ctx.wiki.userInfo.name,2).getPrefixedDBKey()+(o?`/${o}`:"");else if(i.isSpecial("mytalk"))n=i.newTitle(this.ctx.wiki.userInfo.name,3).getPrefixedDBKey()+(o?`/${o}`:"");else if(i.isSpecial("newsection")&&o)n=o,r="new",s="edit";else return null;return{title:new this.Title(n),section:r,action:s}}isWikiLink(e){return e.startsWith(this.wikiArticleBaseUrl)||e.startsWith(this.wikiIndexPhpUrl)||e.startsWith(`${this.wikiBaseUrl}/?`)||e===this.ctx.wiki.landingPageUrl}validateHrefAttr(e){return typeof e!="string"?!1:!Rn.REG_SKIPPED_HREF.test(e)}parseWikiLink(e){if(!e||typeof e=="string"&&!this.validateHrefAttr(e))return null;const i=Ya(e);if(!this.isWikiLink(i.toString()))return null;const n=i.searchParams,r=i.hash.replace("#",""),s=n.get("action")||"view",o=n.get("title")||"",a=parseInt(n.get("curid")||"0",10),l=parseInt(n.get("oldid")||"0",10);let c=o||(()=>{try{return decodeURIComponent(i.pathname.substring(this.wikiArticlePath.length))}catch(p){return this.logger.error("parseLink",i,p),""}})();c.endsWith("index.php")&&(c="");let u,d,h;if(l)h=l;else if(a)d=a;else if(c)u=this.newTitle(c);else if(i.origin+i.pathname===this.ctx.wiki.landingPageUrl)u=this.newMainPageTitle();else return null;return{title:u,pageId:d,revId:h,url:i,params:n,hash:r,action:s}}};Rn.inject=["wiki","wikiPage"],Rn.REG_SKIPPED_HREF=/^(#|javascript:|vbscript:|file:)/i;let Is=Rn;const Vh=t=>typeof t=="function";async function Gh(t){return Vh(t)?await t():t}var Yh=Object.create,Os=Object.defineProperty,Qh=Object.getOwnPropertyDescriptor,il=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),nl=t=>{throw TypeError(t)},Jh=(t,e,i)=>e in t?Os(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Xh=(t,e)=>Os(t,"name",{value:e,configurable:!0}),Zh=t=>[,,,Yh(t?.[il("metadata")]??null)],ep=["class","method","getter","setter","accessor","field","value","get","set"],rl=t=>t!==void 0&&typeof t!="function"?nl("Function expected"):t,tp=(t,e,i,n,r)=>({kind:ep[t],name:e,metadata:n,addInitializer:s=>i._?nl("Already initialized"):r.push(rl(s||null))}),ip=(t,e)=>Jh(e,il("metadata"),t[3]),np=(t,e,i,n)=>{for(var r=0,s=t[e>>1],o=s&&s.length;r<o;r++)s[r].call(i);return n},rp=(t,e,i,n,r,s)=>{var o,a,l,c=e&7,u=!1,d=0,h=t[d]||(t[d]=[]),p=c&&(r=r.prototype,c<5&&(c>3||!u)&&Qh(r,i));Xh(r,i);for(var f=n.length-1;f>=0;f--)l=tp(c,i,a={},t[3],h),o=(0,n[f])(r,l),a._=1,rl(o)&&(r=o);return ip(t,r),p&&Os(r,i,p),u?c^4?s:p:r},sl,Ts,ol;sl=[$e(["storage","wiki"])];class Zn extends(ol=Ot){constructor(e){super(e,"preferences",!0),this.ctx=e,this.db=void 0,this.customRegistries=[],this.categoryDefinitions=[],this._defaultPreferences={},e.set("prefs",this),this.db=e.storage.createDatabase(`preferences:${e.wiki.userInfo.id}`,1/0);try{this._migrageFromLegacyMasterDB()}catch{}}get logger(){return this.ctx.logger("PREFERENCES")}async start(){this.defineCategory({name:"general",label:"General",description:"General settings",autoGenerateForm:!0}),this.defineCategory({name:"editor",label:"Editor",description:"Settings related to editing content",autoGenerateForm:!0})}async get(e,i){if(!e)return this.getAll();i??(i=()=>{const r=this.defaultOf(e);return this.logger.debug(e,`(fallback value: ${r})`),r});const n=await this.db.get(e,void 0);return n!==null?n:await Gh(i)}async getAll(){const e=this.loadDefaultConfigs();for await(const[i,n]of this.db.entries())i!=="_touched"&&i in e&&(e[i]=n.value);return e}async set(e,i){return(await this.setMany({[e]:i}))[e]}async setMany(e){const i=this.loadDefaultConfigs(),n={};for(const[r,s]of Object.entries(e))s===i[r]||s===void 0?n[r]=void 0:n[r]=s;return await this.db.set(n),this.ctx.emit("preferences/changed",{ctx:this.ctx,input:e,changes:n}),n}defaultOf(e){var i;return(i=this._defaultPreferences)[e]??(i[e]=this.loadDefaultConfigs()[e])}async getExportableRecord(e){e??(e=await this.getAll());const i=this.loadDefaultConfigs(),n={};return Object.entries(i).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{const o=e[r];o!==void 0&&o!==s&&(n[r]=o)}),n}loadDefaultConfigs(){const e={};return this.getConfigRegistries().forEach(i=>{try{const n=i.schema({});Object.entries(n).forEach(([r,s])=>{e[r]=s})}catch{}}),Object.entries(e).forEach(([i,n])=>{this._defaultPreferences[i]=n}),e}registerCustomConfig(e,i,n){return this.customRegistries.push({name:e,schema:i,category:n||"general"}),this}getConfigRegistries(e){return Array.from(this.ctx.registry.entries()).map(([i])=>i===null?{name:"@root",schema:Si?.PreferencesSchema||null}:{name:i.name,schema:i?.PreferencesSchema||null}).filter(i=>i.schema!==null).map(i=>({...i,category:i.schema.meta.category||"general"})).concat(this.customRegistries).filter(i=>!e||i.category===e)}getAllSchema(){return new L(L.intersect(this.getConfigRegistries().map(e=>e.schema)))}defineCategory(e){const i=this.categoryDefinitions.findIndex(n=>n.name===e.name);return i<0?this.categoryDefinitions.push(e):this.categoryDefinitions[i]=e,this.categoryDefinitions.sort((n,r)=>(n.index??0)-(r.index??0)),this}getConfigCategories(){return this.categoryDefinitions}async _migrageFromLegacyMasterDB(){const e=this.ctx.storage.createDatabase("preferences",1/0);let i=0;for await(const[n,r]of e.entries())n!=="_touched"&&(await this.db.set(n,r.value),i++);return i&&this.logger.info(`Migrated ${i} preferences from master DB`),await e.clear(),await e?.db?.disconnect?.(),i}}Ts=Zh(ol),Zn=rp(Ts,0,"PreferencesService",sl,Zn),np(Ts,1,Zn);var Lt=(t=>(t.ANALYTICS_API_BASE="https://analytics.ipe.wiki/api/v6",t.ANALYTICS_DASH_URL="https://analytics.ipe.wiki",t.GITHUB_URL="https://github.com/inpageedit/inpageedit-next",t.HOME_URL="https://www.ipe.wiki/",t.UPDATE_LOGS_URL="https://www.ipe.wiki/changelogs/",t.PLUGIN_REGISTRY_URL="https://registry.ipe.wiki/registry.v1.json",t))(Lt||{});const An=class An extends Be{constructor(i){super({name:"InPageEdit"});Hi(this,$t);this.version="0.13.0",this.Endpoints=Lt,this.schema=L,this.config=Vi(An.DEFAULT_CONFIG,i),this.logger=Sa({name:"IPE",color:"#33aaff",level:this.config.logLevel}),lt(this,$t,If).call(this),this.config.autoInstallCorePlugins&<(this,$t,Tf).call(this),lt(this,$t,Lf).call(this)}async withInject(i){const{promise:n,resolve:r}=re();return this.inject(i,s=>{r(s)}),n}};$t=new WeakSet,If=async function(){this.plugin(Ed,this.config.apiConfigs),this.plugin(zn),this.plugin(Md),this.plugin(Ph),this.plugin(Zn),this.plugin(zh,{dbName:this.config.storageNamespace}),this.plugin(Xn),this.plugin(As),this.plugin(Is),lt(this,$t,Of).call(this,["api","currentPage","resourceLoader","modal","preferences","storage","wikiPage","wikiTitle","wiki","getUrl","getSciprtUrl","getMainpageUrl"])},Of=function(i){if(typeof i=="string"&&(i=[i]),!Array.isArray(i)||i.length===0)return this;for(const n of i){const r=this[An.internal][n];r?.type==="service"&&(r.builtin=!0)}return this},Tf=async function(){[Promise.resolve().then(()=>vp).then(({PluginAnalytics:n})=>n),Promise.resolve().then(()=>Ap).then(({PluginInArticleLinks:n})=>n),Promise.resolve().then(()=>dy).then(({PluginPluginStore:n})=>n),Promise.resolve().then(()=>Uy).then(({PluginPreferencesUI:n})=>n),Promise.resolve().then(()=>eb).then(({PluginQuickEdit:n})=>n),Promise.resolve().then(()=>fb).then(({PluginQuickMove:n})=>n),Promise.resolve().then(()=>xb).then(({PluginQuickPreview:n})=>n),Promise.resolve().then(()=>Ub).then(({PluginQuickDiff:n})=>n),Promise.resolve().then(()=>Fb).then(({PluginQuickRedirect:n})=>n),Promise.resolve().then(()=>Jb).then(({PluginToolbox:n})=>n)].forEach(async n=>{this.plugin(await n)})},Lf=async function(){this.inject(["resourceLoader"],i=>{})},An.DEFAULT_CONFIG={apiConfigs:{},legacyPreferences:{},logLevel:ls.info,storageNamespace:"InPageEdit",autoloadStyles:!0,autoInstallCorePlugins:!0};let Si=An;function al(t){return t.charAt(0).toLowerCase()+t.slice(1)}function sp(t){return al(t).replace(/_/g,"-").replace(/.[A-Z]+/g,e=>e[0]+"-"+e.slice(1).toLowerCase())}function op(t){return al(t).replace(/-/g,"_").replace(/.[A-Z]+/g,e=>e[0]+"_"+e.slice(1).toLowerCase())}const Vr=class Vr{constructor(e,i=void 0,n){Hi(this,In);this.ctx=e,this.disposeHandlers=[],this.name=n||"",this.config=i||{};const{promise:r,resolve:s,reject:o}=Promise.withResolvers();queueMicrotask(()=>{this.name||(this.name=this.constructor.name);try{const a=this.start();a&&typeof a.then=="function"?a.then(()=>s()).catch(l=>{this.logger.error("start() returns a rejected promise",l),o(l)}):s()}catch(a){this.logger.error("start() threw synchronously",a),o(a)}r.then(()=>{this.logger.debug("started")}),r.catch(a=>{this.logger.error("start failed",a),this.ctx.scope.dispose()})}),this.ctx.once("dispose",()=>{this.disposeHandlers.forEach(a=>a(this.ctx)),this.stop(),this.logger.debug("disposed")})}start(){}stop(){}addDisposeHandler(e){this.disposeHandlers.push(e)}removeDisposeHandler(e){this.disposeHandlers=this.disposeHandlers.filter(i=>i!==e)}set name(e){Qe(this,In,op(e).toUpperCase())}get name(){return X(this,In)}get logger(){return this.ctx.logger(this.name)}};In=new WeakMap,Vr.inject=[],Vr.reusable=!1;let Xe=Vr;function si(t){return function(e){return e.PreferencesSchema=t,e}}window.RLQ||(window.RLQ=[]),window.__IPE_MODULES__||(window.__IPE_MODULES__=[]),lp("InPageEdit#autoload",()=>{const t=ll();t&&ap({baseURL:t,InPageEdit:Si})});async function ap(t={baseURL:ll(),InPageEdit:Si}){const{baseURL:e,InPageEdit:i}=t;typeof window?.ipe?.stop=="function"&&await window.ipe.stop();const n=window.InPageEdit||{},r=new i({apiConfigs:{baseURL:e},legacyPreferences:n?.myPreferences||{}});if(window.ipe=r,await r.start(),window.RLQ.push(()=>{mw.hook("InPageEdit.ready").fire(r)}),Array.isArray(window.__IPE_MODULES__)){const s=[];for(;window.__IPE_MODULES__.length;)try{const o=window.__IPE_MODULES__.shift();typeof o=="function"&&o?.(r),s.push(o)}catch{}window.__IPE_MODULES__={push:o=>{typeof o=="function"&&o(r),s.push(o)}},r.on("dispose",()=>{window.__IPE_MODULES__=s})}r.logger("AUTOLOAD").info(`
|
|
5
5
|
____ ____ ______ ___ __
|
|
6
6
|
/ _/___ / __ \\____ _____ ____ / ____/___/ (_) /_
|
|
7
7
|
/ // __ \\/ /_/ / __ \`/ __ \`/ _ \\/ __/ / __ / / __/
|