tiny-essentials 1.29.0 → 1.29.2

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.
Files changed (131) hide show
  1. package/changelog/1/29/1.md +11 -0
  2. package/changelog/1/29/2.md +82 -0
  3. package/dist/v1/TinyBasicsEs.min.js +1 -1
  4. package/dist/v1/TinyEssentials.min.js +1 -1
  5. package/dist/v1/TinyFetchLoader.min.js +1 -0
  6. package/dist/v1/TinyImageLoader.min.js +1 -0
  7. package/dist/v1/TinyMediaCache.min.js +1 -0
  8. package/dist/v1/TinyMediaLoader.min.js +1 -0
  9. package/dist/v1/basics/index.cjs +5 -0
  10. package/dist/v1/basics/index.d.mts +2 -1
  11. package/dist/v1/basics/index.d.mts.map +1 -1
  12. package/dist/v1/basics/index.mjs +2 -1
  13. package/dist/v1/basics/media/youtube.cjs +275 -0
  14. package/dist/v1/basics/media/youtube.d.mts +107 -0
  15. package/dist/v1/basics/media/youtube.d.mts.map +1 -0
  16. package/dist/v1/basics/media/youtube.mjs +214 -0
  17. package/dist/v1/index.cjs +13 -0
  18. package/dist/v1/index.d.mts +6 -1
  19. package/dist/v1/index.d.mts.map +1 -1
  20. package/dist/v1/index.mjs +7 -2
  21. package/dist/v1/libs/fs/plugins/OPFS/StorageBucket.cjs +0 -1
  22. package/dist/v1/libs/fs/plugins/OPFS/StorageBucket.d.mts +0 -1
  23. package/dist/v1/libs/fs/plugins/OPFS/StorageBucket.d.mts.map +1 -1
  24. package/dist/v1/libs/fs/plugins/OPFS/StorageBucket.mjs +0 -1
  25. package/dist/v1/libs/fs/plugins/OPFS/index.cjs +0 -8
  26. package/dist/v1/libs/fs/plugins/OPFS/index.d.mts +0 -8
  27. package/dist/v1/libs/fs/plugins/OPFS/index.d.mts.map +1 -1
  28. package/dist/v1/libs/fs/plugins/OPFS/index.mjs +0 -8
  29. package/dist/v1/libs/html/TinyHtml.cjs +1 -1
  30. package/dist/v1/libs/html/TinyHtml.d.mts +2 -2
  31. package/dist/v1/libs/html/TinyHtml.d.mts.map +1 -1
  32. package/dist/v1/libs/html/TinyHtml.mjs +1 -1
  33. package/dist/v1/libs/html/loader/TinyMediaLoader.cjs +1999 -0
  34. package/dist/v1/libs/html/loader/TinyMediaLoader.d.mts +999 -0
  35. package/dist/v1/libs/html/loader/TinyMediaLoader.d.mts.map +1 -0
  36. package/dist/v1/libs/html/loader/TinyMediaLoader.mjs +1852 -0
  37. package/dist/v1/libs/html/loader/beta/formats/TinyAudioLoader.cjs +77 -0
  38. package/dist/v1/libs/html/loader/beta/formats/TinyAudioLoader.d.mts +103 -0
  39. package/dist/v1/libs/html/loader/beta/formats/TinyAudioLoader.d.mts.map +1 -0
  40. package/dist/v1/libs/html/loader/beta/formats/TinyAudioLoader.mjs +67 -0
  41. package/dist/v1/libs/html/loader/beta/formats/TinyContentLoader.cjs +630 -0
  42. package/dist/v1/libs/html/loader/beta/formats/TinyContentLoader.d.mts +138 -0
  43. package/dist/v1/libs/html/loader/beta/formats/TinyContentLoader.d.mts.map +1 -0
  44. package/dist/v1/libs/html/loader/beta/formats/TinyContentLoader.mjs +576 -0
  45. package/dist/v1/libs/html/loader/beta/formats/TinyVideoLoader.cjs +70 -0
  46. package/dist/v1/libs/html/loader/beta/formats/TinyVideoLoader.d.mts +100 -0
  47. package/dist/v1/libs/html/loader/beta/formats/TinyVideoLoader.d.mts.map +1 -0
  48. package/dist/v1/libs/html/loader/beta/formats/TinyVideoLoader.mjs +60 -0
  49. package/dist/v1/libs/html/loader/beta/probe/TinyMediaProbe.cjs +946 -0
  50. package/dist/v1/libs/html/loader/beta/probe/TinyMediaProbe.d.mts +67 -0
  51. package/dist/v1/libs/html/loader/beta/probe/TinyMediaProbe.d.mts.map +1 -0
  52. package/dist/v1/libs/html/loader/beta/probe/TinyMediaProbe.mjs +896 -0
  53. package/dist/v1/libs/html/loader/formats/TinyFetchLoader.cjs +225 -0
  54. package/dist/v1/libs/html/loader/formats/TinyFetchLoader.d.mts +149 -0
  55. package/dist/v1/libs/html/loader/formats/TinyFetchLoader.d.mts.map +1 -0
  56. package/dist/v1/libs/html/loader/formats/TinyFetchLoader.mjs +197 -0
  57. package/dist/v1/libs/html/loader/formats/TinyImageLoader.cjs +1454 -0
  58. package/dist/v1/libs/html/loader/formats/TinyImageLoader.d.mts +200 -0
  59. package/dist/v1/libs/html/loader/formats/TinyImageLoader.d.mts.map +1 -0
  60. package/dist/v1/libs/html/loader/formats/TinyImageLoader.mjs +1317 -0
  61. package/dist/v1/libs/html/loader/probe/TinyImageProbe.cjs +668 -0
  62. package/dist/v1/libs/html/loader/probe/TinyImageProbe.d.mts +83 -0
  63. package/dist/v1/libs/html/loader/probe/TinyImageProbe.d.mts.map +1 -0
  64. package/dist/v1/libs/html/loader/probe/TinyImageProbe.mjs +626 -0
  65. package/dist/v1/libs/html/loader/utils/TinyBufferReader.cjs +277 -0
  66. package/dist/v1/libs/html/loader/utils/TinyBufferReader.d.mts +118 -0
  67. package/dist/v1/libs/html/loader/utils/TinyBufferReader.d.mts.map +1 -0
  68. package/dist/v1/libs/html/loader/utils/TinyBufferReader.mjs +247 -0
  69. package/dist/v1/libs/html/loader/utils/TinyIsoBox.cjs +128 -0
  70. package/dist/v1/libs/html/loader/utils/TinyIsoBox.d.mts +49 -0
  71. package/dist/v1/libs/html/loader/utils/TinyIsoBox.d.mts.map +1 -0
  72. package/dist/v1/libs/html/loader/utils/TinyIsoBox.mjs +116 -0
  73. package/dist/v1/libs/html/loader/utils/TinyMediaCache.cjs +796 -0
  74. package/dist/v1/libs/html/loader/utils/TinyMediaCache.d.mts +354 -0
  75. package/dist/v1/libs/html/loader/utils/TinyMediaCache.d.mts.map +1 -0
  76. package/dist/v1/libs/html/loader/utils/TinyMediaCache.mjs +734 -0
  77. package/dist/v1/libs/html/loader/utils/TinyMediaMirror.cjs +302 -0
  78. package/dist/v1/libs/html/loader/utils/TinyMediaMirror.d.mts +256 -0
  79. package/dist/v1/libs/html/loader/utils/TinyMediaMirror.d.mts.map +1 -0
  80. package/dist/v1/libs/html/loader/utils/TinyMediaMirror.mjs +280 -0
  81. package/dist/v1/libs/html/loader/utils/TinyMediaProgress.cjs +194 -0
  82. package/dist/v1/libs/html/loader/utils/TinyMediaProgress.d.mts +138 -0
  83. package/dist/v1/libs/html/loader/utils/TinyMediaProgress.d.mts.map +1 -0
  84. package/dist/v1/libs/html/loader/utils/TinyMediaProgress.mjs +175 -0
  85. package/dist/v1/libs/tools/TinyPkgExportValidator.cjs +359 -55
  86. package/dist/v1/libs/tools/TinyPkgExportValidator.d.mts +64 -6
  87. package/dist/v1/libs/tools/TinyPkgExportValidator.d.mts.map +1 -1
  88. package/dist/v1/libs/tools/TinyPkgExportValidator.mjs +320 -57
  89. package/dist/v1/libs/worker/engine/TinyWebWorkerEngine.cjs +0 -1
  90. package/dist/v1/libs/worker/engine/TinyWebWorkerEngine.d.mts +0 -1
  91. package/dist/v1/libs/worker/engine/TinyWebWorkerEngine.d.mts.map +1 -1
  92. package/dist/v1/libs/worker/engine/TinyWebWorkerEngine.mjs +0 -1
  93. package/dist/v1/webTemplates/bootstrap/5.3/scss/background/_background-grid.scss +15 -0
  94. package/dist/v1/webTemplates/bootstrap/5.3/scss/components/buttons/_buttons-contrast.scss +208 -0
  95. package/dist/v1/webTemplates/bootstrap/5.3/scss/components/buttons/_buttons-ghost.scss +89 -0
  96. package/dist/v1/webTemplates/bootstrap/5.3/scss/components/icon/_cube-icon.scss +65 -0
  97. package/dist/v1/webTemplates/bootstrap/5.3/scss/components/icon/_sphere-pulse.scss +39 -0
  98. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_badges.scss +90 -0
  99. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_bootstrap-overrides.scss +495 -0
  100. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_buttons.scss +390 -0
  101. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_colors.scss +213 -0
  102. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_effects.scss +153 -0
  103. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_forms-tones.scss +69 -0
  104. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_forms.scss +323 -0
  105. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_global.scss +31 -0
  106. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_links.scss +47 -0
  107. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_tables.scss +25 -0
  108. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_theme.scss +21 -0
  109. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_tokens.scss +161 -0
  110. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_utilities.scss +81 -0
  111. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/_variables.scss +63 -0
  112. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/_form-tone-mixins.scss +236 -0
  113. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/_sizing.scss +68 -0
  114. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/_tone-mixins.scss +392 -0
  115. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/_typography.scss +112 -0
  116. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/background/_tiny_gradient_1.scss +131 -0
  117. package/dist/v1/webTemplates/bootstrap/5.3/scss/themes/deepstrap/plugins/colors/_pink.scss +47 -0
  118. package/dist/v1/webTemplates/multiformats/14.0/IPFSHasher/index.cjs +2 -2
  119. package/docs/v1/Exports.md +33 -2
  120. package/docs/v1/README.md +9 -0
  121. package/docs/v1/basics/youtube.md +204 -0
  122. package/docs/v1/libs/html/loader/TinyFetchLoader.md +114 -0
  123. package/docs/v1/libs/html/loader/TinyImageLoader.md +141 -0
  124. package/docs/v1/libs/html/loader/TinyMediaCache.md +166 -0
  125. package/docs/v1/libs/html/loader/TinyMediaLoader.md +300 -0
  126. package/docs/v1/libs/tools/TinyPkgExportValidator.md +55 -0
  127. package/docs/v1/webTemplates/ag-psd/31.0/ProcessSolidFilters.md +0 -4
  128. package/docs/v1/webTemplates/bootstrap/5.3/DeepStrap.md +177 -0
  129. package/package.json +281 -17
  130. /package/dist/v1/webTemplates/bootstrap/5.3/scss/input/{Placeholder-Colors-Fix.scss → _placeholder-colors-fix.scss} +0 -0
  131. /package/dist/v1/webTemplates/bootstrap/5.3/scss/spacing/{Spacing-Plus.scss → _spacing-plus.scss} +0 -0
@@ -1 +1 @@
1
- (()=>{var e={606(e){var t,r,i=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function o(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{r="function"==typeof clearTimeout?clearTimeout:n}catch(e){r=n}}();var a,l=[],h=!1,u=-1;function c(){h&&a&&(h=!1,a.length?l=a.concat(l):u=-1,l.length&&d())}function d(){if(!h){var e=o(c);h=!0;for(var t=l.length;t;){for(a=l,l=[];++u<t;)a&&a[u].run();u=-1,t=l.length}a=null,h=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===n||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function p(e,t){this.fun=e,this.array=t}function m(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new p(e,t)),1!==l.length||h||o(d)},p.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=m,i.addListener=m,i.once=m,i.off=m,i.removeListener=m,i.removeAllListeners=m,i.emit=m,i.prependListener=m,i.prependOnceListener=m,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},133(){},370(){},913(){},942(){},939(){}};const t={};function r(i){const s=t[i];if(void 0!==s)return s.exports;const n=t[i]={exports:{}};return e[i](n,n.exports,r),n.exports}r.cw=e=>{var t;return()=>{if(e){var r=e;e=0,t={exports:{}},r.call(t.exports,t,t.exports)}return t.exports}},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let i={};(()=>{"use strict";r.r(i),r.d(i,{ColorSafeStringify:()=>oe,FuzzySet:()=>Mi,MamdaniInferenceSystem:()=>Li,TinyAdvancedRaffle:()=>ei,TinyAfterScrollWatcher:()=>lr,TinyAnalogClock:()=>Ei,TinyArrayComparator:()=>Ai,TinyArrayPaginator:()=>ti,TinyBrowserMonitor:()=>Mn,TinyClassManager:()=>_i,TinyClipboard:()=>Sr,TinyCloner:()=>zs,TinyColorConverter:()=>Ar,TinyColorValidator:()=>bi,TinyCookieConsent:()=>ni,TinyDayNightCycle:()=>Yr,TinyDebugger:()=>Ji,TinyDomReadyManager:()=>$t,TinyDragDropDetector:()=>Ae,TinyDragger:()=>Ot,TinyElementObserver:()=>Et,TinyGamepad:()=>Jr,TinyHtml:()=>Pt,TinyHtmlTagRegexBuilder:()=>xn,TinyHttpResponseRegistry:()=>Vs,TinyI18:()=>di,TinyIframeEvents:()=>Fr,TinyInventory:()=>ii,TinyInventoryTrader:()=>si,TinyLevelUp:()=>l,TinyLoadingScreen:()=>gi,TinyLocalStorage:()=>jr,TinyMapCache:()=>ms,TinyMapDb:()=>lo,TinyMediaPlayer:()=>es,TinyNeedBar:()=>mi,TinyNewWinEvents:()=>qr,TinyNotificationAdapter:()=>Ns,TinyNotifications:()=>Ht,TinyNotifyCenter:()=>pe,TinyOPFSFileSystem:()=>to,TinyPkgExportValidator:()=>ns,TinyPlugin:()=>ks,TinyPluginCore:()=>Ds,TinyPluginLayer:()=>Is,TinyPromiseQueue:()=>ae,TinyPushManager:()=>co,TinyRadioFm:()=>Oi,TinyRateLimiter:()=>ue,TinyRouter:()=>cs,TinyServiceWorker:()=>Os,TinySetDb:()=>ao,TinySetMapDatabase:()=>ho,TinySimpleDice:()=>yi,TinySmartScroller:()=>Er,TinyStorageBucketFileSystem:()=>so,TinyTableDb:()=>oo,TinyTextDiffer:()=>Si,TinyTextRangeEditor:()=>Tr,TinyTextarea:()=>Vr,TinyThrottledApi:()=>_n,TinyTimeout:()=>kr,TinyToastNotify:()=>fe,TinyUploadClicker:()=>ts,TinyUriParser:()=>Cn,TinyVersion:()=>ys,TinyWebWorker:()=>Fn,UltraRandomMsgGen:()=>gr,addAiMarkerShortcut:()=>te,areElsCollBottom:()=>it,areElsCollLeft:()=>st,areElsCollPerfBottom:()=>at,areElsCollPerfLeft:()=>lt,areElsCollPerfRight:()=>ht,areElsCollPerfTop:()=>ot,areElsCollRight:()=>nt,areElsCollTop:()=>rt,areElsColliding:()=>ut,areElsPerfColliding:()=>ct,arraySortPositions:()=>d,asyncReplace:()=>Q,backupFile:()=>ze,breakdownDuration:()=>w,browserIs:()=>Ui,calculateMarketcap:()=>Y,checkObj:()=>_,clearDirectory:()=>Me,clearDirectoryAsync:()=>Ye,cloneObjTypeOrder:()=>k,compareMarketcap:()=>X,compileGlob:()=>Pn,compileGlobRegExp:()=>Rn,countObj:()=>b,createCheckDestroyed:()=>le,createPluginIdChecker:()=>vs,createSingletonTask:()=>Ir,decompileGlob:()=>jn,defuzzifyCentroid:()=>Ii,diffArrayList:()=>c,diffObjList:()=>ie,dirExists:()=>Ne,dirSize:()=>Fe,dirSizeAsync:()=>tt,documentIsFullScreen:()=>j,emailRegex:()=>un,emailStringRegexBuilder:()=>hn,ensureCopyFile:()=>Pe,ensureDirectory:()=>ke,exitFullScreen:()=>F,extendObjType:()=>I,extractEmails:()=>mn,extractIPsV4:()=>Ys,extractIPsV6:()=>rn,extractMediaId3Tags:()=>nr,extractUrls:()=>ln,extractUsernames:()=>Sn,fetchJson:()=>Ee,fetchText:()=>Te,fileExists:()=>Le,fileSize:()=>He,fileSizeAsync:()=>et,findEmailRegex:()=>pn,findIPv4Regex:()=>Gs,findIPv6Regex:()=>tn,findUrlRegex:()=>an,findUsernameRegex:()=>Tn,formatBytes:()=>J,formatCustomTimer:()=>f,formatDayTimer:()=>g,formatTimer:()=>y,genFibonacciSeq:()=>G,getAge:()=>K,getBrowserCssPrefix:()=>Wi,getBrowserPings:()=>Vi,getDuckTyping:()=>qi,getElsCollDetails:()=>bt,getElsCollDirDepth:()=>wt,getElsCollOverlap:()=>mt,getElsCollOverlapPos:()=>ft,getElsColliding:()=>dt,getElsPerfColliding:()=>pt,getElsRelativeCenterOffset:()=>gt,getLatestBackupPath:()=>Be,getObjTypeOrder:()=>R,getObjTypeRegistry:()=>P,getPercentage:()=>U,getRectCenter:()=>yt,getSimplePerc:()=>V,getTimeDuration:()=>m,getUserTimeFormat:()=>p,hashText:()=>se,installWindowHiddenScript:()=>Se,ipv4Regex:()=>Ks,ipv6Regex:()=>Zs,isAnyClassInstance:()=>x,isBrowser:()=>$i,isBrowserAgent:()=>Bi,isClass:()=>T,isClassInstance:()=>S,isDirEmpty:()=>_e,isDirEmptyAsync:()=>Xe,isFullScreenMode:()=>$,isJsonObject:()=>v,isObjType:()=>L,isScreenFilled:()=>O,isValidEmail:()=>dn,isValidGlob:()=>On,isValidIPv4:()=>Js,isValidIPv6:()=>en,isValidObj:()=>E,isValidUrl:()=>on,isValidUsername:()=>En,jsonFilter:()=>Ft,jsonFilterByKeys:()=>Bt,jsonFilterRecursive:()=>zt,listDirs:()=>$e,listDirsAsync:()=>Ze,listFiles:()=>Oe,listFilesAsync:()=>Qe,makeSegmentExtractor:()=>os,multiplyArrayBlocks:()=>u,objType:()=>N,objTypeName:()=>M,offFullScreenChange:()=>W,onFullScreenChange:()=>B,parseMediaMetadata:()=>or,readBase64Blob:()=>ge,readFileBlob:()=>ye,readJsonBlob:()=>we,readJsonFile:()=>Ie,renameFileAddPrefixSuffix:()=>Ue,renameFileBatch:()=>qe,renameFileNormalizeCase:()=>Ke,renameFilePadNumbers:()=>Je,renameFileRegex:()=>Ve,reorderObjTypeOrder:()=>D,requestFullScreen:()=>H,restoreLatestBackup:()=>We,ruleOfThree:()=>q,safeTextTrim:()=>re,saveJsonFile:()=>be,segmentExtractorV1:()=>as,shuffleArray:()=>h,signPluginIdentity:()=>bs,toTitleCase:()=>Z,toTitleCaseLowerFirst:()=>ee,trapezoid:()=>Di,tryDeleteFile:()=>Re,urlRegex:()=>nn,urlStringRegexBuilder:()=>sn,usernameRegex:()=>vn,usernameStringRegexBuilder:()=>gn,valFetchMediaContent:()=>ir,valMediaContentMetadata:()=>sr,verifyPluginSignature:()=>Ss,waitForTrue:()=>Cr,writeJsonFile:()=>De,writeTextFile:()=>je});var e=r.cw(function(e,t){var r,i="object"==typeof Reflect?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise(function(r,i){function s(r){e.removeListener(t,n),i(r)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}y(e,t,n,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&y(e,"error",t,{once:!0})}(e,s)})},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,r,i){var s,n,o,a;if(l(r),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]),void 0===o)o=n[t]=r,++e._eventsCount;else if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(s=h(e))>0&&o.length>s&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,a=u,console&&console.warn&&console.warn(a)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=c.bind(i);return s.listener=r,i.wrapFn=s,s}function p(e,t,r){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):f(s,s.length)}function m(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function f(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function y(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(n){i.once&&e.removeEventListener(t,s),r(n)})}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return h(this)},o.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=n[e];if(void 0===l)return!1;if("function"==typeof l)s(l,this,t);else{var h=l.length,u=f(l,h);for(r=0;r<h;++r)s(u[r],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return l(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var r,i,s,n,o;if(l(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length-1;n>=0;n--)if(r[n]===t||r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,n=Object.keys(r);for(i=0;i<n.length;++i)"removeListener"!==(s=n[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},o.prototype.listeners=function(e){return p(this,e,!0)},o.prototype.rawListeners=function(e){return p(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):m.call(e,t)},o.prototype.listenerCount=m,o.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}}),t=r.cw(function(e,t){var i=r(606);function s(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function n(e,t){for(var r,i="",s=0,n=-1,o=0,a=0;a<=e.length;++a){if(a<e.length)r=e.charCodeAt(a);else{if(47===r)break;r=47}if(47===r){if(n===a-1||1===o);else if(n!==a-1&&2===o){if(i.length<2||2!==s||46!==i.charCodeAt(i.length-1)||46!==i.charCodeAt(i.length-2))if(i.length>2){var l=i.lastIndexOf("/");if(l!==i.length-1){-1===l?(i="",s=0):s=(i=i.slice(0,l)).length-1-i.lastIndexOf("/"),n=a,o=0;continue}}else if(2===i.length||1===i.length){i="",s=0,n=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",s=2)}else i.length>0?i+="/"+e.slice(n+1,a):i=e.slice(n+1,a),s=a-n-1;n=a,o=0}else 46===r&&-1!==o?++o:o=-1}return i}var o={resolve:function(){for(var e,t="",r=!1,o=arguments.length-1;o>=-1&&!r;o--){var a;o>=0?a=arguments[o]:(void 0===e&&(e=i.cwd()),a=e),s(a),0!==a.length&&(t=a+"/"+t,r=47===a.charCodeAt(0))}return t=n(t,!r),r?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(s(e),0===e.length)return".";var t=47===e.charCodeAt(0),r=47===e.charCodeAt(e.length-1);return 0!==(e=n(e,!t)).length||t||(e="."),e.length>0&&r&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return s(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,t=0;t<arguments.length;++t){var r=arguments[t];s(r),r.length>0&&(void 0===e?e=r:e+="/"+r)}return void 0===e?".":o.normalize(e)},relative:function(e,t){if(s(e),s(t),e===t)return"";if((e=o.resolve(e))===(t=o.resolve(t)))return"";for(var r=1;r<e.length&&47===e.charCodeAt(r);++r);for(var i=e.length,n=i-r,a=1;a<t.length&&47===t.charCodeAt(a);++a);for(var l=t.length-a,h=n<l?n:l,u=-1,c=0;c<=h;++c){if(c===h){if(l>h){if(47===t.charCodeAt(a+c))return t.slice(a+c+1);if(0===c)return t.slice(a+c)}else n>h&&(47===e.charCodeAt(r+c)?u=c:0===c&&(u=0));break}var d=e.charCodeAt(r+c);if(d!==t.charCodeAt(a+c))break;47===d&&(u=c)}var p="";for(c=r+u+1;c<=i;++c)c!==i&&47!==e.charCodeAt(c)||(0===p.length?p+="..":p+="/..");return p.length>0?p+t.slice(a+u):(a+=u,47===t.charCodeAt(a)&&++a,t.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(s(e),0===e.length)return".";for(var t=e.charCodeAt(0),r=47===t,i=-1,n=!0,o=e.length-1;o>=1;--o)if(47===(t=e.charCodeAt(o))){if(!n){i=o;break}}else n=!1;return-1===i?r?"/":".":r&&1===i?"//":e.slice(0,i)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');s(e);var r,i=0,n=-1,o=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,l=-1;for(r=e.length-1;r>=0;--r){var h=e.charCodeAt(r);if(47===h){if(!o){i=r+1;break}}else-1===l&&(o=!1,l=r+1),a>=0&&(h===t.charCodeAt(a)?-1===--a&&(n=r):(a=-1,n=l))}return i===n?n=l:-1===n&&(n=e.length),e.slice(i,n)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!o){i=r+1;break}}else-1===n&&(o=!1,n=r+1);return-1===n?"":e.slice(i,n)},extname:function(e){s(e);for(var t=-1,r=0,i=-1,n=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(47!==l)-1===i&&(n=!1,i=a+1),46===l?-1===t?t=a:1!==o&&(o=1):-1!==t&&(o=-1);else if(!n){r=a+1;break}}return-1===t||-1===i||0===o||1===o&&t===i-1&&t===r+1?"":e.slice(t,i)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+i:r+"/"+i:i}(0,e)},parse:function(e){s(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var r,i=e.charCodeAt(0),n=47===i;n?(t.root="/",r=1):r=0;for(var o=-1,a=0,l=-1,h=!0,u=e.length-1,c=0;u>=r;--u)if(47!==(i=e.charCodeAt(u)))-1===l&&(h=!1,l=u+1),46===i?-1===o?o=u:1!==c&&(c=1):-1!==o&&(c=-1);else if(!h){a=u+1;break}return-1===o||-1===l||0===c||1===c&&o===l-1&&o===a+1?-1!==l&&(t.base=t.name=0===a&&n?e.slice(1,l):e.slice(a,l)):(0===a&&n?(t.name=e.slice(1,o),t.base=e.slice(1,l)):(t.name=e.slice(a,o),t.base=e.slice(a,l)),t.ext=e.slice(o,l)),a>0?t.dir=e.slice(0,a-1):n&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};o.posix=o,e.exports=o}),s={};r.r(s),r.d(s,{iu:()=>it,cq:()=>st,P8:()=>at,BO:()=>lt,eh:()=>ht,L2:()=>ot,lP:()=>nt,Kr:()=>rt,wE:()=>ut,D6:()=>ct,PN:()=>bt,t_:()=>wt,aI:()=>mt,ej:()=>ft,kx:()=>dt,Pd:()=>pt,NW:()=>gt,Qv:()=>yt});var n={};r.r(n),r.d(n,{areElsCollBottom:()=>it,areElsCollLeft:()=>st,areElsCollPerfBottom:()=>at,areElsCollPerfLeft:()=>lt,areElsCollPerfRight:()=>ht,areElsCollPerfTop:()=>ot,areElsCollRight:()=>nt,areElsCollTop:()=>rt,areElsColliding:()=>ut,areElsPerfColliding:()=>ct,getElsCollDetails:()=>bt,getElsCollDirDepth:()=>wt,getElsCollOverlap:()=>mt,getElsCollOverlapPos:()=>ft,getElsColliding:()=>dt,getElsPerfColliding:()=>pt,getElsRelativeCenterOffset:()=>gt,getRectCenter:()=>yt});var o={};r.r(o),r.d(o,{q:()=>os,N:()=>as});var a={};r.r(a),r.d(a,{makeSegmentExtractor:()=>os,segmentExtractorV1:()=>as});const l=class{constructor(e,t){if("number"!=typeof e||Number.isNaN(e))throw new Error("giveExp must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("expLevel must be a valid number");this.giveExp=e,this.expLevel=t}createUser(){return{exp:0,level:1,totalExp:0}}validateUser(e){if("number"!=typeof e.exp||Number.isNaN(e.exp))throw new Error("exp must be a valid number");if("number"!=typeof e.level||Number.isNaN(e.level))throw new Error("level must be a valid number");if(e.level<1)throw new Error("level must be at least 1");if("number"!=typeof e.totalExp||Number.isNaN(e.totalExp))throw new Error("totalExp must be a valid number")}isValidUser(e){return!("number"!=typeof e.exp||Number.isNaN(e.exp)||"number"!=typeof e.level||Number.isNaN(e.level)||e.level<1||"number"!=typeof e.totalExp||Number.isNaN(e.totalExp))}getGiveExpBase(){if("number"!=typeof this.giveExp||Number.isNaN(this.giveExp))throw new Error("giveExp must be a valid number");return this.giveExp}getExpLevelBase(){if("number"!=typeof this.expLevel||Number.isNaN(this.expLevel))throw new Error("expLevel must be a valid number");return this.expLevel}expValidator(e){const t=this.getExpLevelBase();this.validateUser(e);let r=0;const i=t*e.level;return e.exp>=i&&(e.level++,r=e.exp-i,e.exp=0,r>0)?this.give(e,r,"extra"):e.exp<1&&e.level>1&&(e.level--,r=Math.abs(e.exp),e.exp=t*e.level,r>0)?this.remove(e,r,"extra"):e}getTotalExp(e){this.validateUser(e);let t=0;for(let r=1;r<=e.level;r++)t+=this.getExpLevelBase()*r;return t+=e.exp,t}expGenerator(e=1){if("number"!=typeof e||Number.isNaN(e))throw new Error("multi must be a valid number");return Math.floor(Math.random()*this.getGiveExpBase())*e}getMissingExp(e){return this.getProgress(e)-e.exp}progress(e){return this.getProgress(e)}getProgress(e){return this.validateUser(e),this.getExpLevelBase()*e.level}set(e,t){if("number"!=typeof t||Number.isNaN(t))throw new Error("value must be a valid number");return e.exp=t,this.expValidator(e),e.totalExp=this.getTotalExp(e),e}give(e,t=0,r="add",i=1){if("number"!=typeof i||Number.isNaN(i))throw new Error("multi must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("extraExp must be a valid number");if("string"!=typeof r)throw new Error("type must be a valid string");return"add"===r?e.exp+=this.expGenerator(i)+t:"extra"===r&&(e.exp+=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}remove(e,t=0,r="add",i=1){if("number"!=typeof i||Number.isNaN(i))throw new Error("multi must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("extraExp must be a valid number");if("string"!=typeof r)throw new Error("type must be a valid string");return"add"===r?e.exp-=this.expGenerator(i)+t:"extra"===r&&(e.exp-=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}};function h(e){if(!Array.isArray(e))throw new TypeError("Argument 'items' must be an array.");let t,r=e.length;for(;0!==r;)t=Math.floor(Math.random()*r),r--,[e[r],e[t]]=[e[t],e[r]];return e}function u(e,t){if(!Array.isArray(e))throw new TypeError("Argument 'phases' must be an array.");if(!Array.isArray(t))throw new TypeError("Argument 'counts' must be an array.");if(e.length!==t.length)throw new RangeError("The 'phases' and 'counts' arrays must have the same length.");const r=[];for(let i=0;i<e.length;i++){if("number"!=typeof t[i]||Number.isNaN(t[i]))throw new TypeError(`Element at counts[${i}] must be a valid number.`);for(let s=0;s<t[i];s++)r.push(e[i])}return r}function c(e,t){if(!Array.isArray(e))throw new TypeError("Argument 'oldItems' must be an array.");if(!Array.isArray(t))throw new TypeError("Argument 'newItems' must be an array.");const r=e.filter(e=>!t.includes(e));return{added:t.filter(t=>!e.includes(t)),removed:r}}function d(e,t=!1){if(null!=e&&"string"!=typeof e)throw new TypeError("Argument 'item' must be a string or null.");if("boolean"!=typeof t)throw new TypeError("Argument 'isReverse' must be a boolean.");return t?function(t,r){return(e?t[e]:t)>(e?r[e]:r)?-1:(e?t[e]:t)<(e?r[e]:r)?1:0}:function(t,r){return(e?t[e]:t)<(e?r[e]:r)?-1:(e?t[e]:t)>(e?r[e]:r)?1:0}}function p(){const e=new Intl.DateTimeFormat(void 0,{hour:"numeric"}).resolvedOptions().hourCycle;return e?.startsWith("h12")?12:24}function m(e=new Date,t="asSeconds",r=null){if(!(e instanceof Date))throw new TypeError("The 'timeData' argument must be an instance of Date.");if("string"!=typeof t)throw new TypeError("The 'durationType' argument must be a string.");const i=["asMilliseconds","asSeconds","asMinutes","asHours","asDays"];if(!i.includes(t))throw new RangeError(`The 'durationType' must be one of: ${i.join(", ")}.`);if(null!==r&&!(r instanceof Date))throw new TypeError("The 'now' argument must be an instance of Date or null.");const s=r instanceof Date?r:new Date,n=e.getTime()-s.getTime();switch(t){case"asMilliseconds":return n;case"asSeconds":default:return n/1e3;case"asMinutes":return n/6e4;case"asHours":return n/36e5;case"asDays":return n/864e5}}function f(e,t="seconds",r="{time}"){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'totalSeconds' argument must be a valid number.");if("string"!=typeof t)throw new TypeError("The 'level' argument must be a string.");const i=["seconds","minutes","hours","days","months","years"];if(!i.includes(t))throw new RangeError(`The 'level' must be one of: ${i.join(", ")}.`);if("string"!=typeof r)throw new TypeError("The 'format' argument must be a string.");e=Math.max(0,Math.floor(e));const s=i.indexOf(t),n=s>=5,o=s>=4,a=s>=3,l=s>=2,h=s>=1,u=s>=0,c={years:n?0:NaN,months:o?0:NaN,days:a?0:NaN,hours:l?0:NaN,minutes:h?0:NaN,seconds:u?0:NaN,total:NaN};let d=e;if(n||o||a){const e=new Date(1980,0,1),t=new Date(e.getTime()+1e3*d),r=new Date(e);if(n)for(;new Date(r.getFullYear()+1,r.getMonth(),r.getDate()).getTime()<=t.getTime();)r.setFullYear(r.getFullYear()+1),c.years++;if(o)for(;new Date(r.getFullYear(),r.getMonth()+1,r.getDate()).getTime()<=t.getTime();)r.setMonth(r.getMonth()+1),c.months++;if(a)for(;new Date(r.getFullYear(),r.getMonth(),r.getDate()+1).getTime()<=t.getTime();)r.setDate(r.getDate()+1),c.days++;d=Math.floor((t.getTime()-r.getTime())/1e3)}l&&(c.hours=Math.floor(d/3600),d%=3600),h&&(c.minutes=Math.floor(d/60),d%=60),u&&(c.seconds=d),c.total=+e.toFixed(2).replace(/\.00$/,"");const p=e=>{const t="string"==typeof e?parseInt(e):e;return Number.isNaN(t)?"NaN":String(t).padStart(2,"0")},m=[l?p(c.hours):null,h?p(c.minutes):null,u?p(c.seconds):null].filter(e=>null!==e).join(":");return r.replace(/\{years\}/g,String(c.years)).replace(/\{months\}/g,String(c.months)).replace(/\{days\}/g,String(c.days)).replace(/\{hours\}/g,p(c.hours)).replace(/\{minutes\}/g,p(c.minutes)).replace(/\{seconds\}/g,p(c.seconds)).replace(/\{time\}/g,m).replace(/\{total\}/g,String(c.total)).trim()}function y(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'seconds' argument must be a valid number.");return f(e,"hours","{hours}:{minutes}:{seconds}")}function g(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'seconds' argument must be a valid number.");return f(e,"days","{days}d {hours}:{minutes}:{seconds}")}function w(e,t="milliseconds"){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'totalMs' argument must be a valid number.");if("string"!=typeof t)throw new TypeError("The 'level' argument must be a string.");const r=["milliseconds","seconds","minutes","hours","days","months","years"];if(!r.includes(t))throw new RangeError(`The 'level' must be one of: ${r.join(", ")}.`);e=Math.max(0,Math.floor(e));const i=r.indexOf(t),s=i>=6,n=i>=5,o=i>=4,a=i>=3,l=i>=2,h=i>=1,u=i>=0,c={years:s?0:NaN,months:n?0:NaN,days:o?0:NaN,hours:a?0:NaN,minutes:l?0:NaN,seconds:h?0:NaN,milliseconds:u?0:NaN,total:NaN};let d=e;if(s||n||o){const e=new Date(1980,0,1),t=new Date(e.getTime()+d),r=new Date(e);if(s)for(;new Date(r.getFullYear()+1,r.getMonth(),r.getDate()).getTime()<=t.getTime();)r.setFullYear(r.getFullYear()+1),c.years++;if(n)for(;new Date(r.getFullYear(),r.getMonth()+1,r.getDate()).getTime()<=t.getTime();)r.setMonth(r.getMonth()+1),c.months++;if(o)for(;new Date(r.getFullYear(),r.getMonth(),r.getDate()+1).getTime()<=t.getTime();)r.setDate(r.getDate()+1),c.days++;d=t.getTime()-r.getTime()}return a&&(c.hours=Math.floor(d/36e5),d%=36e5),l&&(c.minutes=Math.floor(d/6e4),d%=6e4),h&&(c.seconds=Math.floor(d/1e3),d%=1e3),u&&(c.milliseconds=d),c.total=+e,c}function b(e){if(!Array.isArray(e)&&!v(e))throw new TypeError("Argument must be either an Array or a pure JSON Object.");return Array.isArray(e)?e.length:Object.keys(e).length}function v(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e)}function E(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}const T=e=>{if("function"!=typeof e)throw new TypeError("The 'target' argument must be a function. Received: "+typeof e);try{return e(),!1}catch(e){return e instanceof TypeError&&e.message.includes("Class constructor")}};function S(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!1;if("function"!=typeof e.constructor)return!1;const r=e.constructor.toString();return/^\s*class\b/.test(r)}function x(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return null!==t&&t!==Object.prototype&&"function"==typeof e.constructor}const A="undefined"!=typeof window&&void 0!==window.document,C={items:{},order:[]};function I(e,t){if("object"!=typeof e||null===e)throw new TypeError("Argument 'ni' must be an object or an array.");if(void 0!==t&&"number"!=typeof t)throw new TypeError("Argument 'index' must be a number.");const r=[];let i;i=Array.isArray(e)?e.length>0&&Array.isArray(e[0])?e:e.length>0?[e]:[]:Object.entries(e);for(const e of i){if(!Array.isArray(e)||e.length<2)throw new TypeError("Each item in the input must be a [key, function] pair.");const[i,s,n]=e;if(void 0!==n&&"function"!=typeof n)throw new TypeError(`Cloner for key '${i}' must be a function.`);const o="function"==typeof n?n:e=>e;if("string"!=typeof i)throw new TypeError("Validator key must be a string.");if("function"!=typeof s)throw new TypeError(`Validator for key '${i}' must be a function.`);if(!C.items.hasOwnProperty(i)){C.items[i]={validator:s,cloner:o};let e="number"==typeof t?t:-1;if(-1===e){const t=C.order.indexOf("object");e=t>-1?t:C.order.length}e=Math.min(Math.max(0,e),C.order.length),C.order.splice(e,0,i),r.push(i)}}return r}function D(e){if(!Array.isArray(e))throw new TypeError("Argument 'newOrder' must be an array of strings.");if(!e.every(e=>"string"==typeof e))throw new TypeError("All elements in 'newOrder' must be strings.");const t=[...C.order];return!!e.every(e=>t.includes(e))&&(C.order=e.slice(),!0)}function k(){return[...C.order]}const M=e=>{if(null===e)return"null";for(const t of C.order)if("function"!=typeof C.items[t].validator||C.items[t].validator(e))return t;return"unknown"};function L(e,t){if("string"!=typeof t)throw new TypeError("Argument 'type' must be a string.");return M(e)===t.toLowerCase()}function N(e,t){if(void 0===e)return null;if(void 0!==t&&"string"!=typeof t)throw new TypeError("Argument 'type' must be a string.");const r=M(e);return"string"==typeof t?r===t.toLowerCase():r}function _(e){const t={valid:null,type:null};for(const r of C.order)if("function"==typeof C.items[r].validator){const i=C.items[r].validator(e);if(i){t.valid=i,t.type=r;break}}return t}function P(){return Object.fromEntries(Object.entries(C.items).map(([e,t])=>[e,{...t}]))}const R=()=>[...C.order];I([["undefined",e=>void 0===e],["null",e=>null===e],["boolean",e=>"boolean"==typeof e],["number",e=>"number"==typeof e&&!Number.isNaN(e)],["nannumber",e=>"number"==typeof e&&Number.isNaN(e)],["bigint",e=>"bigint"==typeof e],["string",e=>"string"==typeof e],["symbol",e=>"symbol"==typeof e],["function",e=>"function"==typeof e]]),I(["array",e=>Array.isArray(e),(e,t,r)=>e.map(e=>t?r.clone(e,t):e)]),A&&I(["file",e=>"undefined"!=typeof File&&e instanceof File,e=>new File([e],e.name,{type:e.type,lastModified:e.lastModified})]),I(["date",e=>e instanceof Date,e=>new Date(e.getTime())]),I(["regexp",e=>e instanceof RegExp,e=>new RegExp(e.source,e.flags)]),I(["map",e=>e instanceof Map,(e,t,r)=>{const i=new Map;for(const[s,n]of e.entries())i.set(s,t?r.clone(n,t):n);return i}]),I(["set",e=>e instanceof Set,(e,t,r)=>{const i=new Set;for(const s of e)i.add(t?r.clone(s,t):s);return i}]),I([["weakmap",e=>e instanceof WeakMap],["weakset",e=>e instanceof WeakSet],["promise",e=>e instanceof Promise]]),I(["url",e=>e instanceof URL,e=>new URL(e.href)]),A&&I(["htmlelement",e=>"undefined"!=typeof HTMLElement&&e instanceof HTMLElement,e=>e.cloneNode(!0)]),I(["object",e=>v(e),(e,t,r)=>{const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t?r.clone(e[s],t):e[s]);return i}]);const j=()=>!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitIsFullScreen||document.mozFullScreen),O=()=>window.innerHeight===screen.height&&window.innerWidth===screen.width,$=()=>j()||O(),H=e=>new Promise(async(t,r)=>{const i=document.documentElement;try{i.requestFullscreen?await i.requestFullscreen(e):i.mozRequestFullScreen?i.mozRequestFullScreen(e):i.webkitRequestFullScreen?i.webkitRequestFullScreen(e):i.msRequestFullscreen&&i.msRequestFullscreen(e),t()}catch(e){r(e)}}),F=()=>new Promise((e,t)=>{if(document.exitFullscreen)document.exitFullscreen().then(e).catch(t);else try{if(document.mozCancelFullScreen)document.mozCancelFullScreen();else if(document.webkitCancelFullScreen)document.webkitCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Fullscreen API is not supported");document.msExitFullscreen()}e()}catch(e){t(e)}}),z=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],B=(e,t)=>{z.forEach(r=>{document.addEventListener(r,e,t)})},W=(e,t)=>{z.forEach(r=>{document.removeEventListener(r,e,t)})};function q(e,t,r,i=!1){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("val1 must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("val2 must be a finite number.");if("number"!=typeof r||!Number.isFinite(r))throw new TypeError("val3 must be a finite number.");if("boolean"!=typeof i)throw new TypeError("inverse must be a boolean.");return i?Number(e*t)/r:Number(r*t)/e}function V(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("price must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("percentage must be a finite number.");return e*(t/100)}function U(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("part must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("total must be a finite number.");return 0===t?0:e/t*100}function K(e=0,t=null){if("number"!=typeof e&&"string"!=typeof e&&!(e instanceof Date))throw new TypeError("timeData must be a number, string, or Date object.");if(null!==t&&!(t instanceof Date))throw new TypeError("now must be a Date object or null.");const r=new Date(e);if(Number.isNaN(r.getTime()))return null;const i=t instanceof Date?t:new Date;let s=i.getFullYear()-r.getFullYear();const n=i.getMonth(),o=r.getMonth(),a=i.getDate(),l=r.getDate();return(n<o||n===o&&a<l)&&s--,Math.abs(s)}function J(e,t=null,r=null){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new TypeError("bytes must be a positive number.");if(0===e)return{unit:"Bytes",value:0};if(null!==t&&("number"!=typeof t||!Number.isFinite(t)))throw new TypeError("decimals must be a number or null.");const i=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"];if(null!==r){if("string"!=typeof r)throw new TypeError("maxUnit must be a string or null.");if(!i.includes(r))throw new RangeError(`maxUnit must be one of: ${i.join(", ")}`)}const s=r&&i.includes(r)?i.indexOf(r):i.length-1,n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),s);let o=e/Math.pow(1024,n);if(null!==t){const e=t<0?0:t;o=parseFloat(o.toFixed(e))}return{unit:i[n],value:o}}function G({baseValues:e=[0,1],length:t=10,combiner:r=(e,t)=>e+t}={}){if(!Array.isArray(e)||2!==e.length||!e.every(e=>"number"==typeof e))throw new Error("baseValues must be an array of exactly two numbers.");if("number"!=typeof t||!Number.isInteger(t))throw new RangeError("length must be an integer.");if("function"!=typeof r)throw new TypeError("combiner must be a function.");const i=[...e.slice(0,2)];for(let e=2;e<t;e++){const t=r(i[e-2],i[e-1],e);i.push(t)}return i}function Y(e,t){if("number"!=typeof e||Number.isNaN(e)||!Number.isFinite(e))throw new TypeError("Original market cap must be a finite number.");if("number"!=typeof t||Number.isNaN(t)||!Number.isFinite(t))throw new TypeError("Circulating supply must be a finite number.");if(t<=0)throw new RangeError("Circulating supply must be greater than zero.");return e/t}function X(e,t,r){if("number"!=typeof r||Number.isNaN(r)||!Number.isFinite(r))throw new TypeError("New market cap must be a finite number.");const i=Y(e,t),s="number"==typeof r?r/t:NaN;return{originalPrice:i,newPrice:s,priceChangePercent:"number"==typeof r?(s-i)/i*100:NaN}}async function Q(e,t,r){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);if(!(t instanceof RegExp))throw new TypeError("Expected a RegExp for 'regex', but received "+typeof t);if("function"!=typeof r)throw new TypeError("Expected a function for 'asyncFn', but received "+typeof r);const i=[];e.replace(t,(e,...t)=>(i.push(r(e,...t)),e));const s=await Promise.all(i);return e.replace(t,()=>s.shift())}function Z(e){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);return e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase())}function ee(e){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);const t=e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase());return t.charAt(0).toLowerCase()+t.slice(1)}function te({key:e="a",className:t="detect-made-by-ai"}={}){if("undefined"==typeof HTMLElement)throw new Error("[AiMarkerShortcut] Environment does not support the DOM. This function must be run in a browser.");if("string"!=typeof e)throw new TypeError("Expected a string for 'config.key', but received "+typeof e);if("string"!=typeof t)throw new TypeError("Expected a string for 'config.className', but received "+typeof t);const r=function(r){if(r.ctrlKey&&r.altKey&&r.key.toLowerCase()===e){if(r.preventDefault(),!document.body)return void console.warn("[AiMarkerShortcut] <body> element not found. Cannot toggle class. Ensure the DOM is fully loaded when using the shortcut.");document.body.classList.toggle(t)}};return document.addEventListener("keydown",r),r}function re(e,t,r=.6){if("string"!=typeof e)throw new TypeError("Expected a string for 'text', but received "+typeof e);if(!Number.isInteger(t)||t<=0)throw new TypeError(`Expected 'limit' to be a positive integer, but received ${t}`);if("number"!=typeof r||r<0||r>1)throw new TypeError(`Expected 'safeCutZone' to be a number between 0 and 1, but received ${r}`);let i=e.trim();if(i.length>t){const e=i.lastIndexOf(" ",t);return e>0&&e>=t*r?`${i.substring(0,e).trim()}...`:`${i.substring(0,t).trim()}...`}return i}function ie(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Expected an object for 'oldStrings', but received "+(null===e?"null":typeof e));if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("Expected an object for 'newStrings', but received "+(null===t?"null":typeof t));const r={added:{},removed:{},modified:{}};for(const i in e)i in t?e[i]!==t[i]&&(r.modified[i]={old:e[i],new:t[i]}):r.removed[i]=e[i];for(const i in t)i in e||(r.added[i]=t[i]);return r}async function se(e,t){if("string"!=typeof e)throw new TypeError('The "text" parameter must be a string.');const r=(new TextEncoder).encode(e),i=await crypto.subtle.digest(t,r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}class ne{#e;static#t={default:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""},solarized:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""},monokai:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""}};constructor(e={}){this.#e={...ne.#t.default,...e}}#r(e,t){const r=[];e=(e=(e=e.replace(/(?<!")\b(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\b(?!")/g,`${t.number}$1${t.reset}`)).replace(/"([^"]+)":/g,(e,t)=>{const i=`___KEY${r.length}___`;return r.push({marker:i,key:t}),`${i}:`})).replace(/"(?:\\.|[^"\\])*?"/g,e=>{const r=e.slice(1,-1);return/^(https?|ftp):\/\/[^\s]+$/i.test(r)?`${t.string_url}${e}${t.reset}`:/^(true|false|null)$/.test(r)?`${t.string_bool}${e}${t.reset}`:/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r)?`${t.string_number}${e}${t.reset}`:`${t.string}${e}${t.reset}`});for(const{marker:i,key:s}of r){const r=new RegExp(i,"g");e=e.replace(r,`${t.key}"${s}"${t.reset}`)}return(e=(e=(e=(e=e.replace(/(?<!")\b(true|false)\b(?!")/g,`${t.boolean}$1${t.reset}`)).replace(/(?<!")\bnull\b(?!")/g,`${t.null}null${t.reset}`)).replace(/\[Circular\]/g,`${t.special}[Circular]${t.reset}`)).replace(/\[undefined\]/g,`${t.special}[undefined]${t.reset}`)).replace(/"function.*?[^\\]"/gs,`${t.func}$&${t.reset}`)}colorize(e,t={}){const r={...this.#e,...t};return this.#r(e,r)}getColors(){return{...this.#e}}updateColors(e){Object.assign(this.#e,e)}resetColors(){this.#e={...ne.#t.default}}loadColorPreset(e){const t=ne.#t[e];if(!t)throw new Error(`Preset "${e}" not found.`);this.#e={...t}}saveColorPreset(e,t){ne.#t[e]={...t}}getAvailablePresets(){return Object.keys(ne.#t)}}const oe=ne,ae=class{#i=[];#s=!1;#n={};#o=new Set;isRunning(){return this.#s}async#a(e){if(e&&"function"==typeof e.task&&"function"==typeof e.resolve&&"function"==typeof e.reject){const{task:t,resolve:r,reject:i,delay:s,id:n}=e;try{if(n&&this.#o.has(n))return i(new Error("The function was canceled on TinyPromiseQueue.")),this.#o.delete(n),this.#s=!1,void this.#l();s&&n&&await new Promise(e=>{const t=setTimeout(()=>{delete this.#n[n],e(null)},s);this.#n[n]=t}),r(await t())}catch(e){i(e)}finally{this.#s=!1,this.#l()}}}async#h(){const e=[];for(;this.#i.length&&"POINT_MARKER"===this.#i[0]?.marker;)e.push(this.#i.shift());if(0===e.length)return this.#s=!1,void this.#l();await Promise.all(e.map(({task:e,resolve:t,reject:r,id:i})=>new Promise(async s=>{if(i&&this.#o.has(i))return this.#o.delete(i),r(new Error("The function was canceled on TinyPromiseQueue.")),void s(!0);await e().then(t).catch(r),s(!0)}))),this.#s=!1,this.#l()}async#l(){if(!this.#s&&0!==this.#i.length)if(this.#s=!0,"string"!=typeof this.#i[0]?.marker||"POINT_MARKER"!==this.#i[0]?.marker){const e=this.#i.shift();this.#a(e)}else this.#h()}getIndexById(e){return this.#i.findIndex(t=>t.id===e)}getQueuedIds(){return this.#i.map((e,t)=>({index:t,id:e.id})).filter(e=>"string"==typeof e.id)}reorderQueue(e,t){if("number"!=typeof e||"number"!=typeof t||e<0||t<0||e>=this.#i.length||t>=this.#i.length)return;const[r]=this.#i.splice(e,1);this.#i.splice(t,0,r)}async enqueuePoint(e,t){if("function"!=typeof e)return Promise.reject(new Error("Task must be a function returning a Promise."));if(void 0!==t&&"string"!=typeof t)throw new Error('The "id" parameter must be a string.');return this.#s?new Promise((r,i)=>{this.#i.push({marker:"POINT_MARKER",task:e,resolve:r,reject:i,id:t}),this.#l()}):e()}enqueue(e,t,r){if("function"!=typeof e)return Promise.reject(new Error("Task must be a function returning a Promise."));if(void 0!==t&&("number"!=typeof t||t<0))return Promise.reject(new Error("Delay must be a positive number or undefined."));if(void 0!==r&&"string"!=typeof r)throw new Error('The "id" parameter must be a string.');return new Promise((i,s)=>{this.#i.push({task:e,resolve:i,reject:s,id:r,delay:t}),this.#l()})}cancelTask(e){if("string"!=typeof e)throw new Error('The "id" parameter must be a string.');let t=!1;e in this.#n&&(clearTimeout(this.#n[e]),delete this.#n[e],t=!0);const r=this.getIndexById(e);if(-1!==r){const[e]=this.#i.splice(r,1);e?.reject?.(new Error("The function was canceled on TinyPromiseQueue.")),t=!0}return t&&this.#o.add(e),t}},le=e=>t=>{if(t)throw new Error(`This ${e} instance has been destroyed and can no longer be used.`)},he=le("TinyRateLimiter"),ue=class{#u=!1;get destroyed(){return this.#u}#c=null;#d=null;#p=null;#m=null;#f=null;#y=null;groupData=new Map;lastSeen=new Map;userToGroup=new Map;groupFlags=new Map;groupTTL=new Map;#g=null;setOnMemoryExceeded(e){if(he(this.#u),"function"!=typeof e)throw new Error("onMemoryExceeded must be a function");this.#g=e}clearOnMemoryExceeded(){he(this.#u),this.#g=null}#w=null;setOnGroupExpired(e){if(he(this.#u),"function"!=typeof e)throw new Error("onGroupExpired must be a function");this.#w=e}clearOnGroupExpired(){he(this.#u),this.#w=null}constructor({maxHits:e,interval:t,cleanupInterval:r,maxIdle:i=3e5,maxMemory:s=1e5}){const n=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1&&Number.isInteger(e),o=n(e),a=n(t),l=n(r),h=n(i);if(!o&&!a)throw new Error("RateLimiter requires at least one valid option: 'maxHits' or 'interval'.");if(void 0!==e&&!o)throw new Error("'maxHits' must be a positive integer if defined.");if(void 0!==t&&!a)throw new Error("'interval' must be a positive integer in milliseconds if defined.");if(void 0!==r&&!l)throw new Error("'cleanupInterval' must be a positive integer in milliseconds if defined.");if(!h)throw new Error("'maxIdle' must be a positive integer in milliseconds.");if("number"==typeof s&&Number.isFinite(s)&&s>0)this.#c=Math.floor(s);else{if(null!=s)throw new Error("maxMemory must be a positive number or null");this.#c=null}this.#p=o?e:null,this.#m=a?t:null,this.#f=l?r:null,this.#y=i,null!==this.#f&&(this.#d=setInterval(()=>this._cleanup(),this.#f))}isGroupId(e){he(this.#u);const t=this.groupFlags.get(e);return"boolean"==typeof t&&t}getUsersInGroup(e){he(this.#u);const t=[];for(const[r,i]of this.userToGroup.entries())i===e&&t.push(r);return t}setGroupTTL(e,t){if(he(this.#u),"number"!=typeof t||!Number.isFinite(t)||t<=0)throw new Error("TTL must be a positive number in milliseconds");this.groupTTL.set(e,t)}getGroupTTL(e){return he(this.#u),this.groupTTL.get(e)??null}deleteGroupTTL(e){he(this.#u),this.groupTTL.delete(e)}assignToGroup(e,t){he(this.#u);const r=this.userToGroup.get(e);if(r&&r!==t)throw new Error(`User ${e} is already assigned to group ${r}`);if(r===t)return;const i=this.groupData.get(e);if(this.isGroupId(e)){for(const[r,i]of this.userToGroup.entries())i===e&&this.userToGroup.set(r,t);this.userToGroup.delete(e)}else this.userToGroup.set(e,t);if(!i)return;const s=this.groupData.get(t);if(s)for(const e of i)s.push(e);else{const e=[];for(const t of i)e.push(t);this.groupData.set(t,e)}this.lastSeen.set(t,Date.now()),this.groupFlags.delete(e),this.groupData.delete(e),this.lastSeen.delete(e),this.groupTTL.delete(e),this.groupFlags.set(t,!0)}getGroupId(e){return he(this.#u),this.userToGroup.get(e)||e}hit(e){he(this.#u);const t=this.getGroupId(e),r=Date.now();this.groupData.has(t)||(this.groupData.set(t,[]),this.groupFlags.set(t,!1));const i=this.groupData.get(t);if(!i)throw new Error(`No data found for groupId: ${t}`);if(i.push(r),this.lastSeen.set(t,r),null!==this.#m){const e=r-this.getInterval();for(;i.length&&i[0]<e;)i.shift()}null!==this.#c&&"number"==typeof this.#c&&i.length>this.#c&&(i.splice(0,i.length-this.#c),"function"==typeof this.#g&&this.#g(t))}isRateLimited(e){he(this.#u);const t=this.getGroupId(e);if(!this.groupData.has(t))return!1;const r=this.groupData.get(t);if(!r)throw new Error(`No data found for groupId: ${t}`);if(null!==this.#m){const e=Date.now()-this.getInterval();let t=0;for(let i=r.length-1;i>=0&&r[i]>e;i--)t++;return null!==this.#p?t>this.getMaxHits():t>0}return null!==this.#p&&r.length>this.getMaxHits()}resetGroup(e){he(this.#u),this.groupFlags.delete(e),this.groupData.delete(e),this.lastSeen.delete(e),this.groupTTL.delete(e)}resetUserGroup(e){he(this.#u),this.userToGroup.delete(e)}setData(e,t){if(he(this.#u),!Array.isArray(t))throw new Error("timestamps must be an array of numbers.");for(const e of t)if("number"!=typeof e||!Number.isFinite(e))throw new Error("All timestamps must be finite numbers.");this.groupData.has(e)||this.groupFlags.set(e,!1),this.groupData.set(e,t),this.lastSeen.set(e,Date.now())}hasData(e){return he(this.#u),this.groupData.has(e)}getData(e){return he(this.#u),this.groupData.get(e)||[]}getMaxIdle(){if(he(this.#u),"number"!=typeof this.#y||!Number.isFinite(this.#y)||this.#y<0)throw new Error("'maxIdle' must be a non-negative finite number.");return this.#y}setMaxIdle(e){if(he(this.#u),"number"!=typeof e||!Number.isFinite(e)||e<0)throw new Error("'maxIdle' must be a non-negative finite number.");this.#y=e}_cleanup(){const e=Date.now();for(const[t,r]of this.lastSeen.entries())e-r>(this.getGroupTTL(t)??this.getMaxIdle())&&(this.groupFlags.delete(t),this.groupData.delete(t),this.lastSeen.delete(t),this.groupTTL.delete(t),"function"==typeof this.#w&&this.#w(t))}getActiveGroups(){return he(this.#u),Array.from(this.groupData.keys())}getAllUserMappings(){return he(this.#u),Object.fromEntries(this.userToGroup)}getInterval(){if(he(this.#u),"number"!=typeof this.#m||!Number.isFinite(this.#m))throw new Error("'interval' is not a valid finite number.");return this.#m}getMaxHits(){if(he(this.#u),"number"!=typeof this.#p||!Number.isFinite(this.#p))throw new Error("'maxHits' is not a valid finite number.");return this.#p}getTotalHits(e){he(this.#u);const t=this.groupData.get(e);return Array.isArray(t)?t.length:0}getLastHit(e){he(this.#u);const t=this.groupData.get(e);return t?.length?t[t.length-1]:null}getTimeSinceLastHit(e){he(this.#u);const t=this.getLastHit(e);return null!==t?Date.now()-t:null}_calculateAverageSpacing(e){if(!Array.isArray(e)||e.length<2)return null;let t=0;for(let r=1;r<e.length;r++)t+=e[r]-e[r-1];return t/(e.length-1)}getAverageHitSpacing(e){return he(this.#u),this._calculateAverageSpacing(this.groupData.get(e))}getMetrics(e){he(this.#u);const t=this.groupData.get(e);if(!Array.isArray(t)||0===t.length)return{totalHits:0,lastHit:null,timeSinceLastHit:null,averageHitSpacing:null};const r=t.length,i=t[r-1];return{totalHits:r,lastHit:i,timeSinceLastHit:Date.now()-i,averageHitSpacing:this._calculateAverageSpacing(t)}}destroy(){this.destroyed||(this.#d&&clearInterval(this.#d),this._cleanup(),this.groupData.clear(),this.lastSeen.clear(),this.userToGroup.clear(),this.groupTTL.clear(),this.groupFlags.clear(),this.#u=!0)}},ce=le("TinyNotifyCenter");class de{static getTemplate(){return'\n<div class="notify-overlay hidden">\n <div class="notify-center" id="notifCenter">\n <div class="header">\n <div>Notifications</div>\n <div class="options">\n <button class="clear-all" type="button">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n width="24"\n height="24"\n fill="currentColor"\n >\n <path\n d="M21.6 2.4a1 1 0 0 0-1.4 0L13 9.6l-1.3-1.3a1 1 0 0 0-1.4 0L3 15.6a1 1 0 0 0 0 1.4l4 4a1 1 0 0 0 1.4 0l7.3-7.3a1 1 0 0 0 0-1.4l-1.3-1.3 7.2-7.2a1 1 0 0 0 0-1.4zM6 17l3.5-3.5 1.5 1.5L7.5 18.5 6 17z"\n />\n </svg>\n </button>\n <button class="close">×</button>\n </div>\n </div>\n <div class="list"></div>\n </div>\n</div>\n\n<button class="notify-bell" aria-label="Open notifications">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n fill="currentColor"\n viewBox="0 0 24 24"\n >\n <path\n d="M12 2C10.3 2 9 3.3 9 5v1.1C6.7 7.2 5 9.4 5 12v5l-1 1v1h16v-1l-1-1v-5c0-2.6-1.7-4.8-4-5.9V5c0-1.7-1.3-3-3-3zm0 20c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2z"\n />\n </svg>\n <span class="badge" id="notifBadge">0</span>\n</button>\n '}static insertTemplate(e="afterbegin"){document.body.insertAdjacentHTML(e,de.getTemplate())}#u=!1;get destroyed(){return this.#u}#b;#v;#E;#T;#S;#x=0;#A=99;#C=300;#I=!1;#D=new WeakMap;#k(e){if(this.#D.delete(e),!(e instanceof HTMLElement))throw new Error("Invalid HTMLElement to clear.");e.classList.add("removing"),setTimeout(()=>{this.markAsRead(e),e.remove()},this.#C)}#M(e){this.#x=Math.max(0,e),this.#E.setAttribute("data-value",String(this.#x)),this.#E.textContent=this.#x>this.#A?`${this.#A}+`:String(this.#x)}constructor(e={}){const{center:t=document.getElementById("notifCenter"),badge:r=document.getElementById("notifBadge"),button:i=document.querySelector(".notify-bell"),overlay:s=document.querySelector(".notify-overlay")}=e;if(!(t instanceof HTMLElement))throw new Error(`NotificationCenter: "center" must be an HTMLElement. Got: ${t}`);if(!(s instanceof HTMLElement))throw new Error(`NotificationCenter: "overlay" must be an HTMLElement. Got: ${s}`);if(!(r instanceof HTMLElement))throw new Error(`NotificationCenter: "badge" must be an HTMLElement. Got: ${r}`);if(!(i instanceof HTMLElement))throw new Error(`NotificationCenter: "button" must be an HTMLElement. Got: ${i}`);const n=t?.querySelector(".clear-all"),o=t?.querySelector(".list")??null;if(!(o instanceof HTMLElement))throw new Error(`NotificationCenter: ".list" inside center must be an HTMLElement. Got: ${o}`);this.#b=t,this.#v=o,this.#E=r,this.#T=i,this.#S=s,this.#T.addEventListener("click",()=>this.toggle()),this.#b.querySelector(".close")?.addEventListener("click",()=>this.close()),n&&n.addEventListener("click",()=>this.clear()),this.#S.addEventListener("click",e=>{e.target===this.#S&&this.close()})}setMarkAllAsReadOnClose(e){if(ce(this.#u),"boolean"!=typeof e)throw new TypeError("Expected boolean for markAllAsReadOnClose, got "+typeof e);this.#I=e}setRemoveDelay(e){if(ce(this.#u),"number"!=typeof e)throw new Error('NotificationCenter: "ms" must be an number.');this.#C=e}getItemMode(e){ce(this.#u);const t=this.getItem(e);return t?this.#D.get(t):null}getItem(e){ce(this.#u);const t=this.#v.children.item(e);if(!(t instanceof HTMLElement))throw new Error(`NotificationCenter: "item" must be an HTMLElement. Got: ${t}`);return t}hasItem(e){return ce(this.#u),e>=0&&e<this.#v.children.length}markAsRead(e){ce(this.#u);const t=e instanceof HTMLElement?e:this.getItem(e);t.classList.contains("unread")&&(t.classList.remove("unread"),this.#M(this.#x-1))}add(e,t="text"){ce(this.#u);const r=document.createElement("div");r.className="item unread";let i=null,s=null,n=null,o=null;if("object"==typeof e&&null!==e?(i=e.title,s=e.message,n=e.avatar,o=e.onClick):s=e,n){const e=document.createElement("div");e.className="avatar",e.style.backgroundImage=`url("${n}")`,r.appendChild(e)}const a=document.createElement("div");if(a.className="content",i){const e=document.createElement("div");e.className="title",e.textContent=i,a.appendChild(e)}const l=document.createElement("div");l.className="message","html"===t?l.innerHTML=s:l.textContent=s,a.appendChild(l),"function"==typeof o&&(r.classList.add("clickable"),r.addEventListener("click",e=>{e.target instanceof HTMLElement&&!e.target.closest(".notify-close")&&o(e)}));const h=document.createElement("button");h.className="notify-close",h.setAttribute("type","button"),h.innerHTML="&times;",h.addEventListener("click",e=>{e.stopPropagation(),this.#k(r)}),r.append(a,h),this.#v.prepend(r),this.#D.set(r,t),this.#M(this.#x+1)}remove(e){ce(this.#u);const t=this.getItem(e);this.#k(t)}clear(){ce(this.#u);let e=!0;for(;e;){e=!1;const t=Array.from(this.#v.children);for(const r of t)r instanceof HTMLElement&&!r.classList.contains("removing")&&(this.#k(r),e=!0)}}open(){ce(this.#u),this.#S.classList.remove("hidden"),this.#b.classList.add("open")}close(){if(ce(this.#u),this.#S.classList.add("hidden"),this.#b.classList.remove("open"),this.#I){const e=this.#v.querySelectorAll(".item.unread");for(const t of e)t instanceof HTMLElement&&this.markAsRead(t)}}toggle(){ce(this.#u),this.#b.classList.contains("open")?this.close():this.open()}recount(){ce(this.#u);const e=this.#v.querySelectorAll(".item.unread").length;this.#M(e)}get count(){return this.#x}destroy(){this.#u||(this.#T?.removeEventListener("click",this.toggle),this.#b?.querySelector(".close")?.removeEventListener("click",this.close),this.#b?.querySelector(".clear-all")?.removeEventListener("click",this.clear),this.#S?.removeEventListener("click",this.close),this.clear(),this.#b?.remove(),this.#S?.remove(),this.#T?.remove(),this.#x=0,this.#D=new WeakMap,this.#u=!0)}}const pe=de,me=le("TinyToastNotify"),fe=class{#L;#N;#_;#P;#R;#j;#u=!1;get destroyed(){return this.#u}constructor(e="top",t="right",r=3e3,i=50,s=300,n=".notify-container"){this.#O(e),this.#$(t),this.#H(r,"baseDuration"),this.#H(i,"extraPerChar"),this.#H(s,"fadeOutDuration"),this.#L=e,this.#N=t,this.#_=r,this.#P=i,this.#R=s;const o=document.querySelector(`${n}.${e}.${t}`);o instanceof HTMLElement?this.#j=o:(this.#j=document.createElement("div"),this.#j.className=`notify-container ${e} ${t}`,document.body.appendChild(this.#j))}getContainer(){if(me(this.#u),!(this.#j instanceof HTMLElement))throw new Error("Container is not a valid HTMLElement.");return this.#j}#O(e){if(!["top","bottom"].includes(e))throw new Error(`Invalid vertical direction "${e}". Expected "top" or "bottom".`)}#$(e){if(!["left","right","center"].includes(e))throw new Error(`Invalid horizontal position "${e}". Expected "left", "right" or "center".`)}#H(e,t){if("number"!=typeof e||e<0||!Number.isFinite(e))throw new Error(`Invalid value for "${t}": ${e}. Must be a non-negative finite number.`)}getY(){return me(this.#u),this.#L}setY(e){me(this.#u),this.#O(e);const t=this.getContainer();t.classList.remove(this.#L),t.classList.add(e),this.#L=e}getX(){return me(this.#u),this.#N}setX(e){me(this.#u),this.#$(e);const t=this.getContainer();t.classList.remove(this.#N),t.classList.add(e),this.#N=e}getBaseDuration(){return me(this.#u),this.#_}setBaseDuration(e){me(this.#u),this.#H(e,"baseDuration"),this.#_=e}getExtraPerChar(){return me(this.#u),this.#P}setExtraPerChar(e){me(this.#u),this.#H(e,"extraPerChar"),this.#P=e}getFadeOutDuration(){return me(this.#u),this.#R}setFadeOutDuration(e){me(this.#u),this.#H(e,"fadeOutDuration"),this.#R=e}show(e){me(this.#u);let t="",r="",i=null,s=!1,n=null;const o=document.createElement("div");if(o.className="notify enter","string"==typeof e)t=e;else{if("object"!=typeof e||null===e||"string"!=typeof e.message)throw new Error("Invalid argument for show(): expected string or { message: string, title?: string, onClick?: function, html?: boolean, avatar?: string }");if(t=e.message,r="string"==typeof e.title?e.title:"",s=!0===e.html,n="string"==typeof e.avatar?e.avatar:null,void 0!==e.onClick){if("function"!=typeof e.onClick)throw new Error("onClick must be a function if defined");i=e.onClick,o.classList.add("clickable")}}const a=document.createElement("button");if(a.innerHTML="&times;",a.className="close",a.setAttribute("aria-label","Close"),a.addEventListener("mouseenter",()=>{a.style.color="var(--notify-close-color-hover)"}),a.addEventListener("mouseleave",()=>{a.style.color="var(--notify-close-color)"}),n){const e=document.createElement("img");e.src=n,e.alt="avatar",e.className="avatar",o.appendChild(e)}if(r){const e=document.createElement("strong");e.textContent=r,e.style.display="block",o.appendChild(e)}if(s){const e=document.createElement("div");e.innerHTML=t,o.appendChild(e)}else o.appendChild(document.createTextNode(t));o.appendChild(a),this.getContainer().appendChild(o);const l=this.#_+t.length*this.#P+this.#R;let h=!1;const u=()=>{h||(h=!0,o.classList.remove("enter","show"),o.classList.add("exit"),setTimeout(()=>o.remove(),this.#R))};"function"==typeof i&&o.addEventListener("click",e=>{e.target!==a&&i(e,u)}),a.addEventListener("click",e=>{e.stopPropagation(),u()}),setTimeout(()=>{o.classList.remove("enter"),o.classList.add("show")},1),setTimeout(()=>u(),l)}destroy(){this.#u||this.#j instanceof HTMLElement&&(this.#j.querySelectorAll(".notify").forEach(e=>e.remove()),this.#j.parentNode&&this.#j.parentNode.removeChild(this.#j),this.#j=null,this.#u=!0)}};function ye(e,t){if(!(e instanceof Blob))return Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'));const r=["readAsArrayBuffer","readAsDataURL","readAsText","readAsBinaryString"];return"string"==typeof t&&r.includes(t)?new Promise((r,i)=>{const s=new FileReader;s.onload=()=>{try{r(s.result)}catch(e){i(e)}},s.onerror=()=>{i(s.error)},s[t](e)}):Promise.reject(new TypeError(`The "method" argument must be one of: ${r.join(", ")}.`))}function ge(e,t=!1){return e instanceof Blob?"string"!=typeof t&&"boolean"!=typeof t?Promise.reject(new TypeError("The isDataUrl parameter must be a boolean or a string.")):new Promise((r,i)=>{ye(e,"readAsDataURL").then(e=>{if("string"!=typeof e)throw new TypeError("Expected file content to be a string.");const i=e.match(/^data:(.+);base64,(.*)$/);if(!i||!i[2])throw new Error("Invalid data URL format or missing Base64 content.");const[,s,n]=i;if(!/^[\w/+]+=*$/.test(n))throw new Error("Base64 content is malformed.");if("boolean"==typeof t)return r(t?e:n);if(!/^[\w-]+\/[\w.+-]+$/.test(t))throw new Error(`Invalid MIME type string: ${t}`);return r(`data:${t};base64,${n}`)}).catch(i)}):Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'))}function we(e){return e instanceof Blob?new Promise((t,r)=>ye(e,"readAsText").then(e=>{if("string"!=typeof e)throw new TypeError("Expected file content to be a string.");const r=e.trim();if(0===r.length)throw new Error("File is empty or contains only whitespace.");const i=JSON.parse(r);if("object"!=typeof i||null===i)throw new Error("Parsed content is not a valid JSON object or array.");t(i)}).catch(r)):Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'))}function be(e,t,r=2){if("string"!=typeof e)throw new TypeError('The "filename" argument must be a string.');if("number"!=typeof r||!Number.isInteger(r)||r<0)throw new TypeError('The "spaces" argument must be a non-negative integer.');const i=JSON.stringify(t,null,r),s=new Blob([i],{type:"application/json"}),n=URL.createObjectURL(s),o=document.createElement("a");o.href=n,o.download=e,o.click(),URL.revokeObjectURL(n)}function ve(e,t,r=e=>({headers:e.headers,status:e.status,statusText:e.statusText})){if(!(e instanceof Response))throw new TypeError('The "response" argument must be an instance of Response.');if("function"!=typeof t)throw new TypeError('The "onProgress" argument must be a function.');if(!e.body)return e;const i=e.headers.get("content-length"),s=i?parseInt(i,10):0;let n=0;const o=e.body.getReader(),a=new ReadableStream({async start(e){for(;;){const{done:r,value:i}=await o.read();if(r)break;n+=i.byteLength,t(n,s),e.enqueue(i)}e.close()}});return new Response(a,r(e))}async function Ee(e,t,r){return"string"!=typeof e?Promise.reject(new TypeError('The "url" argument must be a string.')):void 0!==t&&"object"!=typeof t?Promise.reject(new TypeError('The "options" argument must be an object.')):void 0!==r&&"function"!=typeof r?Promise.reject(new TypeError('The "onProgress" option must be a function.')):new Promise((i,s)=>{fetch(e,t??void 0).then(async e=>{const t=r?ve(e,r):e,s=t.headers.get("content-type")||"";if(!s.includes("application/json"))throw new Error(`Unexpected content-type: ${s}`);const n=await t.json();if(!Array.isArray(n)&&!v(n))throw new Error("Received invalid data instead of valid JSON.");return i(n)}).catch(s)})}async function Te(e,t,r,i){return"string"!=typeof e?Promise.reject(new TypeError('The "url" argument must be a string.')):void 0===t||Array.isArray(t)?void 0!==r&&"object"!=typeof r?Promise.reject(new TypeError('The "options" argument must be an object.')):void 0!==i&&"function"!=typeof i?Promise.reject(new TypeError('The "onProgress" option must be a function.')):new Promise((s,n)=>{fetch(e,r??void 0).then(async e=>{const r=i?ve(e,i):e,n=r.headers.get("content-type")||"";if(Array.isArray(t)&&t.length>0&&!t.some(e=>n.includes(e)))throw new Error(`Blocked MIME type: ${n}`);const o=await r.text();return s(o)}).catch(n)}):Promise.reject(new TypeError('The "allowedMimeTypes" argument must be an array of strings.'))}function Se(e={}){if(null===e||"object"!=typeof e)throw new TypeError('The "settings" argument must be an object.');const{element:t=document.body,hiddenClass:r="windowHidden",visibleClass:i="windowVisible",onVisible:s,onHidden:n}=e;if(!(t instanceof Element))throw new TypeError('"element" must be an instance of Element.');if("string"!=typeof r)throw new TypeError('"hiddenClass" must be a string.');if("string"!=typeof i)throw new TypeError('"visibleClass" must be a string.');if(void 0!==s&&"function"!=typeof s)throw new TypeError('"onVisible" must be a function if provided.');if(void 0!==n&&"function"!=typeof n)throw new TypeError('"onHidden" must be a function if provided.');let o="",a="";const l=()=>{t.classList.remove(r),t.classList.remove(i)};let h=null;const u=["visibilitychange","mozvisibilitychange","webkitvisibilitychange","msvisibilitychange"],c=["hidden","mozHidden","webkitHidden","msHidden"];for(let e=0;e<c.length;e++)if(c[e]in document){h=c[e];break}const d=function(e){l();const u=e?.type,c=h&&document[h];["focus","focusin","pageshow"].includes(u)?(t.classList.add(i),s?.({type:u,oldClass:a,oldType:o}),a=i):["blur","focusout","pagehide"].includes(u)||c?(t.classList.add(r),n?.({type:u,oldClass:a,oldType:o}),a=r):(t.classList.add(i),s?.({type:u,oldClass:a,oldType:o}),a=i),o=u};let p=()=>{};if(h){const e=u[c.indexOf(h)];document.addEventListener(e,d),window.addEventListener("focus",d),window.addEventListener("blur",d),p=()=>{document.removeEventListener(e,d),window.removeEventListener("focus",d),window.removeEventListener("blur",d),l()}}else"onfocusin"in document?(document.onfocusin=document.onfocusout=d,p=()=>{document.onfocusin=document.onfocusout=null,l()}):(window.onpageshow=window.onpagehide=window.onfocus=window.onblur=d,p=()=>{window.onpageshow=window.onpagehide=window.onfocus=window.onblur=null,l()});const m=new Event(h&&document[h]?"blur":"focus");return d(m),p}const xe=le("TinyDragDropDetector"),Ae=class{#F;#z;#B;#W;#q;#V;#U;#u=!1;get destroyed(){return this.#u}constructor(e,t){const{hoverClass:r="dnd-hover",onDrop:i,onEnter:s,onLeave:n}=t;if(!(e instanceof HTMLElement))throw new TypeError('The "target" option must be an instance of HTMLElement.');if("string"!=typeof r)throw new TypeError('The "hoverClass" option must be a string.');if("function"!=typeof i)throw new TypeError('The "onDrop" option must be a function.');if("function"!=typeof s)throw new TypeError('The "onEnter" option must be a function.');if("function"!=typeof n)throw new TypeError('The "onLeave" option must be a function.');this.#F=e,this.#z=r,this.#B=i||(()=>{}),this.#W=s,this.#q=n,this.#V=!1,this.#U=!1,this._handleDragEnter=this._handleDragEnter.bind(this),this._handleDragOver=this._handleDragOver.bind(this),this._handleDragLeave=this._handleDragLeave.bind(this),this._handleDrop=this._handleDrop.bind(this),this.#K()}getTarget(){return xe(this.#u),this.#F}getHoverClass(){return xe(this.#u),this.#z}isDragging(){return xe(this.#u),this.#V}bound(){return xe(this.#u),this.#U}#K(){if(this.#U)return;const e=this.getTarget();e.addEventListener("dragenter",this._handleDragEnter),e.addEventListener("dragover",this._handleDragOver),e.addEventListener("dragleave",this._handleDragLeave),e.addEventListener("drop",this._handleDrop),this.#U=!0}#J(){if(!this.#U)return;const e=this.getTarget();e.removeEventListener("dragenter",this._handleDragEnter),e.removeEventListener("dragover",this._handleDragOver),e.removeEventListener("dragleave",this._handleDragLeave),e.removeEventListener("drop",this._handleDrop),this.#U=!1}_handleDragEnter(e){if(e.preventDefault(),!this.#V){const t=this.getTarget();this.#V=!0,t.classList.add(this.#z),this.#W(e)}}_handleDragOver(e){e.preventDefault(),e.dataTransfer?e.dataTransfer.dropEffect="copy":console.warn("[TinyDragDropDetector] [handleDragOver] DragOver event missing dataTransfer.")}_handleDragLeave(e){e.preventDefault();const t=this.getTarget();null!==e.relatedTarget&&t.contains(e.relatedTarget)||(this.#V=!1,t.classList.remove(this.#z),this.#q(e))}_handleDrop(e){if(e.preventDefault(),!e.dataTransfer)return void console.warn("[TinyDragDropDetector] [handleDrop] DragOver event missing dataTransfer.");const t=this.getTarget();this.#V=!1,t.classList.remove(this.#z);const r=e.dataTransfer.files;r.length>0&&this.#B(r,e)}destroy(){this.#u||(this.#J(),this.getTarget().classList.remove(this.#z),this.#u=!0)}};var Ce=r(133);function Ie(e){if(!(0,Ce.existsSync)(e))throw new Error(`File not found: ${e}`);const t=(0,Ce.readFileSync)(e,"utf-8");return JSON.parse(t)}function De(e,t,r=2){const i=JSON.stringify(t,null,r);(0,Ce.writeFileSync)(e,i,"utf-8")}function ke(e){(0,Ce.existsSync)(e)||(0,Ce.mkdirSync)(e,{recursive:!0})}function Me(e){if(!(0,Ce.existsSync)(e))return;const r=(0,Ce.readdirSync)(e);for(const i of r){const r=(0,t().join)(e,i);(0,Ce.lstatSync)(r).isDirectory()?(0,Ce.rmSync)(r,{recursive:!0,force:!0}):(0,Ce.unlinkSync)(r)}}function Le(e){return(0,Ce.existsSync)(e)&&(0,Ce.lstatSync)(e).isFile()}function Ne(e){return(0,Ce.existsSync)(e)&&(0,Ce.lstatSync)(e).isDirectory()}function _e(e){return 0===(0,Ce.readdirSync)(e).length}function Pe(e,r,i){ke((0,t().dirname)(r)),(0,Ce.copyFileSync)(e,r,i)}function Re(e){return!!Le(e)&&((0,Ce.unlinkSync)(e),!0)}function je(e,r,i="utf-8"){ke((0,t().dirname)(e)),(0,Ce.writeFileSync)(e,r,i)}function Oe(e,r=!1){const i={files:[],dirs:[]};if(!Ne(e))return i;const s=(0,Ce.readdirSync)(e);for(const n of s){const s=(0,t().join)(e,n);if((0,Ce.lstatSync)(s).isDirectory()){if(i.dirs.push(s),r){const e=Oe(s,!0);i.files.push(...e.files),i.dirs.push(...e.dirs)}}else i.files.push(s)}return i}function $e(e,r=!1){const i=[];if(!Ne(e))return i;const s=(0,Ce.readdirSync)(e);for(const n of s){const s=(0,t().join)(e,n);(0,Ce.lstatSync)(s).isDirectory()&&(i.push(s),r&&i.push(...$e(s,!0)))}return i}function He(e){return Le(e)?(0,Ce.statSync)(e).size:0}function Fe(e){let t=0;const r=Oe(e,!0).files;for(const e of r)t+=He(e);return t}function ze(e,t="bak"){Le(e)&&Pe(e,`${e}.${t}.${(new Date).toISOString().replace(/[:.]/g,"-")}`)}function Be(e,r="bak"){const i=(0,t().dirname)(e),s=(0,t().basename)(e),n=(0,Ce.readdirSync)(i).filter(e=>e.startsWith(`${s}.${r}.`)).sort().reverse();if(0===n.length)throw new Error(`No backups found for ${e}`);return(0,t().join)(i,n[0])}function We(e,t="bak"){Pe(Be(e,t),e)}function qe(e,r,i=[]){if("string"!=typeof e)throw new TypeError("dirPath must be a string");if("function"!=typeof r)throw new TypeError("renameFn must be a function");if(!Array.isArray(i))throw new TypeError("extensions must be an array of strings");if(!(0,Ce.existsSync)(e)||!(0,Ce.statSync)(e).isDirectory())throw new Error(`Directory not found or invalid: ${e}`);for(const e of i)if("string"!=typeof e||!e.startsWith("."))throw new TypeError(`Invalid extension: ${e}`);const s=Oe(e).files;let n=0;for(const o of s){const s=(0,t().extname)(o);if(i.length&&!i.includes(s))continue;const a=(0,t().basename)(o),l=r(a,n++),h=(0,t().join)(e,l);a!==l&&(0,Ce.renameSync)(o,h)}}function Ve(e,r,i,s=[]){qe(e,e=>{const s=(0,t().extname)(e);return`${(0,t().basename)(e,s).replace(r,i)}${s}`},s)}function Ue(e,{prefix:r="",suffix:i=""},s=[]){qe(e,e=>{const s=(0,t().extname)(e),n=(0,t().basename)(e,s);return`${r}${n}${i}${s}`},s)}function Ke(e,r="lower",i=[],s=!1){if("string"!=typeof r||!["lower","upper","title"].includes(r))throw new Error(`Invalid mode "${r}". Must be 'lower', 'upper' or 'title'.`);qe(e,e=>{const i=e=>"lower"===r?e.toLowerCase():"upper"===r?e.toUpperCase():"title"===r?Z(e):e,n=(0,t().extname)(e),o=s?i(n):n;return`${i((0,t().basename)(e,n))}${o}`},i)}function Je(e,t=3,r=[]){qe(e,e=>e.replace(/\d+/,e=>e.padStart(t,"0")),r)}t();var Ge=r(370);async function Ye(e){if(!(0,Ce.existsSync)(e))return;const r=await(0,Ge.readdir)(e),i={},s=[];for(const n of r){const r=(0,t().join)(e,n),o=(0,Ge.lstat)(r);o.then(e=>(i[r]=e,e)),s.push(o)}await Promise.all(s);const n=[];for(const e in i)i[e].isDirectory()?n.push((0,Ge.rm)(e,{recursive:!0,force:!0})):n.push((0,Ge.unlink)(e));await Promise.all(n)}async function Xe(e){return 0===(await(0,Ge.readdir)(e)).length}async function Qe(e,r=!1){const i={files:[],dirs:[]};if(!Ne(e))return i;const s=await(0,Ge.readdir)(e);for(const n of s){const s=(0,t().join)(e,n);if((await(0,Ge.lstat)(s)).isDirectory()){if(i.dirs.push(s),r){const e=await Qe(s,!0);i.files.push(...e.files),i.dirs.push(...e.dirs)}}else i.files.push(s)}return i}async function Ze(e,r=!1){const i=[];if(!Ne(e))return i;const s=await(0,Ge.readdir)(e);for(const n of s){const s=(0,t().join)(e,n);(await(0,Ge.lstat)(s)).isDirectory()&&(i.push(s),r&&i.push(...await Ze(s,!0)))}return i}async function et(e){return Le(e)?(await(0,Ge.stat)(e)).size:0}async function tt(e){let t=0;const{files:r}=await Qe(e,!0),i=[];for(const e of r){const r=et(e);r.then(e=>(t+=e,e)),i.push(r)}return await Promise.all(i),t}const rt=(e,t)=>e.bottom<t.top,it=(e,t)=>e.top>t.bottom,st=(e,t)=>e.right<t.left,nt=(e,t)=>e.left>t.right,ot=(e,t)=>e.bottom<=t.top,at=(e,t)=>e.top>=t.bottom,lt=(e,t)=>e.right<=t.left,ht=(e,t)=>e.left>=t.right,ut=(e,t)=>!(st(e,t)||nt(e,t)||rt(e,t)||it(e,t)),ct=(e,t)=>!(lt(e,t)||ht(e,t)||ot(e,t)||at(e,t)),dt=(e,t)=>st(e,t)?"left":nt(e,t)?"right":rt(e,t)?"top":it(e,t)?"bottom":null,pt=(e,t)=>lt(e,t)?"left":ht(e,t)?"right":ot(e,t)?"top":at(e,t)?"bottom":null,mt=(e,t)=>({overlapLeft:t.right-e.left,overlapRight:e.right-t.left,overlapTop:t.bottom-e.top,overlapBottom:e.bottom-t.top}),ft=({overlapLeft:e=-1,overlapRight:t=-1,overlapTop:r=-1,overlapBottom:i=-1}={})=>({dirX:e<t?"right":"left",dirY:r<i?"bottom":"top"}),yt=e=>({x:e.left+e.width/2,y:e.top+e.height/2});function gt(e,t){const r=e.left+e.width/2,i=e.top+e.height/2;return{x:t.left+t.width/2-r,y:t.top+t.height/2-i}}function wt(e,t){if(!ct(e,t))return{inDir:null,dirX:null,dirY:null,depthX:0,depthY:0};const{overlapLeft:r,overlapRight:i,overlapTop:s,overlapBottom:n}=mt(e,t),{dirX:o,dirY:a}=ft({overlapLeft:r,overlapRight:i,overlapTop:s,overlapBottom:n}),l=Math.min(r,i),h=Math.min(s,n);let u;return u=l<h?o:a,{inDir:u,dirX:o,dirY:a,depthX:l,depthY:h}}function bt(e,t){const r=ct(e,t),i={in:null,x:null,y:null},s={y:null,x:null},n={top:0,bottom:0,left:0,right:0},{overlapLeft:o,overlapRight:a,overlapTop:l,overlapBottom:h}=mt(t,e);n.top=l,n.bottom=h,n.left=o,n.right=a;const u=Object.entries(n).filter(([,e])=>e>0).sort((e,t)=>e[1]-t[1]),{dirX:c,dirY:d}=ft({overlapLeft:a,overlapRight:o,overlapTop:h,overlapBottom:l});return i.y=d,i.x=c,n.bottom<0?s.y="bottom":n.top<0&&(s.y="top"),n.left<0?s.x="left":n.right<0&&(s.x="right"),i.in=r?n.top===n.bottom&&n.bottom===n.left&&n.left===n.right?"center":u.length?u[0][0]:"top":null,{dirs:i,depth:n,isNeg:s}}const vt=le("TinyElementObserver"),Et=class{#u=!1;get destroyed(){return this.#u}#G;get el(){return vt(this.#u),this.#G}#Y={};get settings(){return vt(this.#u),this.#Y}set settings(e){if(vt(this.#u),"object"!=typeof e||null===e)throw new TypeError("settings must be a non-null object.");this.#Y=e}#X=null;get observer(){return vt(this.#u),this.#X}#Q=[];get detectors(){return vt(this.#u),this.#Q.map(e=>[e[0],e[1]])}set detectors(e){if(vt(this.#u),!Array.isArray(e))throw new TypeError("detectors must be an array.");const t=[];for(const[r,i]of e){if("string"!=typeof r)throw new TypeError("Detector name must be a string.");if("function"!=typeof i)throw new TypeError(`Detector handler for "${r}" must be a function.`);t.push([r,i])}this.#Q=t}get isActive(){return vt(this.#u),!!this.#X}get size(){return vt(this.#u),this.#Q.length}constructor(e,{initDetectors:t=[],initCfg:r={}}={}){this.#G=e,t.length&&(this.detectors=t),r&&(this.settings=r)}clear(){vt(this.#u),this.#Q=[]}start(){if(vt(this.#u),!this.#G)throw new Error("Cannot start observation: no target element has been set.");this.#X||(this.#X=new MutationObserver(e=>{e.forEach((e,t,r)=>this.#Q.forEach(i=>i[1](e,t,r)))}),this.#X.observe(this.#G,this.#Y))}stop(){vt(this.#u),this.#X&&(this.#X.disconnect(),this.#X=null)}add(e,t){vt(this.#u),this.#Z(e,t),this.#Q.push([e,t])}insertAtStart(e,t){vt(this.#u),this.#Z(e,t),this.#Q.unshift([e,t])}insertAt(e,t,r,i="after"){if(vt(this.#u),this.#Z(t,r),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for insertDetectorAt.");const s="before"===i?e:e+1;this.#Q.splice(s,0,[t,r])}removeAt(e){if(vt(this.#u),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for removeDetectorAt.");this.#Q.splice(e,1)}removeAround(e,t=0,r=0){if(vt(this.#u),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for removeDetectorsAround.");const i=Math.max(0,e-t),s=t+1+r;this.#Q.splice(i,s)}isIndexUsed(e){return vt(this.#u),e>=0&&e<this.#Q.length}hasHandler(e){if(vt(this.#u),"function"!=typeof e)throw new TypeError("Handler must be a function.");return this.#Q.some(([t,r])=>r===e)}#Z(e,t){if("string"!=typeof e||!e.trim())throw new TypeError("Detector name must be a non-empty string.");if("function"!=typeof t)throw new TypeError(`Detector handler for "${e}" must be a function.`)}destroy(){this.#u||(this.stop(),this.clear(),this.#u=!0)}},{wE:Tt,D6:St,Kr:xt,iu:At,cq:Ct,lP:It}=s,Dt=new WeakMap,kt=new WeakMap,Mt=new WeakMap,Lt=new WeakMap,Nt={top:new WeakMap,bottom:new WeakMap,left:new WeakMap,right:new WeakMap};class _t{static Utils={...n};static#ee=1;static get version(){return this.#ee}static#te=!1;static get elemDebug(){return _t.#te}static set elemDebug(e){if("boolean"!=typeof e)throw new TypeError("Expected a boolean value for elemDebug");_t.#te=e}static _debugElemError(e,t){if(!_t.#te)return;const r="[TinyHtml Debug] Element validation error";if(console.groupCollapsed(`${r}${t?" — details below":""}`),console.error(r),"undefined"!=typeof Error&&"function"==typeof Error.captureStackTrace){const e=new Error(r);Error.captureStackTrace(e,_t._debugElemError),console.error(e.stack)}else console.trace(r);if(Array.isArray(e)){const t=e.map((e,t)=>({index:t,typeOf:null===e?"null":typeof e,constructor:e?.constructor?.name??(null===e?"null":"primitive"),summary:"undefined"!=typeof Element&&e instanceof Element?`${e.tagName?.toLowerCase?.()??"element"}#${e.id||""}.${String(e.className||"").trim().replace(/\s+/g,".")}`:e&&"object"==typeof e&&"nodeType"in e?`nodeType:${e.nodeType}`:"",value:e}));console.table(t)}else console.warn('[TinyHtml Debug] "elems" is not an array:',e);arguments.length>1&&(console.error("[TinyHtml Debug] Problematic element:",t),t&&"object"==typeof t&&console.dir(t)),console.groupEnd()}static parseStyle(e){const t={};return e.split(";").forEach(e=>{const[r,i]=e.split(":").map(e=>e&&e.trim());r&&i&&(t[r]=i)}),t}static#re="undefined"!=typeof window&&void 0!==window.document?new Et(window.document.documentElement,{initDetectors:[["tinyStyleEvent",e=>{if("attributes"!==e.type||"style"!==e.attributeName||!(e.target instanceof HTMLElement))return;const t=e.oldValue||"",r=e.target.getAttribute("style")||"",i=ie(_t.parseStyle(t),_t.parseStyle(r));(Object.keys(i.added).length||Object.keys(i.removed).length||Object.keys(i.modified).length)&&e.target.dispatchEvent(new CustomEvent("tinyhtml.stylechanged",{detail:i}))}],["tinyClassEvent",e=>{if("attributes"!==e.type||"class"!==e.attributeName||!(e.target instanceof HTMLElement))return;const t=e.oldValue||"",r=e.target.className||"",i=c(t.split(/\s+/).filter(Boolean),r.split(/\s+/).filter(Boolean));(i.added.length||i.removed.length)&&e.target.dispatchEvent(new CustomEvent("tinyhtml.classchanged",{detail:i}))}]],initCfg:{attributeOldValue:!0,attributes:!0,subtree:!0,attributeFilter:["style","class"]}}):void 0;static get tinyObserver(){return _t.#re}static async fetchHtmlFile(e,t={method:"GET"}){const r=await fetch(e,t),i=r.headers.get("Content-Type")||"";if(!r.ok)throw new Error(`Failed to fetch: ${r.status} ${r.statusText}`);if(!i.includes("text/html"))throw new Error(`Invalid content type: ${i} (expected text/html)`);const s=await r.text();return _t.htmlToJson(s)}static async fetchHtmlNodes(e,t){const r=await _t.fetchHtmlFile(e,t);return _t.jsonToNodes(r)}static async fetchHtmlTinyElems(e,t){const r=await _t.fetchHtmlNodes(e,t);return _t.toTinyElm(r)}static templateToJson(e){return _t.htmlToJson([...e.content.childNodes].map(e=>e instanceof Element?e.getHTML():e instanceof Text?e.textContent:"").join(""))}static templateToNodes(e){const t=[];return[...e.content.cloneNode(!0).childNodes].map(e=>{if(!(e instanceof Element||e instanceof Text||e instanceof Comment))throw new Error(`Expected only Element nodes in <template>, but found: ${e.constructor.name}`);e instanceof Comment||t.push(e)}),t}static templateToTinyElems(e){return _t.toTinyElm(_t.templateToNodes(e))}static htmlToJson(e){const t=document.createElement("div");t.innerHTML=e.trim();const r=[],i=e=>{if(e instanceof Comment)return null;if(e instanceof Text){const t=e.textContent?.trim();return t||null}if(!(e instanceof Element))return null;const t=e.tagName.toLowerCase(),r={};for(const t of e.attributes)r[_t.getPropName(t.name)]=t.value;const s=Array.from(e.childNodes).map(i).filter(Boolean);return s.length>0?[t,r,...s]:[t,r]};for(const e of t.childNodes){const t=i(e);t&&r.push(t)}return t.innerHTML="",r}static jsonToNodes(e){const t=e=>{if("string"==typeof e)return document.createTextNode(e);if(!Array.isArray(e))return document.createTextNode("");const[r,i,...s]=e,n=document.createElement(r);for(const[e,t]of Object.entries(i))n.setAttribute(_t.getAttrName(e),t);for(const e of s){const r=t(e);r instanceof Comment||n.appendChild(r)}return n};return e.map(t).filter(e=>!(e instanceof Comment))}static jsonToTinyElems(e){return _t.toTinyElm(_t.jsonToNodes(e))}static createFrom(e,t){if("string"!=typeof e)throw new TypeError('The "tagName" must be a string.');if(void 0!==t&&"object"!=typeof t)throw new TypeError('The "attrs" must be a object.');const r=_t.createElement(e);if("object"==typeof t)for(const e in t)r.setAttr(e,t[e]);return r}static createElement(e,t){if("string"!=typeof e)throw new TypeError("[TinyHtml] createElement(): The tagName must be a string.");if(void 0!==t&&"object"!=typeof t)throw new TypeError("[TinyHtml] createElement(): The ops must be a object.");return new _t(document.createElement(e,t))}static createTextNode(e){if("string"!=typeof e)throw new TypeError("[TinyHtml] createTextNode(): The value must be a string.");return new _t(document.createTextNode(e))}static createElementFromHTML(e){const t=document.createElement("template");if(!(e=e.trim()).startsWith("<"))return _t.createTextNode(e);if(t.innerHTML=e,!(t.content.firstChild instanceof Element))throw new Error("The HTML string must contain a valid HTML element.");return new _t(t.content.firstChild)}static createFromHTML(e){const t=document.createElement("template");e=e.trim(),t.innerHTML=e;const r=Array.from(t.content.childNodes);if(!r.every(e=>e instanceof Element||e instanceof Text))throw new Error("The HTML string must contain a valid HTML element.");return new _t(r)}static createFromHtml(e){return _t.createFromHTML(e)}static query(e,t=document){const r=t.querySelector(e);return r?new _t(r):null}querySelector(e){return _t.query(e,_t._preElem(this,"query"))}static queryAll(e,t=document){return new _t(t.querySelectorAll(e))}querySelectorAll(e){return _t.queryAll(e,_t._preElem(this,"queryAll"))}static getById(e){const t=document.getElementById(e);return t?new _t(t):null}static getByClassName(e,t=document){return new _t(t.getElementsByClassName(e))}getElementsByClassName(e){return _t.getByClassName(e,_t._preElem(this,"getByClassName"))}static getByName(e){return new _t(document.getElementsByName(e))}static getByTagNameNS(e,t="http://www.w3.org/1999/xhtml",r=document){return new _t(r.getElementsByTagNameNS(t,e))}getElementsByTagNameNS(e,t="http://www.w3.org/1999/xhtml"){return _t.getByTagNameNS(e,t,_t._preElem(this,"getByTagNameNS"))}get elements(){return[...this.#G]}forEach(e){const t=this.elements.map((e,t)=>this.extract(t));for(const r in t)e(t[r],Number(r),t);return this}get(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");if(!this.#G[e])throw new Error(`No element found at index ${e}.`);return this.#G[e]}extract(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");if(!this.#G[e])throw new Error(`Cannot extract: no element exists at index ${e}.`);return new _t(this.#G[e])}exists(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");return!!this.#G[e]}_getElement(e,t){if(!(this.#G[t]instanceof Element||this.#G[t]instanceof Window||this.#G[t]instanceof Document||this.#G[t]instanceof Text))throw _t._debugElemError([...this.#G],this.#G[t]),new Error(`[TinyHtml] Invalid Element in ${e}().`);return this.#G[t]}_getElements(e){if(!this.#G.every(e=>e instanceof Element||e instanceof Window||e instanceof Document||e instanceof Text))throw _t._debugElemError([...this.#G]),new Error(`[TinyHtml] Invalid Element in ${e}().`);return[...this.#G]}static _preElemsTemplate(e,t,r,i){const s=e=>{const s=[];return e.map(n=>(n instanceof _t?n._getElements(t):[n]).map(n=>{let o=!1;for(const e of r)if(n instanceof e){o=!0;break}if(!o)throw _t._debugElemError([...e],n),new Error(`[TinyHtml] Invalid element of the list "${i.join(",")}" in ${t}().`);return s.push(n),n})),s};return Array.isArray(e)?s(e):s([e])}_preElemsTemplate(e,t,r){return _t._preElemsTemplate(this,e,t,r)}static _preElemTemplate(e,t,r,i,s=!1){const n=e=>{const n=e[0],o=n instanceof _t?n._getElements(t):[n];if(o.length>1)throw _t._debugElemError([...e]),new Error(`[TinyHtml] Invalid element amount in ${t}() (Received ${o.length}/1).`);let a=!1;for(const e of r)if(o[0]instanceof e){a=!0;break}if(!s||null!==o[0]&&void 0!==o[0]||(o[0]=null,a=!0),!a)throw _t._debugElemError([...e],o[0]),new Error(`[TinyHtml] Invalid element of the list "${i.join(",")}" in ${t}().`);return o[0]};if(!Array.isArray(e))return n([e]);if(e.length>1)throw _t._debugElemError([...e]),new Error(`[TinyHtml] Invalid element amount in ${t}() (Received ${e.length}/1).`);return n(e)}_preElemTemplate(e,t,r,i=!1){return _t._preElemTemplate(this,e,t,r,i)}static _preElems(e,t){return _t._preElemsTemplate(e,t,[Element],["Element"])}_preElems(e){return _t._preElems(this,e)}static _preElem(e,t){return _t._preElemTemplate(e,t,[Element],["Element"])}_preElem(e){return _t._preElem(this,e)}static _preNodeElems(e,t){return _t._preElemsTemplate(e,t,[Node],["Node"])}_preNodeElems(e){return _t._preNodeElems(this,e)}static _preNodeElem(e,t){return _t._preElemTemplate(e,t,[Node],["Node"])}_preNodeElem(e){return _t._preNodeElem(this,e)}static _preNodeElemWithNull(e,t){return _t._preElemTemplate(e,t,[Node],["Node"],!0)}_preNodeElemWithNull(e){return _t._preNodeElemWithNull(this,e)}static _preHtmlElems(e,t){return _t._preElemsTemplate(e,t,[HTMLElement],["HTMLElement"])}_preHtmlElems(e){return _t._preHtmlElems(this,e)}static _preHtmlElem(e,t){return _t._preElemTemplate(e,t,[HTMLElement],["HTMLElement"])}_preHtmlElem(e){return _t._preHtmlElem(this,e)}static _preInputElems(e,t){return _t._preElemsTemplate(e,t,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLOptionElement],["HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement"])}_preInputElems(e){return _t._preInputElems(this,e)}static _preInputElem(e,t){return _t._preElemTemplate(e,t,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLOptionElement],["HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement"])}_preInputElem(e){return _t._preInputElem(this,e)}static _preEventTargetElems(e,t){return _t._preElemsTemplate(e,t,[EventTarget],["EventTarget"])}_preEventTargetElems(e){return _t._preEventTargetElems(this,e)}static _preEventTargetElem(e,t){return _t._preElemTemplate(e,t,[EventTarget],["EventTarget"])}_preEventTargetElem(e){return _t._preEventTargetElem(this,e)}static _preElemsAndWindow(e,t){return _t._preElemsTemplate(e,t,[Element,Window],["Element","Window"])}_preElemsAndWindow(e){return _t._preElemsAndWindow(this,e)}static _preElemAndWindow(e,t){return _t._preElemTemplate(e,t,[Element,Window],["Element","Window"])}_preElemAndWindow(e){return _t._preElemAndWindow(this,e)}static _preElemsAndWinAndDoc(e,t){return _t._preElemsTemplate(e,t,[Element,Window,Document],["Element","Window","Document"]).map(e=>e instanceof Document?e.documentElement:e)}_preElemsAndWinAndDoc(e){return _t._preElemsAndWinAndDoc(this,e)}static _preElemAndWinAndDoc(e,t){const r=_t._preElemTemplate(e,t,[Element,Window,Document],["Element","Window","Document"]);return r instanceof Document?r.documentElement:r}_preElemAndWinAndDoc(e){return _t._preElemAndWinAndDoc(this,e)}static _preElemsWithDoc(e,t){return _t._preElemsTemplate(e,t,[Element,Document],["Element","Document"])}_preElemsWithDoc(e){return _t._preElemsWithDoc(this,e)}static _preElemWithDoc(e,t){return _t._preElemTemplate(e,t,[Element,Document],["Element","Document"])}_preElemWithDoc(e){return _t._preElemWithDoc(this,e)}static toTinyElm(e){const t=e=>e.map(e=>e instanceof _t?e:new _t(e));return Array.isArray(e)?t(e):t([e])}static fromTinyElm(e){const t=e=>{const t=[];return e.map(e=>(e instanceof _t?e._getElements("fromTinyElm"):[e]).map(e=>t.push(e))),t};return Array.isArray(e)?t(e):t([e])}static winnow(e,t,r,i=!1){if("boolean"!=typeof i)throw new TypeError('The "not" must be a boolean.');if("function"==typeof t)return _t._preElems(e,r).filter((e,r)=>!!t.call(e,r,e)!==i);if(t instanceof Element)return _t._preElems(e,r).filter(e=>e===t!==i);if(Array.isArray(t)||"string"!=typeof t&&null!=t.length)return _t._preElems(e,r).filter(e=>t.includes(e)!==i);let s=t;return i&&(s=`:not(${s})`),_t._preElems(e,r).filter(e=>1===e.nodeType&&e.matches(s))}static filter(e,t,r=!1){return r&&(t=`:not(${t})`),_t._preElems(e,"filter").filter(e=>1===e.nodeType&&e.matches(t))}static filterOnly(e,t){return _t.winnow(e,t,"filterOnly",!1)}static not(e,t){return _t.winnow(e,t,"not",!0)}not(e){return _t.not(this,e)}static find(e,t){const r=[];for(const i of _t._preElems(e,"find"))r.push(...i.querySelectorAll(t));return[...new Set(r)]}find(e){return _t.find(this,e)}static is(e,t){return _t.winnow(e,t,"is",!1).length>0}is(e){return _t.is(this,e)}static has(e,t){const r="string"==typeof t?[...document.querySelectorAll(t)]:_t._preElems(t,"has");return _t._preElems(e,"has").filter(e=>r.some(t=>e&&e.contains(t)))}has(e){return _t.has(this,e)}static closest(e,t,r){const i=[];for(const s of _t._preElems(e,"closest")){let e=s;for(;e&&e!==r;){if(1===e.nodeType&&("string"==typeof t?e.matches(t):e===t)){i.push(e);break}e=e.parentElement}}return[...new Set(i)]}closest(e,t){return _t.closest(this,e,t)}static isSameDom(e,t){return _t._preNodeElem(e,"isSameDom")===_t._preNodeElem(t,"isSameDom")}isSameDom(e){return _t.isSameDom(this,e)}#ie={};get _data(){return{...this.#ie}}set _data(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error("value must be a non-null object.");this.#ie=e}static _dataSelector={public:(e,t)=>{const r=_t._preElem(t,e);let i=kt.get(r);return i||(i={},kt.set(r,i)),i},private:(e,t)=>{if(!(t instanceof _t))throw new Error(`Element must be a TinyHtml instance to execute ${e}().`);return t.#ie}};static data(e,t,r=!1){const i=_t._dataSelector[r?"private":"public"]("data",e);if(null==t)return{...i};if("string"!=typeof t)throw new TypeError("The key must be a string.");return i.hasOwnProperty(t)?i[t]:void 0}data(e,t){return _t.data(this,e,t)}static setData(e,t,r,i=!1){const s=_t._dataSelector[i?"private":"public"]("setData",e);if("string"!=typeof t)throw new TypeError("The key must be a string.");return void 0!==r?s[t]=r:_t.removeData(e,t),e}setData(e,t,r=!1){return _t.setData(this,e,t,r)}static hasData(e,t,r=!1){if("string"!=typeof t)throw new TypeError("The key must be a string.");const i=_t._dataSelector[r?"private":"public"]("hasData",e);return Object.prototype.hasOwnProperty.call(i,t)}hasData(e,t=!1){return _t.hasData(this,e,t)}static removeData(e,t,r=!1){if("string"!=typeof t)throw new TypeError("The key must be a string.");return delete _t._dataSelector[r?"private":"public"]("removeData",e)[t]}removeData(e,t=!1){return _t.removeData(this,e,t)}static _getSibling(e,t,r){let i=_t._preNodeElemWithNull(e,r);for(;i&&(i=i[t])&&1!==i.nodeType;);return i instanceof Node?i:null}static _getSiblings(e,t){let r=e;const i=[];for(;r;r=r.nextSibling)1===r.nodeType&&r!==t&&i.push(r);return i}static domDir(e,t,r,i="domDir"){if("string"!=typeof t)throw new TypeError('The "direction" must be a string.');let s=_t._preNodeElemWithNull(e,i);const n=[];for(;s&&(s=s[t]);)if(1===s.nodeType){if(r&&("string"==typeof r?s.matches(r):s===r))break;n.push(s)}return n}static parent(e){let t=_t._preNodeElemWithNull(e,"parent");const r=t?t.parentNode:null;return r&&11!==r.nodeType?r:null}parent(){return _t.parent(this)}static parents(e,t){return _t.domDir(e,"parentNode",t,"parents")}parents(e){return _t.parents(this,e)}static next(e){return _t._getSibling(e,"nextSibling","next")}next(){return _t.next(this)}static prev(e){return _t._getSibling(e,"previousSibling","prev")}prev(){return _t.prev(this)}static nextAll(e){return _t.domDir(e,"nextSibling",void 0,"nextAll")}nextAll(){return _t.nextAll(this)}static prevAll(e){return _t.domDir(e,"previousSibling",void 0,"prevAll")}prevAll(){return _t.prevAll(this)}static nextUntil(e,t){return _t.domDir(e,"nextSibling",t,"nextUtil")}nextUntil(e){return _t.nextUntil(this,e)}static prevUntil(e,t){return _t.domDir(e,"previousSibling",t,"prevUtil")}prevUntil(e){return _t.prevUntil(this,e)}static siblings(e){const t=_t._preNodeElemWithNull(e,"siblings");return _t._getSiblings(t&&t.parentNode?t.parentNode.firstChild:null,t)}siblings(){return _t.siblings(this)}static children(e){const t=_t._preNodeElemWithNull(e,"children");return _t._getSiblings(t?t.firstChild:null)}children(){return _t.children(this)}static contents(e){const t=_t._preNodeElemWithNull(e,"contents");return t instanceof HTMLIFrameElement&&null!=t.contentDocument&&Object.getPrototypeOf(t.contentDocument)?[t.contentDocument]:t instanceof HTMLTemplateElement?Array.from((t.content||t).childNodes):t?Array.from(t.childNodes):[]}contents(){return _t.contents(this)}static clone(e,t=!0){if("boolean"!=typeof t)throw new TypeError('The "deep" must be a boolean.');return _t._preNodeElems(e,"clone").map(e=>e.cloneNode(t))}clone(e){return _t.clone(this,e)[0]}static _appendChecker(e,...t){const r=[];for(const i of t)if(null!=i&&!1!==i)if("string"!=typeof i&&"number"!=typeof i)if(i instanceof Node||i instanceof _t)r.push(..._t._preNodeElems(i,e));else if(Array.isArray(i))r.push(..._t._appendChecker(e,...i));else for(const t in i){const s=i[t];r.push(..._t._appendChecker(e,s))}else r.push(i);return r}static append(e,...t){return _t._preElem(e,"append").append(..._t._appendChecker("append",...t)),e}append(...e){return _t.append(this,...e)}static prepend(e,...t){return _t._preElem(e,"prepend").prepend(..._t._appendChecker("prepend",...t)),e}prepend(...e){return _t.prepend(this,...e)}static before(e,...t){return _t._preElem(e,"before").before(..._t._appendChecker("before",...t)),e}before(...e){return _t.before(this,...e)}static after(e,...t){return _t._preElem(e,"after").after(..._t._appendChecker("after",...t)),e}after(...e){return _t.after(this,...e)}static replaceWith(e,...t){return _t._preElem(e,"replaceWith").replaceWith(..._t._appendChecker("replaceWith",...t)),e}replaceWith(...e){return _t.replaceWith(this,...e)}static appendTo(e,t){const r=_t._preNodeElems(e,"appendTo"),i=_t._preNodeElems(t,"appendTo");return i.forEach((e,t)=>{r.forEach(r=>e.appendChild(t===i.length-1?r:r.cloneNode(!0)))}),e}appendTo(e){return _t.appendTo(this,e)}static prependTo(e,t){const r=_t._preElems(e,"prependTo"),i=_t._preElems(t,"prependTo");return i.forEach((e,t)=>{r.slice().reverse().forEach(r=>e.prepend(t===i.length-1?r:r.cloneNode(!0)))}),e}prependTo(e){return _t.prependTo(this,e)}static insertBefore(e,t,r=null){const i=_t._preNodeElem(e,"insertBefore"),s=_t._preNodeElem(t,"insertBefore"),n=_t._preNodeElemWithNull(r,"insertBefore");if(!s.parentNode)throw new Error("The target element has no parent node to insert before.");return s.parentNode.insertBefore(i,n||s),e}insertBefore(e,t){return _t.insertBefore(this,e,t)}static insertAfter(e,t,r=null){const i=_t._preNodeElem(e,"insertAfter"),s=_t._preNodeElem(t,"insertBefore"),n=_t._preNodeElemWithNull(r,"insertBefore");if(!s.parentNode)throw new Error("The target element has no parent node to insert after.");return s.parentNode.insertBefore(i,n||s.nextSibling),e}insertAfter(e,t){return _t.insertAfter(this,e,t)}static replaceAll(e,t){const r=_t._preNodeElems(e,"replaceAll"),i=_t._preNodeElems(t,"replaceAll");return i.forEach((e,t)=>{const s=e.parentNode;r.forEach(r=>{s&&s.replaceChild(t===i.length-1?r:r.cloneNode(!0),e)})}),e}replaceAll(e){return _t.replaceAll(this,e)}#G;get size(){return this.#G.length}static _elCheck(e){for(const t of e)if(!(t instanceof Element||t instanceof Window||t instanceof Document||t instanceof Text))throw new Error("[TinyHtml] Invalid Target in constructor.")}add(e){return new _t([...this.#G,..._t._selector(e)])}static _selector(e){if(e instanceof _t)throw new Error("[TinyHtml] You are trying to put a TinyHtml inside another TinyHtml in constructor.");const t=e=>Array.from(new Set(e)),r="string"!=typeof e?e:document.querySelectorAll(e);if(Array.isArray(r))return _t._elCheck(r),t(r);if(r instanceof NodeList||r instanceof HTMLCollection){const e=[...r];return _t._elCheck(e),t(e)}{const e=[r];return _t._elCheck(e),t(e)}}constructor(e){this.#G=_t._selector(e),this.#se=_t.#ne}static isWindow(e){return null!=e&&e===e.window}static css(e){const t=_t._preElem(e,"css");return window.getComputedStyle(t)}css(){return _t.css(this)}static cssString(e,t){const r=_t._preElem(e,"cssString");if("string"!=typeof t)throw new TypeError("The prop must be a string.");const i=window.getComputedStyle(r)[t];return"string"==typeof i?i:"number"==typeof i?i.toString():null}cssString(e){return _t.cssString(this,e)}static cssList(e,t){const r=_t._preElem(e,"cssList");if(!Array.isArray(t))throw new TypeError("The prop must be an array of strings.");const i=window.getComputedStyle(r),s={};for(const e of t)void 0!==e&&(s[e]=i.getPropertyValue(e));return s}cssList(e){return _t.cssList(this,e)}static cssFloat(e,t){const r=_t._preElem(e,"cssFloat");if("string"!=typeof t)throw new TypeError("The prop must be a string.");const i=window.getComputedStyle(r)[t];return parseFloat(i)||0}cssFloat(e){return _t.cssFloat(this,e)}static cssFloats(e,t){const r=_t._preElem(e,"cssFloats");if(!Array.isArray(t))throw new TypeError("The prop must be an array of strings.");const i=window.getComputedStyle(r),s={};for(const e of t)s[e]=parseFloat(i[e])||0;return s}cssFloats(e){return _t.cssFloats(this,e)}static#oe={alignContent:"align-content",alignItems:"align-items",alignSelf:"align-self",animationDelay:"animation-delay",animationDirection:"animation-direction",animationDuration:"animation-duration",animationFillMode:"animation-fill-mode",animationIterationCount:"animation-iteration-count",animationName:"animation-name",animationPlayState:"animation-play-state",animationTimingFunction:"animation-timing-function",backfaceVisibility:"backface-visibility",backgroundAttachment:"background-attachment",backgroundBlendMode:"background-blend-mode",backgroundClip:"background-clip",backgroundColor:"background-color",backgroundImage:"background-image",backgroundOrigin:"background-origin",backgroundPosition:"background-position",backgroundRepeat:"background-repeat",backgroundSize:"background-size",borderBottom:"border-bottom",borderBottomColor:"border-bottom-color",borderBottomLeftRadius:"border-bottom-left-radius",borderBottomRightRadius:"border-bottom-right-radius",borderBottomStyle:"border-bottom-style",borderBottomWidth:"border-bottom-width",borderCollapse:"border-collapse",borderColor:"border-color",borderImage:"border-image",borderImageOutset:"border-image-outset",borderImageRepeat:"border-image-repeat",borderImageSlice:"border-image-slice",borderImageSource:"border-image-source",borderImageWidth:"border-image-width",borderLeft:"border-left",borderLeftColor:"border-left-color",borderLeftStyle:"border-left-style",borderLeftWidth:"border-left-width",borderRadius:"border-radius",borderRight:"border-right",borderRightColor:"border-right-color",borderRightStyle:"border-right-style",borderRightWidth:"border-right-width",borderSpacing:"border-spacing",borderStyle:"border-style",borderTop:"border-top",borderTopColor:"border-top-color",borderTopLeftRadius:"border-top-left-radius",borderTopRightRadius:"border-top-right-radius",borderTopStyle:"border-top-style",borderTopWidth:"border-top-width",borderWidth:"border-width",boxDecorationBreak:"box-decoration-break",boxShadow:"box-shadow",boxSizing:"box-sizing",breakAfter:"break-after",breakBefore:"break-before",breakInside:"break-inside",captionSide:"caption-side",caretColor:"caret-color",clipPath:"clip-path",columnCount:"column-count",columnFill:"column-fill",columnGap:"column-gap",columnRule:"column-rule",columnRuleColor:"column-rule-color",columnRuleStyle:"column-rule-style",columnRuleWidth:"column-rule-width",columnSpan:"column-span",columnWidth:"column-width",counterIncrement:"counter-increment",counterReset:"counter-reset",emptyCells:"empty-cells",flexBasis:"flex-basis",flexDirection:"flex-direction",flexFlow:"flex-flow",flexGrow:"flex-grow",flexShrink:"flex-shrink",flexWrap:"flex-wrap",fontFamily:"font-family",fontFeatureSettings:"font-feature-settings",fontKerning:"font-kerning",fontLanguageOverride:"font-language-override",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontSynthesis:"font-synthesis",fontVariant:"font-variant",fontVariantAlternates:"font-variant-alternates",fontVariantCaps:"font-variant-caps",fontVariantEastAsian:"font-variant-east-asian",fontVariantLigatures:"font-variant-ligatures",fontVariantNumeric:"font-variant-numeric",fontVariantPosition:"font-variant-position",fontWeight:"font-weight",gridArea:"grid-area",gridAutoColumns:"grid-auto-columns",gridAutoFlow:"grid-auto-flow",gridAutoRows:"grid-auto-rows",gridColumn:"grid-column",gridColumnEnd:"grid-column-end",gridColumnGap:"grid-column-gap",gridColumnStart:"grid-column-start",gridGap:"grid-gap",gridRow:"grid-row",gridRowEnd:"grid-row-end",gridRowGap:"grid-row-gap",gridRowStart:"grid-row-start",gridTemplate:"grid-template",gridTemplateAreas:"grid-template-areas",gridTemplateColumns:"grid-template-columns",gridTemplateRows:"grid-template-rows",imageRendering:"image-rendering",justifyContent:"justify-content",letterSpacing:"letter-spacing",lineBreak:"line-break",lineHeight:"line-height",listStyle:"list-style",listStyleImage:"list-style-image",listStylePosition:"list-style-position",listStyleType:"list-style-type",marginBottom:"margin-bottom",marginLeft:"margin-left",marginRight:"margin-right",marginTop:"margin-top",maskClip:"mask-clip",maskComposite:"mask-composite",maskImage:"mask-image",maskMode:"mask-mode",maskOrigin:"mask-origin",maskPosition:"mask-position",maskRepeat:"mask-repeat",maskSize:"mask-size",maskType:"mask-type",maxHeight:"max-height",maxWidth:"max-width",minHeight:"min-height",minWidth:"min-width",mixBlendMode:"mix-blend-mode",objectFit:"object-fit",objectPosition:"object-position",offsetAnchor:"offset-anchor",offsetDistance:"offset-distance",offsetPath:"offset-path",offsetRotate:"offset-rotate",outlineColor:"outline-color",outlineOffset:"outline-offset",outlineStyle:"outline-style",outlineWidth:"outline-width",overflowAnchor:"overflow-anchor",overflowWrap:"overflow-wrap",overflowX:"overflow-x",overflowY:"overflow-y",paddingBottom:"padding-bottom",paddingLeft:"padding-left",paddingRight:"padding-right",paddingTop:"padding-top",pageBreakAfter:"page-break-after",pageBreakBefore:"page-break-before",pageBreakInside:"page-break-inside",perspectiveOrigin:"perspective-origin",placeContent:"place-content",placeItems:"place-items",placeSelf:"place-self",pointerEvents:"pointer-events",rowGap:"row-gap",scrollBehavior:"scroll-behavior",scrollMargin:"scroll-margin",scrollMarginBlock:"scroll-margin-block",scrollMarginBlockEnd:"scroll-margin-block-end",scrollMarginBlockStart:"scroll-margin-block-start",scrollMarginBottom:"scroll-margin-bottom",scrollMarginInline:"scroll-margin-inline",scrollMarginInlineEnd:"scroll-margin-inline-end",scrollMarginInlineStart:"scroll-margin-inline-start",scrollMarginLeft:"scroll-margin-left",scrollMarginRight:"scroll-margin-right",scrollMarginTop:"scroll-margin-top",scrollPadding:"scroll-padding",scrollPaddingBlock:"scroll-padding-block",scrollPaddingBlockEnd:"scroll-padding-block-end",scrollPaddingBlockStart:"scroll-padding-block-start",scrollPaddingBottom:"scroll-padding-bottom",scrollPaddingInline:"scroll-padding-inline",scrollPaddingInlineEnd:"scroll-padding-inline-end",scrollPaddingInlineStart:"scroll-padding-inline-start",scrollPaddingLeft:"scroll-padding-left",scrollPaddingRight:"scroll-padding-right",scrollPaddingTop:"scroll-padding-top",scrollSnapAlign:"scroll-snap-align",scrollSnapStop:"scroll-snap-stop",scrollSnapType:"scroll-snap-type",shapeImageThreshold:"shape-image-threshold",shapeMargin:"shape-margin",shapeOutside:"shape-outside",tabSize:"tab-size",tableLayout:"table-layout",textAlign:"text-align",textAlignLast:"text-align-last",textCombineUpright:"text-combine-upright",textDecoration:"text-decoration",textDecorationColor:"text-decoration-color",textDecorationLine:"text-decoration-line",textDecorationStyle:"text-decoration-style",textIndent:"text-indent",textJustify:"text-justify",textOrientation:"text-orientation",textOverflow:"text-overflow",textShadow:"text-shadow",textTransform:"text-transform",transformBox:"transform-box",transformOrigin:"transform-origin",transformStyle:"transform-style",transitionDelay:"transition-delay",transitionDuration:"transition-duration",transitionProperty:"transition-property",transitionTimingFunction:"transition-timing-function",unicodeBidi:"unicode-bidi",userSelect:"user-select",verticalAlign:"vertical-align",whiteSpace:"white-space",willChange:"will-change",wordBreak:"word-break",wordSpacing:"word-spacing",wordWrap:"word-wrap",writingMode:"writing-mode",zIndex:"z-index",WebkitTransform:"-webkit-transform",WebkitTransition:"-webkit-transition",WebkitBoxShadow:"-webkit-box-shadow",MozBoxShadow:"-moz-box-shadow",MozTransform:"-moz-transform",MozTransition:"-moz-transition",msTransform:"-ms-transform",msTransition:"-ms-transition"};static cssPropAliases=new Proxy(_t.#oe,{set:(e,t,r)=>(e[t]=r,_t.cssPropRevAliases[r]=t,!0)});static cssPropRevAliases=Object.fromEntries(Object.entries(_t.#oe).map(([e,t])=>[t,e]));static toStyleKc(e){return"string"==typeof _t.cssPropAliases[e]?_t.cssPropAliases[e]:e}static toStyleCc(e){return"string"==typeof _t.cssPropRevAliases[e]?_t.cssPropRevAliases[e]:e}static setStyle(e,t,r=null){return _t._preHtmlElems(e,"setStyle").forEach(e=>{if("object"==typeof t)for(const[r,i]of Object.entries(t))e.style.setProperty(_t.toStyleKc(r),"string"==typeof i?i:"number"==typeof i?`${i}px`:String(i));else e.style.setProperty(_t.toStyleKc(t),r)}),e}setStyle(e,t){return _t.setStyle(this,e,t)}static getStyle(e,t){return _t._preHtmlElem(e,"getStyle").style.getPropertyValue(_t.toStyleKc(t))}getStyle(e){return _t.getStyle(this,e)}static style(e,{camelCase:t=!1,rawAttr:r=!1}={}){if("boolean"!=typeof t)throw new TypeError('"camelCase" must be a boolean. Received: '+typeof t);if("boolean"!=typeof r)throw new TypeError('"rawAttr" must be a boolean. Received: '+typeof r);const i=_t._preHtmlElem(e,"style"),s={};if(r){const e=(i.getAttribute("style")||"").split(";");for(const r of e){const[e,i]=r.split(":");if(!e||!i)continue;const n=e.trim(),o=i.trim();s[t?_t.toStyleCc(n):n]=o}}else{const e=i.style;for(let r=0;r<e.length;r++){const i=e[r],n=e.getPropertyValue(i);s[t?_t.toStyleCc(i):i]=n}}return s}style(e){return _t.style(this,e)}static removeStyle(e,t){return _t._preHtmlElems(e,"removeStyle").forEach(e=>{if(Array.isArray(t))for(const r of t)e.style.removeProperty(_t.toStyleKc(r));else e.style.removeProperty(_t.toStyleKc(t))}),e}removeStyle(e){return _t.removeStyle(this,e)}static toggleStyle(e,t,r,i){return _t._preHtmlElems(e,"toggleStyle").forEach(e=>{const s=_t.getStyle(e,t).trim()===_t.toStyleKc(r)?i:r;_t.setStyle(e,t,s)}),e}toggleStyle(e,t,r){return _t.toggleStyle(this,e,t,r)}static clearStyle(e){return _t._preElems(e,"clearStyle").forEach(e=>e.removeAttribute("style")),e}clearStyle(){return _t.clearStyle(this)}static focus(e){return _t._preHtmlElem(e,"focus").focus(),e}focus(){return _t.focus(this)}static blur(e){return _t._preHtmlElem(e,"blur").blur(),e}blur(){return _t.blur(this)}static select(e){const t=_t._preHtmlElem(e,"select");if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement))throw new Error("Element must be an <input> or <textarea> to use select().");return t.select(),e}select(){return _t.select(this)}static boolCheck(e){return void 0!==e&&("true"===e||"1"===e||!0===e||"on"===e||"number"==typeof e&&e>0)}static setWinScrollTop(e){if("number"!=typeof e)throw new TypeError("The value must be a number.");_t.setScrollTop(window,e)}static setWinScrollLeft(e){if("number"!=typeof e)throw new TypeError("The value must be a number.");_t.setScrollLeft(window,e)}static winScrollTop(){return window.scrollY||document.documentElement.scrollTop}static winScrollLeft(){return window.scrollX||document.documentElement.scrollLeft}static winInnerHeight(){return window.innerHeight||document.documentElement.clientHeight}static winInnerWidth(){return window.innerWidth||document.documentElement.clientWidth}static isPageTop(){return 0===window.scrollY}static isPageBottom(){return window.innerHeight+window.scrollY>=document.body.offsetHeight}static getDimension(e,t,r="content"){const i=_t._preElemAndWinAndDoc(e,"getDimension");if("string"!=typeof t)throw new TypeError("The type must be a string.");if("string"!=typeof r)throw new TypeError("The extra must be a string.");const s="width"===t?"Width":"Height";if(_t.isWindow(i))return"margin"===r?i["inner"+s]:i.document.documentElement["client"+s];const n=i;if(9===n.nodeType){const e=n.documentElement;return Math.max(n.body["scroll"+s],e["scroll"+s],n.body["offset"+s],e["offset"+s],e["client"+s])}let o=n.getBoundingClientRect()[t];function a(e){return"width"===t?_t.cssFloat(n,e+"Left")+_t.cssFloat(n,e+"Right"):_t.cssFloat(n,e+"Top")+_t.cssFloat(n,e+"Bottom")}switch(r){case"content":o-=a("padding"),o-=a("border");break;case"padding":o-=a("border");break;case"border":break;case"margin":o+=a("margin")}return o}getDimension(e,t){return _t.getDimension(this,e,t)}static setHeight(e,t){const r=_t._preHtmlElem(e,"setHeight");if("number"!=typeof t&&"string"!=typeof t)throw new TypeError("The value must be a string or number.");return r.style.height="number"==typeof t?`${t}px`:t,e}setHeight(e){return _t.setHeight(this,e)}set height(e){_t.setHeight(this,e)}static setWidth(e,t){const r=_t._preHtmlElem(e,"setWidth");if("number"!=typeof t&&"string"!=typeof t)throw new TypeError("The value must be a string or number.");return r.style.width="number"==typeof t?`${t}px`:t,e}setWidth(e){return _t.setWidth(this,e)}set width(e){_t.setWidth(this,e)}static height(e){const t=_t._preElemAndWinAndDoc(e,"height");return _t.getDimension(t,"height","content")}get height(){return _t.height(this)}static width(e){const t=_t._preElemAndWinAndDoc(e,"width");return _t.getDimension(t,"width","content")}get width(){return _t.width(this)}static innerHeight(e){const t=_t._preElemAndWinAndDoc(e,"innerHeight");return _t.getDimension(t,"height","padding")}innerHeight(){return _t.innerHeight(this)}static innerWidth(e){const t=_t._preElemAndWinAndDoc(e,"innerWidth");return _t.getDimension(t,"width","padding")}innerWidth(){return _t.innerWidth(this)}static outerHeight(e,t=!1){if("boolean"!=typeof t)throw new TypeError('The "includeMargin" must be a boolean.');const r=_t._preElemAndWinAndDoc(e,"outerHeight");return _t.getDimension(r,"height",t?"margin":"border")}outerHeight(e){return _t.outerHeight(this,e)}static outerWidth(e,t=!1){if("boolean"!=typeof t)throw new TypeError('The "includeMargin" must be a boolean.');const r=_t._preElemAndWinAndDoc(e,"outerWidth");return _t.getDimension(r,"width",t?"margin":"border")}outerWidth(e){return _t.outerWidth(this,e)}#se="";get mainDisplay(){return this.#se}set mainDisplay(e){if("string"!=typeof e)throw new TypeError("mainDisplay must be a string.");this.#se=e}static#ne="block";static get defaultDisplay(){return _t.#ne}static set defaultDisplay(e){if("string"!=typeof e)throw new TypeError("defaultDisplay must be a string.");_t.#ne=e}static getAnimateData(e,t){let r=Mt.get(e);return r||(r={},Mt.set(e,r)),r[t]}static setAnimateData(e,t,r){if(!(e instanceof HTMLElement))throw new TypeError("setAnimateData: el must be an HTMLElement.");if("string"!=typeof t)throw new TypeError("setAnimateData: where must be a string.");if("string"!=typeof r&&"number"!=typeof r)throw new TypeError("setAnimateData: value must be a string or number.");let i=Mt.get(e);i||(i={},Mt.set(e,i)),i[t]=r}static#ae=!0;static get cancelOldStyleFx(){return _t.#ae}static set cancelOldStyleFx(e){if("boolean"!=typeof e)throw new TypeError("Expected a boolean value.");_t.#ae=e}static#le={slow:{duration:600,easing:"ease"},fast:{duration:200,easing:"ease-out"},_default:{duration:400,easing:"linear"}};static get styleFxSpeeds(){const e={};for(const t in _t.#le){const r=_t.#le[t];e[t]="object"==typeof r?{...r}:r}return e}static set styleFxSpeeds(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleFxSpeeds must be an object.");for(const[t,r]of Object.entries(e))if("number"!=typeof r&&"object"!=typeof r)throw new TypeError(`styleFxSpeeds["${t}"] must be a number or KeyframeAnimationOptions.`);_t.#le={};for(const[t,r]of Object.entries(e))_t.setStyleFxSpeed(t,r)}static getStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');const t=_t.#le[e];return"object"==typeof t?{...t}:t}static setStyleFxSpeed(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("number"!=typeof t&&"object"!=typeof t)throw new TypeError("styleFxSpeed must be a number or KeyframeAnimationOptions");_t.#le[e]="object"==typeof t?{...t}:t}static deleteStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#le[e]}static hasStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#le,e)}static#he=["Top","Right","Bottom","Left"];static#ue={slideDown:_t.genStyleFx("show"),slideUp:_t.genStyleFx("hide"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}};static get styleEffects(){return JSON.parse(JSON.stringify(_t.#ue))}static set styleEffects(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleEffects must be an object");for(const t in e)for(const[r,i]of Object.entries(e[t]))if(!("string"==typeof i||Array.isArray(i)&&i.every(e=>"string"==typeof e||"number"==typeof e)))throw new TypeError(`Invalid styleEffect["${r}"]`);_t.#ue={};for(const t in e)_t.setStyleEffect(t,e[t])}static getStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');const t=_t.#ue[e];return t?JSON.parse(JSON.stringify(t)):void 0}static setStyleEffect(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("styleEffect must be an object");const r={};for(const[e,i]of Object.entries(t))if("string"==typeof i)r[e]=i;else{if(!Array.isArray(i)||!i.every(e=>"string"==typeof e||"number"==typeof e))throw new TypeError(`Invalid styleEffect["${e}"]`);r[e]=[...i]}_t.#ue[e]=r}static deleteStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#ue[e]}static hasStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#ue,e)}static#ce={slideDown:"slideUp",slideUp:"slideDown",fadeIn:"fadeOut",fadeOut:"fadeIn",fadeTo:"fadeIn"};static get styleEffectInverse(){return{..._t.#ce}}static set styleEffectInverse(e){if("object"!=typeof e||null===e)throw new TypeError("styleEffectInverse must be an object.");for(const[t,r]of Object.entries(e))if("string"!=typeof r)throw new TypeError(`styleEffectInverse["${t}"] must be a string.`);_t.#ce={};for(const[t,r]of Object.entries(e))_t.setStyleEffectInverse(t,r)}static getStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#ce[e]||null}static setStyleEffectInverse(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("string"!=typeof t)throw new TypeError(`styleEffectInverse["${e}"] must be a string.`);_t.#ce[e]=t}static deleteStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#ce[e]}static hasStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#ce,e)}static#de={slideDown:e=>e.height[0]===e.height[1]&&(!e.width||e.width[0]===e.width[1]),slideUp:e=>e.height[0]===e.height[1]&&(!e.width||e.width[0]===e.width[1]),fadeIn:e=>Number(e.opacity[0])===Number(e.opacity[1]),fadeOut:e=>Number(e.opacity[0])===Number(e.opacity[1])};static get styleEffectsRd(){return{..._t.#de}}static set styleEffectsRd(e){if("object"!=typeof e||null===e)throw new TypeError("styleEffectsRd must be an object.");for(const[t,r]of Object.entries(e))if("function"!=typeof r)throw new TypeError(`styleEffectsRd["${t}"] must be a function.`);_t.#de={};for(const[t,r]of Object.entries(e))_t.setStyleEffectRd(t,r)}static getStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#de[e]||null}static setStyleEffectRd(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("function"!=typeof t)throw new TypeError(`styleEffectsRd["${e}"] must be a function.`);_t.#de[e]=t}static deleteStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#de[e]}static hasStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#de,e)}static#pe={show:(e,t,r,i)=>{if("height"===r||"width"===r){const s=_t.getAnimateData(e,`orig${r}`)||e.scrollHeight+"px";_t.setAnimateData(e,`orig${r}`,s);const n=i[r];t[r]=[n,s]}else if(r.startsWith("margin")||r.startsWith("padding")){const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=["0px",s]}else if("opacity"===r){const e=i.opacity;t[r]=[e,1]}else{const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[s,i[r]||1]}},hide:(e,t,r,i)=>{if("height"===r||"width"===r){const s=_t.getAnimateData(e,`orig${r}`)||i[r];_t.setAnimateData(e,`orig${r}`,s);const n=i[r];t[r]=[n,0]}else if(r.startsWith("margin")||r.startsWith("padding")){const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[i[r],"0px"]}else if("opacity"===r){const e=i.opacity;t[r]=[e,0]}else{const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[s,0]}}};static get styleEffectsProps(){return{..._t.#pe}}static set styleEffectsProps(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleEffectsProps must be an object");for(const[t,r]of Object.entries(e))if("function"!=typeof r)throw new TypeError(`styleEffectsProps["${t}"] must be a function`);_t.#pe={};for(const[t,r]of Object.entries(e))_t.setStyleEffectProp(t,r)}static getStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#pe[e]||null}static setStyleEffectProp(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("function"!=typeof t)throw new TypeError(`styleEffectsProps["${e}"] must be a function`);_t.#pe[e]=t}static deleteStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#pe[e]}static hasStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#pe,e)}static genStyleFx(e,t=!1){if("string"!=typeof e)throw new TypeError("genStyleFx: type must be a string.");if("boolean"!=typeof t)throw new TypeError("genStyleFx: includeWidth must be a boolean.");let r,i=0;const s={height:e},n=t?1:0;for(;i<4;i+=2-n)r=_t.#he[i],s["margin"+r]=e,s["padding"+r]=e;return t&&(s.opacity=e,s.width=e),s}static applyStyleFx(e,t,r,i){if("string"!=typeof t)throw new TypeError("applyStyleFx: id must be a string.");if("object"!=typeof r||null===r)throw new TypeError("applyStyleFx: props must be a non-null object.");if(void 0!==i&&"number"!=typeof i&&"string"!=typeof i&&("object"!=typeof i||null===i))throw new TypeError("applyStyleFx: ops must be a number, string, KeyframeAnimationOptions, or undefined.");const s=new Map;return _t._preHtmlElems(e,"applyStyleFx").forEach(n=>{const o={};for(const[e,t]of Object.entries(r))if("string"==typeof t&&this.#pe[t]){const r=getComputedStyle(n);this.#pe[t](n,o,e,r)}else{if("object"!=typeof t)throw new TypeError(`applyStyleFx: invalid action for prop "${e}". Must be string or array.`);o[e]=t}if("function"==typeof _t.#de[t]&&_t.#de[t](o))return void s.set(n,null);const a=[],l=o[Object.keys(o)[0]].length;for(let e=0;e<l;e++){const t={};for(const r in o)t[r]=o[r][e];a.push(t)}s.set(n,_t.animate(e,a,i,t)[0])}),s}applyStyleFx(e,t,r){return _t.applyStyleFx(this,e,t,r)}static getCurrentAnimationId(e){if(!(e instanceof HTMLElement))throw new TypeError("Expected an HTMLElement.");return Lt.get(e)?.id??void 0}static animate(e,t,r=_t.#le._default,i=null,s=_t.#ae){const n="string"==typeof r?_t.#le[r]??void 0:"number"!=typeof r?{...r}:r;"object"==typeof n&&void 0===n.fill&&(n.fill="forwards");const o=[];return _t._preHtmlElems(e,"animate").forEach(e=>{if(s){const t=Lt.get(e);t&&t.animation.cancel()}const r=e.animate(t,n);o.push(r),Lt.set(e,{animation:r,id:i??""}),r.addEventListener("finish",()=>{Lt.get(e)?.animation===r&&Lt.delete(e)})}),o}animate(e,t,r,i){return _t.animate(this,e,t,r,i)}static stop(e){const t=[];return _t._preHtmlElems(e,"stop").forEach(e=>{const r=Lt.get(e);r?(r.animation.cancel(),Lt.delete(e),t.push(!0)):t.push(!1)}),t}stop(){return _t.stop(this)}static slideDown(e,t){return _t.applyStyleFx(e,"slideDown",this.#ue.slideDown,t??{duration:500,easing:"ease-out"})}slideDown(e){return _t.slideDown(this,e)}static slideUp(e,t){return _t.applyStyleFx(e,"slideUp",this.#ue.slideUp,t??{duration:500,easing:"ease-out"})}slideUp(e){return _t.slideUp(this,e)}static slideToggle(e,t){const r=_t._preHtmlElem(e,"slideToggle"),i=getComputedStyle(r),s=_t.getCurrentAnimationId(r),n="none"===i.display||0===r.offsetHeight;return("string"==typeof s?"slideUp"===s:n)?_t.slideDown(e,t):_t.slideUp(e,t)}slideToggle(e){return _t.slideToggle(this,e)}static fadeIn(e,t){return _t.applyStyleFx(e,"fadeIn",this.#ue.fadeIn,t)}fadeIn(e){return _t.fadeIn(this,e)}static fadeOut(e,t){return _t.applyStyleFx(e,"fadeOut",this.#ue.fadeOut,t)}fadeOut(e){return _t.fadeOut(this,e)}static fadeToggle(e,t){const r=_t._preHtmlElem(e,"fadeToggle"),i=getComputedStyle(r),s=_t.getCurrentAnimationId(r),n="0"===i.opacity||null===r.offsetParent;return("string"==typeof s?"fadeOut"===s:n)?_t.fadeIn(e,t):_t.fadeOut(e,t)}fadeToggle(e){return _t.fadeToggle(this,e)}static fadeTo(e,t,r,i=_t.#ne){if("number"!=typeof t||isNaN(t)||t<0||t>1)throw new TypeError("fadeTo: opacity must be a number between 0 and 1.");if(void 0!==r&&"number"!=typeof r&&"string"!=typeof r&&("object"!=typeof r||null===r))throw new TypeError("fadeTo: ops must be a number, string, KeyframeAnimationOptions, or undefined.");const s=new Map;return _t._preHtmlElems(e,"fadeTo").forEach(n=>{const o=getComputedStyle(n);if(!(e instanceof Element&&(e.offsetWidth||e.offsetHeight||e.getClientRects().length))){const e=_t.getAnimateData(n,"origdisplay");n.style.display="string"==typeof e?e:i}const a=[o.opacity,t].map(e=>({opacity:e}));s.set(n,_t.animate(n,a,r,"fadeTo")[0])}),s}fadeTo(e,t,r=this.#se){return _t.fadeTo(this,e,t,r)}static offset(e){const t=_t._preElem(e,"offset").getBoundingClientRect(),r=window.scrollY||document.documentElement.scrollTop,i=window.scrollX||document.documentElement.scrollLeft;return{top:t.top+r,left:t.left+i}}offset(){return _t.offset(this)}static position(e){const t=_t._preHtmlElem(e,"position");let r,i,s={top:0,left:0};if("fixed"===window.getComputedStyle(t).position)i=t.getBoundingClientRect();else{i=_t.offset(t),r=t.offsetParent||document.documentElement;const{position:e}=window.getComputedStyle(r);for(;r instanceof HTMLElement&&(r===document.body||r===document.documentElement)&&"static"===e;)r=r.parentNode;if(r instanceof HTMLElement&&r!==t&&1===r.nodeType){const{borderTopWidth:e,borderLeftWidth:t}=_t.cssFloats(r,["borderTopWidth","borderLeftWidth"]);s=_t.offset(r),s.top+=e,s.left+=t}}return{top:i.top-s.top-_t.cssFloat(t,"marginTop"),left:i.left-s.left-_t.cssFloat(t,"marginLeft")}}position(){return _t.position(this)}static offsetParent(e){let t=_t._preHtmlElem(e,"offsetParent").offsetParent;for(;t instanceof HTMLElement&&"static"===window.getComputedStyle(t).position;)t=t.offsetParent;return t instanceof HTMLElement?t:document.documentElement}offsetParent(){return _t.offsetParent(this)}static scrollTop(e){const t=_t._preElemAndWindow(e,"scrollTop");return _t.isWindow(t)?t.pageYOffset:9===t.nodeType?t.defaultView.pageYOffset:t.scrollTop}scrollTop(){return _t.scrollTop(this)}static scrollLeft(e){const t=_t._preElemAndWindow(e,"scrollLeft");return _t.isWindow(t)?t.pageXOffset:9===t.nodeType?t.defaultView.pageXOffset:t.scrollLeft}scrollLeft(){return _t.scrollLeft(this)}static easings={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:(4-2*e)*e-1,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1};static scrollToXY(e,{targetX:t,targetY:r,duration:i,easing:s,onAnimation:n}={}){if(void 0!==t&&"number"!=typeof t)throw new TypeError("`targetX` must be a number if provided.");if(void 0!==r&&"number"!=typeof r)throw new TypeError("`targetY` must be a number if provided.");if(void 0!==i&&"number"!=typeof i)throw new TypeError("`duration` must be a number if provided.");if(void 0!==s&&"string"!=typeof s)throw new TypeError("`easing` must be a string if provided.");if(void 0!==s&&"function"!=typeof _t.easings[s])throw new TypeError(`Unknown easing function: "${s}".`);if(void 0!==n&&"function"!=typeof n)throw new TypeError("`onAnimation` must be a function if provided.");const o=(e,t,r,i)=>{if(e instanceof Window)window.scrollTo(t,r);else if(9===e.nodeType)e.defaultView.scrollTo(t,r);else{const i=e instanceof Window?window.scrollX:e.scrollLeft,s=e instanceof Window?window.scrollY:e.scrollTop;i!==t&&(e.scrollLeft=t),s!==r&&(e.scrollTop=r)}"function"==typeof n&&n({x:t,y:r,isComplete:i>=1,time:i})};return _t._preElemsAndWindow(e,"scrollToXY").forEach(e=>{const n=e instanceof Window?window.scrollX:e.scrollLeft,a=e instanceof Window?window.scrollY:e.scrollTop,l=t??n,h=r??a,u=l-n,c=h-a,d="string"==typeof s&&_t.easings[s]||null;if("number"!=typeof i||"function"!=typeof d)return o(e,l,h,1);const p=performance.now(),m=i??0;requestAnimationFrame(function t(r){if("function"!=typeof d)return;const i=Math.min(1,(r-p)/m),s=d(i);o(e,n+u*s,a+c*s,i),i<1&&requestAnimationFrame(t)})}),e}scrollToXY({targetX:e,targetY:t,duration:r,easing:i,onAnimation:s}={}){return _t.scrollToXY(this,{targetX:e,targetY:t,duration:r,easing:i,onAnimation:s})}static setScrollTop(e,t){if("number"!=typeof t)throw new TypeError("ScrollTop value must be a number.");return _t.scrollToXY(e,{targetY:t})}setScrollTop(e){return _t.setScrollTop(this,e)}static setScrollLeft(e,t){if("number"!=typeof t)throw new TypeError("ScrollLeft value must be a number.");return _t.scrollToXY(e,{targetX:t})}setScrollLeft(e){return _t.setScrollLeft(this,e)}static borderWidth(e){const t=_t._preElem(e,"borderWidth"),{borderLeftWidth:r,borderRightWidth:i,borderTopWidth:s,borderBottomWidth:n}=_t.cssFloats(t,["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}borderWidth(){return _t.borderWidth(this)}static border(e){const t=_t._preElem(e,"border"),{borderLeft:r,borderRight:i,borderTop:s,borderBottom:n}=_t.cssFloats(t,["borderLeft","borderRight","borderTop","borderBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}border(){return _t.border(this)}static margin(e){const t=_t._preElem(e,"margin"),{marginLeft:r,marginRight:i,marginTop:s,marginBottom:n}=_t.cssFloats(t,["marginLeft","marginRight","marginTop","marginBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}margin(){return _t.margin(this)}static padding(e){const t=_t._preElem(e,"padding"),{paddingLeft:r,paddingRight:i,paddingTop:s,paddingBottom:n}=_t.cssFloats(t,["paddingLeft","paddingRight","paddingTop","paddingBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}padding(){return _t.padding(this)}static#me=!1;static get classCanWhitespace(){return this.#me}static set classCanWhitespace(e){if("boolean"!=typeof e)throw new TypeError("classCanWhitespace must be a boolean");this.#me=e}static addClass(e,...t){const r=[];for(const e of t)if(_t.#me){const t=e.split(" ");for(const e of t)r.push(e)}else r.push(e);return _t._preElems(e,"addClass").forEach(e=>e.classList.add(...r)),e}addClass(...e){return _t.addClass(this,...e)}static removeClass(e,...t){const r=[];for(const e of t)if(_t.#me){const t=e.split(" ");for(const e of t)r.push(e)}else r.push(e);return _t._preElems(e,"removeClass").forEach(e=>e.classList.remove(...r)),e}removeClass(...e){return _t.removeClass(this,...e)}static replaceClass(e,t,r){if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');if("string"!=typeof r)throw new TypeError('The "newToken" parameter must be a string.');const i=[];return _t._preElems(e,"replaceClass").forEach(e=>i.push(e.classList.replace(t,r))),i}replaceClass(e,t){return _t.replaceClass(this,e,t)[0]}static classItem(e,t){const r=_t._preElem(e,"classItem");if("number"!=typeof t)throw new TypeError('The "index" parameter must be a number.');return r.classList.item(t)}classItem(e){return _t.classItem(this,e)}static toggleClass(e,t,r){if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');if(void 0!==r&&"boolean"!=typeof r)throw new TypeError('The "force" parameter must be a boolean.');const i=[];return _t._preElems(e,"toggleClass").forEach(e=>i.push(e.classList.toggle(t,r))),i}toggleClass(e,t){return _t.toggleClass(this,e,t)[0]}static hasClass(e,t){const r=_t._preElem(e,"hasClass");if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');return r.classList.contains(t)}hasClass(e){return _t.hasClass(this,e)}static classLength(e){return _t._preElem(e,"classLength").classList.length}classLength(){return _t.classLength(this)}static classList(e){return _t._preElem(e,"classList").classList.values().toArray()}classList(){return _t.classList(this)}static tagName(e){return _t._preElem(e,"tagName").tagName}tagName(){return _t.tagName(this)}static id(e){return _t._preElem(e,"id").id}get id(){return _t.id(this)}set id(e){_t.setAttr(this,"id",e)}static toBigInt(e){const t=_t._preElem(e,"toBigInt"),r=t.textContent?.trim();let i=null;try{i=BigInt(r??"")}catch{i=null}return i}toBigInt(){return _t.toBigInt(this)}static setBigInt(e,t){if("bigint"!=typeof t)throw new Error("Value is not a valid BigInt.");const r=t.toString();return _t._preElems(e,"setBigInt").forEach(e=>e.textContent=r),e}setBigInt(e){return _t.setBigInt(this,e)}static toDate(e){const t=_t._preElem(e,"toDate"),r=t.textContent?.trim();if(!r)return null;const i=new Date(r);return Number.isNaN(i.getTime())?null:i}toDate(){return _t.toDate(this)}static setDate(e,t){if(!(t instanceof Date)||Number.isNaN(t.getTime()))throw new Error("Value is not a valid Date.");const r=t.toISOString();return _t._preElems(e,"setDate").forEach(e=>e.textContent=r),e}setDate(e){return _t.setDate(this,e)}static toJson(e){const t=_t._preElem(e,"toJson"),r=t.textContent?.trim();if(!r)return null;try{return JSON.parse(r)}catch{return null}}toJson(){return _t.toJson(this)}static setJson(e,t,r,i){const s=JSON.stringify(t,r,i);return _t._preElems(e,"setJson").forEach(e=>e.textContent=s),e}setJson(e,t,r){return _t.setJson(this,e,t,r)}static toNumber(e){const t=_t._preElem(e,"toNumber");return"string"==typeof t.textContent?parseFloat(t.textContent.trim()):null}toNumber(){return _t.toNumber(this)}static setNumber(e,t){if("number"!=typeof t)throw new Error("Value is not a valid number.");const r=t.toString();return _t._preElems(e,"setNumber").forEach(e=>e.textContent=r),e}setNumber(e){return _t.setNumber(this,e)}static toBoolean(e){const t=_t._preElem(e,"toBoolean"),r=t.textContent?.trim();return null==r||"true"!==r&&"false"!==r?null:/^true$/i.test(r)}toBoolean(){return _t.toBoolean(this)}static setBoolean(e,t){if("boolean"!=typeof t)throw new Error("Value is not a valid boolean.");const r=t.toString();return _t._preElems(e,"setBoolean").forEach(e=>e.textContent=r),e}setBoolean(e){return _t.setBoolean(this,e)}static toString(e){const t=_t._preElem(e,"toString");return"string"==typeof t.textContent?t.textContent:null}toString(){return _t.toString(this)}static setString(e,t){if("string"!=typeof t)throw new Error("Value is not a valid string.");return _t._preElems(e,"setString").forEach(e=>e.textContent=t),e}setString(e){return _t.setString(this,e)}static text(e){return _t._preElem(e,"text").textContent}text(){return _t.text(this)}static setText(e,t){const r=null!=t?String(t):"";return _t._preElems(e,"setText").forEach(e=>e.textContent=r),e}setText(e){return _t.setText(this,e)}static empty(e){return _t._preElems(e,"empty").forEach(e=>e.textContent=""),e}empty(){return _t.empty(this)}static html(e,t){return _t._preElem(e,"html").getHTML(t)}html(e){return _t.html(this,e)}static setHtml(e,t){if("string"!=typeof t)throw new Error("Value is not a valid string.");return _t._preElems(e,"setHtml").forEach(e=>e.innerHTML=t),e}setHtml(e){return _t.setHtml(this,e)}static _valHooks={option:{get:e=>{const t=e.getAttribute("value");return null!=t?t:e.textContent}},select:{get:e=>{const t=e.options,r=e.selectedIndex,i="select-one"===e.type,s=i?r+1:t.length,n=[];let o=r<0?s:i?r:0;for(;o<s;o++){const e=t[o],s=e.parentNode;if((e.selected||o===r)&&!e.disabled&&(!s||!s.disabled||"OPTGROUP"!==s.tagName)){const t=_t._valHooks.option.get(e);if(i)return t;n.push(t)}}return n},set:(e,t)=>{const r=e.options,i=Array.isArray(t)?t.map(String):[String(t)];let s=!1;for(let e=0;e<r.length;e++){const t=r[e],n=_t._valHooks.option.get(t);"string"==typeof n&&(t.selected=i.includes(n))&&(s=!0)}return s||(e.selectedIndex=-1),i}},radio:{get:e=>e.checked?"on":"off",set(e,t){if("boolean"==typeof t){const r=e.closest("label");return t&&r&&r.querySelectorAll('input[type="radio"]').forEach(t=>{t instanceof HTMLInputElement&&t!==e&&(t.checked=!1)}),e.checked=t,t}}},checkbox:{get:e=>e.checked?"on":"off",set(e,t){if("boolean"==typeof t)return e.checked=t,t}}};static setVal(e,t){return _t._preInputElems(e,"setVal").forEach(e=>{if(1!==e.nodeType)return;let r="function"==typeof t?t(e,_t.val(e)):t;null==r?r="":"number"==typeof r?r=String(r):Array.isArray(r)&&(r=((e,t)=>{const r=[];for(let i=0;i<e.length;i++)r.push(t(e[i]));return r})(r,e=>null==e?"":String(e)));const i=_t._valHooks[e.type]||_t._valHooks[e.nodeName.toLowerCase()];if(!i||"function"!=typeof i.set||void 0===i.set(e,r,"value")){if("string"!=typeof r&&"boolean"!=typeof r)throw new Error(`Invalid setValue "${typeof r}" value.`);"string"==typeof r&&(e.value=r)}}),e}setVal(e){return _t.setVal(this,e)}static _valTypes={string:e=>e.value,date:e=>e.valueAsDate,number:e=>e.valueAsNumber};static _getValByType(e,t,r){if("string"!=typeof t)throw new TypeError('The "type" must be a string.');if("string"!=typeof r)throw new TypeError('The "where" must be a string.');if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement))throw new Error(`Provided element is not an HTMLInputElement in ${r}().`);if("function"!=typeof _t._valTypes[t])throw new Error(`No handler found for type "${t}" in ${r}().`);return _t._valTypes[t](e)}static _val(e,t,r){const i=_t._preInputElem(e,t),s=_t._valHooks[i.type]||_t._valHooks[i.nodeName.toLowerCase()];if(s&&"function"==typeof s.get){const e=s.get(i,"value",r);if(void 0!==e)return"string"==typeof e?e.replace(/\r/g,""):e}return _t._getValByType(i,r,t)}_val(e,t){return _t._val(this,e,t)}static val(e){return _t._val(e,"val","string")}val(){return _t.val(this)}static valTxt(e){const t=_t._val(e,"valTxt","string");if("string"!=typeof t&&null!==t)throw new Error("Value is not a valid string.");return null==t?"":"string"==typeof t?t.replace(/\r/g,""):t}valTxt(){return _t.valTxt(this)}static _valArr(e,t,r){const i=_t._val(e,t,r);if(!Array.isArray(i))throw new Error(`Value expected an array but got ${typeof i}.`);return i}_valArr(e,t){return _t._valArr(this,e,t)}static valArr(e){return _t._valArr(e,"valArr","string")}valArr(){return _t.valArr(this)}static valNb(e){if(!(_t._preInputElem(e,"valNb")instanceof HTMLInputElement))throw new Error("Element must be an input element.");const t=_t._val(e,"valNb","number");if(Number.isNaN(t))throw new Error("Value is not a valid number.");return t}valNb(){return _t.valNb(this)}static valDate(e){if(!(_t._preInputElem(e,"valDate")instanceof HTMLInputElement))throw new Error("Element must be an input element.");const t=_t._val(e,"valDate","date");if(!(t instanceof Date))throw new Error("Value is not a valid date.");return t}valDate(){return _t.valDate(this)}static valBool(e){const t=_t._preInputElem(e,"valBool");if(!(t instanceof HTMLInputElement))throw new Error("Element must be an input element.");return"on"===_t.val(t)}valBool(){return _t.valBool(this)}static listenForPaste(e,{onFilePaste:t,onTextPaste:r}={}){if(void 0!==t&&"function"!=typeof t)throw new TypeError("onFilePaste must be a function.");if(void 0!==r&&"function"!=typeof r)throw new TypeError("onTextPaste must be a function.");const i=e=>{if(!(e instanceof ClipboardEvent))return;const i=e.clipboardData?.items||[];for(const e of i)if("file"===e.kind){if("function"==typeof t){const r=e.getAsFile();r&&t(e,r)}}else"string"===e.kind&&"function"==typeof r&&e.getAsString(t=>r(e,t))};return _t._preElemsWithDoc(e,"listenForPaste").forEach(e=>_t.on(e,"paste",i)),i}listenForPaste({onFilePaste:e,onTextPaste:t}={}){return _t.listenForPaste(this,{onFilePaste:e,onTextPaste:t})}static hasEventListener(e,t){const r=_t._preEventTargetElem(e,"hasEventListener");if(!Dt.has(r))return!1;const i=Dt.get(r);return!!(i&&Array.isArray(i[t])&&i[t].length>0)}hasEventListener(e){return _t.hasEventListener(this,e)}static hasExactEventListener(e,t,r){const i=_t._preEventTargetElem(e,"hasExactEventListener");if("function"!=typeof r)throw new TypeError('The "handler" must be a function.');if(!Dt.has(i))return!1;const s=Dt.get(i);return!(!s||!Array.isArray(s[t]))&&s[t].some(e=>e.handler===r)}hasExactEventListener(e,t){return _t.hasExactEventListener(this,e,t)}static hover(e,t,r,i){return _t.on(e,"mouseenter",t,i),_t.on(e,"mouseleave",r||t,i),e}hover(e,t,r){return _t.hover(this,e,t,r)}static on(e,t,r,i){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"on").forEach(e=>{e.addEventListener(s,r,i),Dt.has(e)||Dt.set(e,{});const t=Dt.get(e);t&&(Array.isArray(t[s])||(t[s]=[]),t[s].push({handler:r,options:i}))})}return e}on(e,t,r){return _t.on(this,e,t,r)}static once(e,t,r,i={}){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"once").forEach(e=>{const t=i=>{_t.off(e,s,t),"function"==typeof r&&r(i)};_t.on(e,s,t,"boolean"==typeof i?i:{...i,once:!0})})}return e}once(e,t,r={}){return _t.once(this,e,t,r)}static off(e,t,r,i){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"off").forEach(e=>{e.removeEventListener(s,r,i);const t=Dt.get(e);t&&t[s]&&(t[s]=t[s].filter(e=>e.handler!==r),0===t[s].length&&delete t[s])})}return e}off(e,t,r){return _t.off(this,e,t,r)}static offAll(e,t){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const r of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof r)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"offAll").forEach(e=>{const t=Dt.get(e);if(t&&t[r]){for(const i of t[r])e.removeEventListener(r,i.handler,i.options);delete t[r]}})}return e}offAll(e){return _t.offAll(this,e)}static offAllTypes(e,t=null){if(null!==t&&"function"!=typeof t)throw new TypeError('The "filterFn" must be a function.');return _t._preEventTargetElems(e,"offAllTypes").forEach(e=>{const r=Dt.get(e);if(r){for(const i in r)for(const s of r[i])("function"!=typeof t||t(s.handler,i))&&e.removeEventListener(i,s.handler,s.options);Dt.delete(e)}}),e}offAllTypes(e=null){return _t.offAllTypes(this,e)}static trigger(e,t,r={}){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const i of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof i)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"trigger").forEach(e=>{const t=r instanceof Event||r instanceof CustomEvent?r:new CustomEvent(i,{bubbles:!0,cancelable:!0,detail:r});e.dispatchEvent(t)})}return e}trigger(e,t={}){return _t.trigger(this,e,t)}static#fe={for:"htmlFor",class:"className"};static propFix=new Proxy(_t.#fe,{set:(e,t,r)=>(e[t]=r,_t.attrFix[r]=t,!0)});static attrFix=Object.fromEntries(Object.entries(_t.#fe).map(([e,t])=>[t,e]));static getPropName(e){return"string"==typeof _t.propFix[e]?_t.propFix[e]:e}static getAttrName(e){return"string"==typeof _t.attrFix[e]?_t.attrFix[e]:e}static attrBigInt(e,t){const r=_t._preElem(e,"attrBigInt").getAttribute(_t.getAttrName(t));if(null==r)return null;try{return BigInt(r)}catch{return null}}attrBigInt(e){return _t.attrBigInt(this,e)}static setAttrBigInt(e,t,r){if("bigint"!=typeof r)throw new Error("Value is not a valid BigInt.");return _t.setAttr(e,t,r.toString())}setAttrBigInt(e,t){return _t.setAttrBigInt(this,e,t)}static attrDate(e,t){const r=_t._preElem(e,"attrDate").getAttribute(_t.getAttrName(t));if(!r)return null;const i=new Date(r);return Number.isNaN(i.getTime())?null:i}attrDate(e){return _t.attrDate(this,e)}static setAttrDate(e,t,r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new Error("Value is not a valid Date.");return _t.setAttr(e,t,r.toISOString())}setAttrDate(e,t){return _t.setAttrDate(this,e,t)}static attrJson(e,t){const r=_t._preElem(e,"attrJson").getAttribute(_t.getAttrName(t));if(!r)return null;try{return JSON.parse(r)}catch{return null}}attrJson(e){return _t.attrJson(this,e)}static setAttrJson(e,t,r,i,s){const n=JSON.stringify(r,i,s);return _t.setAttr(e,t,n)}setAttrJson(e,t,r,i){return _t.setAttrJson(this,e,t,r,i)}static attrNumber(e,t){const r=_t._preElem(e,"attrNumber").getAttribute(_t.getAttrName(t));return null!=r?parseFloat(r):null}attrNumber(e){return _t.attrNumber(this,e)}static setAttrNumber(e,t,r){if("number"!=typeof r)throw new Error("Value is not a valid number.");return _t.setAttr(e,t,r.toString())}setAttrNumber(e,t){return _t.setAttrNumber(this,e,t)}static attrBoolean(e,t){const r=_t._preElem(e,"attrBoolean").getAttribute(_t.getAttrName(t));return null===r||"true"!==r&&"false"!==r?null:/^true$/i.test(r)}attrBoolean(e){return _t.attrBoolean(this,e)}static setAttrBoolean(e,t,r){if("boolean"!=typeof r)throw new Error("Value is not a valid boolean.");return _t.setAttr(e,t,r.toString())}setAttrBoolean(e,t){return _t.setAttrBoolean(this,e,t)}static attrString(e,t){const r=_t._preElem(e,"attrString").getAttribute(_t.getAttrName(t));return"string"==typeof r?r:null}attrString(e){return _t.attrString(this,e)}static setAttrString(e,t,r){if("string"!=typeof r)throw new Error("Value is not a valid string.");return _t.setAttr(e,t,r)}setAttrString(e,t){return _t.setAttrString(this,e,t)}static attr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElem(e,"attr").getAttribute(_t.getAttrName(t))}attr(e){return _t.attr(this,e)}static setAttr(e,t,r=null){const i=_t._preElems(e,"setAttr");if("object"==typeof t&&null!==t)return Object.entries(t).forEach(([e,t])=>i.forEach(r=>{null===t?r.removeAttribute(_t.getAttrName(e)):r.setAttribute(_t.getAttrName(e),String(t))})),e;if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return i.forEach(e=>{null===r?e.removeAttribute(_t.getAttrName(t)):e.setAttribute(_t.getAttrName(t),String(r))}),e}setAttr(e,t){return _t.setAttr(this,e,t)}static removeAttr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElems(e,"removeAttr").forEach(e=>e.removeAttribute(_t.getAttrName(t))),e}removeAttr(e){return _t.removeAttr(this,e)}static hasAttr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElem(e,"hasAttr").hasAttribute(_t.getAttrName(t))}hasAttr(e){return _t.hasAttr(this,e)}static hasProp(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return!!_t._preElem(e,"hasProp")[_t.getPropName(t)]}hasProp(e){return _t.hasProp(this,e)}static addProp(e,...t){return _t._preElems(e,"addProp").forEach(e=>{t.forEach(t=>{if("string"!=typeof t)throw new TypeError('Each "name" must be a string.');e[_t.getPropName(t)]=!0})}),e}addProp(...e){return _t.addProp(this,...e)}static removeProp(e,...t){return _t._preElems(e,"removeProp").forEach(e=>{t.forEach(t=>{if("string"!=typeof t)throw new TypeError('Each "name" must be a string.');e[_t.getPropName(t)]=!1})}),e}removeProp(...e){return _t.removeProp(this,...e)}static toggleProp(e,t,r){const i=_t._preElems(e,"toggleProp");if(void 0!==r&&"boolean"!=typeof r)throw new TypeError('The "force" must be a boolean.');return(Array.isArray(t)?t:[t]).forEach(e=>{if("string"!=typeof e)throw new TypeError("Each property name must be a string.");i.forEach(t=>{(void 0===r?!t[_t.getPropName(e)]:r)?_t.addProp(t,e):_t.removeProp(t,e)})}),e}toggleProp(e,t){return _t.toggleProp(this,e,t)}static prop(e,t){if("string"!=typeof t)throw new TypeError('Invalid arguments passed to prop(). Expected string for "name".');return _t._preElem(e,"prop")[t]}prop(e){return _t.prop(this,e)}static setProp(e,t,r){if("string"!=typeof t||""===t.trim())throw new Error("Property name must be a non-empty string.");return _t._preElems(e,"setProp").forEach(e=>{e[t]=r}),e}setProp(e,t){return _t.setProp(this,e,t)}static remove(e){return _t._preElems(e,"remove").forEach(e=>e.remove()),e}remove(){return _t.remove(this)}static index(e,t=null){const r=_t._preElem(e,"index");if(!r)return-1;if(!t)return Array.prototype.indexOf.call(r.parentNode?.children||[],r);if(t){const e="string"==typeof t?document.querySelectorAll(t):_t._preElems(t,"index");return Array.prototype.indexOf.call(e,r)}return-1}index(e){return _t.index(this,e)}static _getCustomRect(e,t){const r={height:0,width:0,x:0,y:0,bottom:0,left:0,right:0,top:0,toJSON:function(){throw new Error("Function not implemented.")}};for(const t in e)"number"==typeof e[t]&&(r[t]=e[t]);if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("extraRect must be a non-null object.");const{height:i=0,width:s=0,top:n=0,bottom:o=0,left:a=0,right:l=0}=t;if("number"!=typeof i)throw new Error("extraRect.height must be a number.");if("number"!=typeof s)throw new Error("extraRect.width must be a number.");if("number"!=typeof n)throw new Error("extraRect.top must be a number.");if("number"!=typeof o)throw new Error("extraRect.bottom must be a number.");if("number"!=typeof a)throw new Error("extraRect.left must be a number.");if("number"!=typeof l)throw new Error("extraRect.right must be a number.");return r.height+=i,r.width+=s,r.top+=n,r.bottom+=o,r.left+=a,r.right+=l,r}static isCollWith(e,t,r={}){const i=_t._getCustomRect(_t._preElem(e,"isCollWith").getBoundingClientRect(),r),s=_t._preElem(t,"isCollWith").getBoundingClientRect();return Tt(i,s)}isCollWith(e,t){return _t.isCollWith(this,e,t)}static isCollPerfWith(e,t,r={}){const i=_t._getCustomRect(_t._preElem(e,"isCollPerfWith").getBoundingClientRect(),r),s=_t._preElem(t,"isCollPerfWith").getBoundingClientRect();return St(i,s)}isCollPerfWith(e,t){return _t.isCollPerfWith(this,e,t)}static _isCollWithLock(e,t,r,i,s){const n=Nt[s];if(e)return n.has(i)||n.set(i,!0),!0;if(n.has(i)){let e=!1;switch(s){case"top":e=xt(t,r);break;case"bottom":e=At(t,r);break;case"left":e=Ct(t,r);break;case"right":e=It(t,r)}return e&&n.delete(i),n.has(i)}return!1}static isCollWithLock(e,t,r,i={}){const s=_t._preElem(e,"isCollWithLock"),n=_t._preElem(t,"isCollWithLock"),o=_t._getCustomRect(s.getBoundingClientRect(),i),a=n.getBoundingClientRect(),l=Tt(o,a);return _t._isCollWithLock(l,o,a,s,r)}isCollWithLock(e,t,r){return _t.isCollWithLock(this,e,t,r)}static isCollPerfWithLock(e,t,r,i={}){const s=_t._preElem(e,"isCollPerfWithLock"),n=_t._preElem(t,"isCollPerfWithLock"),o=_t._getCustomRect(s.getBoundingClientRect(),i),a=n.getBoundingClientRect(),l=St(o,a);return _t._isCollWithLock(l,o,a,s,r)}isCollPerfWithLock(e,t,r){return _t.isCollPerfWithLock(this,e,t,r)}static resetCollLock(e){const t=_t._preElem(e,"resetCollLock");let r=!1;for(const e of["top","bottom","left","right"])Nt[e].has(t)&&(Nt[e].delete(t),r=!0);return r}resetCollLock(){return _t.resetCollLock(this)}static resetCollLockDir(e,t){const r=_t._preElem(e,"resetCollLockDir"),i=Nt[t];return!!i.has(r)&&(i.delete(r),!0)}resetCollLockDir(e){return _t.resetCollLockDir(this,e)}static isInViewport(e){const t=_t._preElem(e,"isInViewport");if(!t.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const r=_t.offset(t).top,i=r+_t.outerHeight(t),s=_t.scrollTop(window),n=s+_t.height(window);return i>s&&r<n}isInViewport(){return _t.isInViewport(this)}static isScrolledIntoView(e){const t=_t._preElem(e,"isScrolledIntoView");if(!t.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const r=_t.scrollTop(window),i=r+_t.height(window),s=_t.offset(t).top;return s+_t.height(t)<=i&&s>=r}isScrolledIntoView(){return _t.isScrolledIntoView(this)}static isInContainer(e,t){const r=_t._preElem(e,"isInContainer"),i=_t._preElem(t,"isInContainer");if(!r.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const s=r.getBoundingClientRect(),n=i.getBoundingClientRect(),o=s.bottom>n.top&&s.top<n.bottom,a=s.right>n.left&&s.left<n.right;return o&&a}isInContainer(e){return _t.isInContainer(this,e)}static isFullyInContainer(e,t){const r=_t._preElem(e,"isScrolledIntoView"),i=_t._preElem(t,"isInContainer");if(!r.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const s=r.getBoundingClientRect(),n=i.getBoundingClientRect();return s.top>=n.top&&s.bottom<=n.bottom&&s.left>=n.left&&s.right<=n.right}isFullyInContainer(e){return _t.isFullyInContainer(this,e)}static hasScroll(e){const t=_t._preElem(e,"hasScroll");return{v:t.scrollHeight>t.clientHeight,h:t.scrollWidth>t.clientWidth}}hasScroll(){return _t.hasScroll(this)}}const Pt=_t,Rt=le("TinyDragger");class jt{static Utils={...n,TinyHtml:Pt};#ye=!0;#u=!1;#ge=0;#we=0;#be=!0;#ve=!1;#Ee=!1;#Te=!1;#Se=!1;#xe=!1;#Ae=!1;#Ce=null;#Ie=[];#De=null;#ke={start:!1,end:!1,collide:!1,move:!1};#Me=null;#F;#Le="drag-hidden";#Ne="dragging";#_e="drag-active";#Pe="jail-drag-active";#Re="jail-drag-disabled";#je="dragging-collision";#Oe=9999;constructor(e,t={}){if(!(e instanceof HTMLElement))throw new Error("TinyDragger requires a valid target HTMLElement to initialize.");if(this.#F=e,void 0!==t.jail&&!(t.jail instanceof HTMLElement))throw new Error('The "jail" option must be an HTMLElement if provided.');if(void 0!==t.defaultZIndex&&this.setDefaultZIndex(t.defaultZIndex),void 0!==t.vibration&&!1!==t.vibration&&!v(t.vibration))throw new Error('The "vibration" option must be an object or false.');const r=(e,t)=>{if(void 0!==e&&"boolean"!=typeof e)throw new Error(`The "${t}" option must be a boolean.`)},i=(e,t)=>{if(void 0!==e&&"string"!=typeof e)throw new Error(`The "${t}" option must be a string.`)};r(t.mirrorElem,"mirrorElem"),r(t.collisionByMouse,"collisionByMouse"),r(t.lockInsideJail,"lockInsideJail"),r(t.dropInJailOnly,"dropInJailOnly"),r(t.revertOnDrop,"revertOnDrop"),r(t.multiCollision,"multiCollision"),i(t.classDragging,"classDragging"),i(t.classBodyDragging,"classBodyDragging"),i(t.classJailDragging,"classJailDragging"),i(t.classJailDragDisabled,"classJailDragDisabled"),i(t.classDragCollision,"classDragCollision"),i(t.classHidden,"classHidden"),t.jail instanceof HTMLElement&&(this.#Me=t.jail),this.#ke=Object.assign({start:!1,end:!1,collide:!1,move:!1},v(t.vibration)?t.vibration:{}),"string"==typeof t.classDragging&&(this.#Ne=t.classDragging),"string"==typeof t.classBodyDragging&&(this.#_e=t.classBodyDragging),"string"==typeof t.classJailDragging&&(this.#Pe=t.classJailDragging),"string"==typeof t.classJailDragDisabled&&(this.#Re=t.classJailDragDisabled),"string"==typeof t.classHidden&&(this.#Le=t.classHidden),"string"==typeof t.classDragCollision&&(this.#je=t.classDragCollision),"boolean"==typeof t.collisionByMouse&&(this.#xe=t.collisionByMouse),"boolean"==typeof t.mirrorElem&&(this.#be=t.mirrorElem),"boolean"==typeof t.revertOnDrop&&(this.#Te=t.revertOnDrop),"boolean"==typeof t.lockInsideJail&&(this.#Ee=t.lockInsideJail),"boolean"==typeof t.dropInJailOnly&&(this.#Ae=t.dropInJailOnly),"boolean"==typeof t.multiCollision&&(this.#ve=t.multiCollision),this._onMouseDown=this.#$e.bind(this),this._onMouseMove=this.#He.bind(this),this._onMouseUp=this.#Fe.bind(this),this._onTouchStart=e=>this.#$e(e.touches[0]),this._onTouchMove=e=>this.#He(e.touches[0]),this._onTouchEnd=e=>this.#Fe(e.changedTouches[0]),this.#F.addEventListener("mousedown",this._onMouseDown),this.#F.addEventListener("touchstart",this._onTouchStart,{passive:!1})}enable(){Rt(this.#u),this.#Me&&this.#Me.classList.add(this.#Re),this.#ye=!0}disable(){Rt(this.#u),this.#Me&&this.#Me.classList.remove(this.#Re),this.#ye=!1}addCollidable(e){if(Rt(this.#u),!(e instanceof HTMLElement))throw new Error("addCollidable expects an HTMLElement as argument.");this.#Ie.includes(e)||this.#Ie.push(e)}removeCollidable(e){if(Rt(this.#u),!(e instanceof HTMLElement))throw new Error("removeCollidable expects an HTMLElement as argument.");this.#Ie=this.#Ie.filter(t=>t!==e)}setVibrationPattern({startPattern:e=!1,endPattern:t=!1,collidePattern:r=!1,movePattern:i=!1}={}){Rt(this.#u);const s=e=>!1===e||Array.isArray(e)&&e.every(e=>"number"==typeof e);if(!s(e))throw new Error('Invalid "startPattern": must be false or an array of numbers.');if(!s(t))throw new Error('Invalid "endPattern": must be false or an array of numbers.');if(!s(r))throw new Error('Invalid "collidePattern": must be false or an array of numbers.');if(!s(i))throw new Error('Invalid "movePattern": must be false or an array of numbers.');this.#ke={start:e,end:t,collide:r,move:i}}disableVibration(){Rt(this.#u),this.#ke={start:!1,end:!1,collide:!1,move:!1}}getOffset(e){if(Rt(this.#u),!(e instanceof MouseEvent||e instanceof Touch)||"number"!=typeof e.clientX||"number"!=typeof e.clientY)throw new Error("getOffset expects an event with valid clientX and clientY coordinates.");const t=this.#F.getBoundingClientRect(),{left:r,top:i}=Pt.borderWidth(this.#F);return{x:e.clientX-t.left+r,y:e.clientY-t.top+i}}#$e(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#ye||!this.#F.parentElement)return;if(this.#be){const e=this.#F.cloneNode(!0);if(!(e instanceof HTMLElement))throw new Error("[TinyDragger] INVALID DRAG ELEMENT!");this.#De=e}else this.#De=this.#F;this.#Se=!0;const t=this.#F.getBoundingClientRect();Object.assign(this.#De.style,{position:"absolute",pointerEvents:"none",left:`${this.#F.offsetLeft}px`,top:`${this.#F.offsetTop}px`,width:`${t.width}px`,height:`${t.height}px`,zIndex:this.#Oe}),this.#be&&(this.#F.classList.add(this.#Le),this.#F.parentElement.appendChild(this.#De));const{x:r,y:i}=this.getOffset(e);this.#we=r,this.#ge=i,this.#De.classList.add(this.#Ne),document.body.classList.add(this.#_e),this.#Me&&this.#Me.classList.add(this.#Pe),document.addEventListener("mousemove",this._onMouseMove),document.addEventListener("mouseup",this._onMouseUp),document.addEventListener("touchmove",this._onTouchMove,{passive:!1}),document.addEventListener("touchend",this._onTouchEnd),navigator.vibrate&&Array.isArray(this.#ke.start)&&navigator.vibrate(this.#ke.start),this.checkDragCollision(e),this.#ze("drag")}#Be=[];#We(e){e&&(e.classList.add(this.#je),this.#Be.push(e))}#qe(){for(;this.#Be.length>0;){const e=this.#Be.shift();e&&e.classList.remove(this.#je)}this.#Ce&&this.#Ce.classList.remove(this.#je)}checkDragCollision(e){Rt(this.#u);const{collidedElements:t}=this.execCollision(e),r=t[0]||null;this.#Ce&&!t.includes(this.#Ce)&&this.#qe(),t.forEach(e=>this.#We(e)),this.#Ie.forEach(e=>{t.includes(e)||e.classList.remove(this.#je)}),navigator.vibrate&&Array.isArray(this.#ke.collide)&&t.length>0&&navigator.vibrate(this.#ke.collide),this.#Ce=r}#He(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#Se||!this.#ye||!this.#De)return;const t=(this.#De.offsetParent||document.body).getBoundingClientRect();let r=e.clientX-t.left-this.#we,i=e.clientY-t.top-this.#ge;if(this.#Ee&&this.#Me){const e=this.#Me.getBoundingClientRect(),s=this.#De.getBoundingClientRect(),n=e.left-t.left,o=e.top-t.top,{x:a,y:l}=Pt.borderWidth(this.#Me),h=n+e.width-s.width-l,u=o+e.height-s.height-a;r=Math.max(n,Math.min(r,h)),i=Math.max(o,Math.min(i,u))}this.#De.style.position="absolute",this.#De.style.left=`${r}px`,this.#De.style.top=`${i}px`,navigator.vibrate&&Array.isArray(this.#ke.move)&&navigator.vibrate(this.#ke.move),this.checkDragCollision(e),this.#ze("dragging")}execCollision(e){if(Rt(this.#u),this.#u||!this.#De)return{inJail:!1,collidedElements:[]};let t=[],r=!0;const i=this.#Me?.getBoundingClientRect();if(this.#xe){const s=e.clientX,n=e.clientY;this.#Ae&&this.#Me&&i&&(r=s>=i.left&&s<=i.right&&n>=i.top&&n<=i.bottom),t=r?this.#ve?this.getAllCollidedElements(s,n):[this.getCollidedElement(s,n)].filter(Boolean):[]}else{const e=this.#De.getBoundingClientRect();this.#Ae&&this.#Me&&i&&(r=e.left>=i.left&&e.right<=i.right&&e.top>=i.top&&e.bottom<=i.bottom),t=r?this.#ve?this.getAllCollidedElementsByRect(e):[this.getCollidedElementByRect(e)].filter(Boolean):[]}return{inJail:r,collidedElements:t}}#Fe(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#Se)return;if(this.#Se=!1,!this.#De)return;this.#F.classList.remove(this.#Ne),document.body.classList.remove(this.#_e),this.#Me&&this.#Me.classList.remove(this.#Pe),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),document.removeEventListener("touchmove",this._onTouchMove),document.removeEventListener("touchend",this._onTouchEnd);const{collidedElements:t}=this.execCollision(e);navigator.vibrate&&Array.isArray(this.#ke.end)&&navigator.vibrate(this.#ke.end);const r=this.#De.style.left,i=this.#De.style.top;this.#De&&(this.#be?this.#De.remove():Object.assign(this.#De.style,{position:"",pointerEvents:"",left:"",top:"",width:"",height:"",zIndex:""}),this.#De=null),this.#Ce&&this.#qe(),this.#Ce=null,this.#be&&this.#F.classList.remove(this.#Le),this.#Te||(this.#F.style.left=r,this.#F.style.top=i);const s=new CustomEvent("drop",{detail:{targets:t,first:t[0]||null}});this.#F.dispatchEvent(s)}#Ve(e,t){const r=e.getBoundingClientRect();return!(t.right<r.left||t.left>r.right||t.bottom<r.top||t.top>r.bottom)}getAllCollidedElementsByRect(e){if(Rt(this.#u),!(e instanceof DOMRect)||"number"!=typeof e.left||"number"!=typeof e.right||"number"!=typeof e.top||"number"!=typeof e.bottom)throw new Error("getCollidedElementByRect expects a valid DOMRect object.");return this.#Ie.filter(t=>this.#Ve(t,e))}getCollidedElementByRect(e){if(Rt(this.#u),!(e instanceof DOMRect)||"number"!=typeof e.left||"number"!=typeof e.right||"number"!=typeof e.top||"number"!=typeof e.bottom)throw new Error("getCollidedElementByRect expects a valid DOMRect object.");return this.#Ie.find(t=>this.#Ve(t,e))||null}#Ue(e,t,r){const i=e.getBoundingClientRect();return t>=i.left&&t<=i.right&&r>=i.top&&r<=i.bottom}getAllCollidedElements(e,t){if(Rt(this.#u),"number"!=typeof e||"number"!=typeof t)throw new Error("getCollidedElement expects numeric x and y coordinates.");return this.#Ie.filter(r=>this.#Ue(r,e,t))}getCollidedElement(e,t){if(Rt(this.#u),"number"!=typeof e||"number"!=typeof t)throw new Error("getCollidedElement expects numeric x and y coordinates.");return this.#Ie.find(r=>this.#Ue(r,e,t))||null}#ze(e){const t=new CustomEvent(e);this.#F.dispatchEvent(t)}getDragging(){return Rt(this.#u),this.#Se}getLockInsideJail(){return Rt(this.#u),this.#Ee}setLockInsideJail(e){if(Rt(this.#u),"boolean"!=typeof e)throw new Error("lockInsideJail must be a boolean.");this.#Ee=e}getRevertOnDrop(){return Rt(this.#u),this.#Te}setRevertOnDrop(e){if(Rt(this.#u),"boolean"!=typeof e)throw new Error("revertOnDrop must be a boolean.");this.#Te=e}getCollisionByMouse(){return Rt(this.#u),this.#xe}setCollisionByMouse(e){if(Rt(this.#u),"boolean"!=typeof e)throw new Error("collisionByMouse must be a boolean.");this.#xe=e}getDropInJailOnly(){return Rt(this.#u),this.#Ae}setDropInJailOnly(e){if(Rt(this.#u),"boolean"!=typeof e)throw new Error("dropInJailOnly must be a boolean.");this.#Ae=e}getDefaultZIndex(){return Rt(this.#u),this.#Oe}setDefaultZIndex(e){if(Rt(this.#u),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("Z-index must be a finite number.");this.#Oe=e}isMirrorEnabled(){return Rt(this.#u),this.#be}setMirrorEnabled(e){if(Rt(this.#u),"boolean"!=typeof e)throw new TypeError("Mirror setting must be a boolean.");this.#be=e}getTarget(){return Rt(this.#u),this.#F}getJail(){return Rt(this.#u),this.#Me}getDragProxy(){return Rt(this.#u),this.#De}getLastCollision(){return Rt(this.#u),this.#Ce}getCollidables(){return Rt(this.#u),[...this.#Ie]}getDragHiddenClass(){return Rt(this.#u),this.#Le}getClassDragging(){return Rt(this.#u),this.#Ne}getClassBodyDragging(){return Rt(this.#u),this.#_e}getClassJailDragging(){return Rt(this.#u),this.#Pe}getClassJailDragDisabled(){return Rt(this.#u),this.#Re}getClassDragCollision(){return Rt(this.#u),this.#je}getVibrations(){return Rt(this.#u),{...this.#ke}}getStartVibration(){return Rt(this.#u),this.#ke.start}getEndVibration(){return Rt(this.#u),this.#ke.end}getCollideVibration(){return Rt(this.#u),this.#ke.collide}getMoveVibration(){return Rt(this.#u),this.#ke.move}isEnabled(){return Rt(this.#u),this.#ye}destroy(){this.#u||(this.disable(),this.#F.removeEventListener("mousedown",this._onMouseDown),this.#F.removeEventListener("touchstart",this._onTouchStart),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),document.removeEventListener("touchmove",this._onTouchMove),document.removeEventListener("touchend",this._onTouchEnd),this.#Ce&&this.#qe(),this.#De&&(this.#be?this.#De.remove():Object.assign(this.#De.style,{position:"",pointerEvents:"",left:"",top:"",width:"",height:"",zIndex:""}),this.#De=null),this.#Ie=[],this.#Se=!1,this.#Ce=null,this.#be&&this.#F.classList.remove(this.#Le),this.#F.classList.remove(this.#Ne),document.body.classList.remove(this.#_e),this.#Me&&this.#Me.classList.remove(this.#Pe,this.#Re),this.#u=!0)}}const Ot=jt,$t=class{#Ke=[];#Je=!1;#Ge=!1;#Ye=[];#Xe(){this.#Je&&Promise.all(this.#Ye).then(()=>{this.#Ge=!0,this.#Qe(!1)}).catch(e=>{console.error("[TinyDomReadyManager] Promise rejected:",e)})}#Qe(e){this.#Ke.filter(t=>t.domOnly===e).sort((e,t)=>t.priority-e.priority).forEach(e=>this.#Ze(e)),this.#Ke=this.#Ke.filter(t=>!(t.once&&(!e||t.domOnly)))}#Ze(e){if("function"==typeof e.filter)try{if(!e.filter())return}catch(e){return void console.warn("[TinyDomReadyManager] Filter error:",e)}try{e.fn()}catch(e){console.error("[TinyDomReadyManager] Handler error:",e)}}_markDomReady(){this.#Je=!0,this.#Qe(!0),this.#Xe()}init(){if(this.#Je)throw new Error("[TinyDomReadyManager] init() has already been called.");"interactive"===document.readyState||"complete"===document.readyState?this._markDomReady():document.addEventListener("DOMContentLoaded",()=>this._markDomReady())}addPromise(e){if(!(e instanceof Promise))throw new TypeError("[TinyDomReadyManager] promise must be a valid Promise.");this.#Ge||(this.#Ye.push(e),this.#Je&&this.#Xe())}onReady(e,{once:t=!0,priority:r=0,filter:i=null,domOnly:s=!1}={}){if("function"!=typeof e)throw new TypeError("[TinyDomReadyManager] fn must be a function.");const n={fn:e,once:t,priority:r,filter:i,domOnly:s};if(s&&this.#Je)return this.#Ze(n),void(t||this.#Ke.push(n));!s&&this.#Ge?this.#Ze(n):this.#Ke.push(n)}isReady(){return this.#Ge}isDomReady(){return this.#Je}},Ht=class{#et=!1;#tt=!1;#rt=null;#it=100;#st=null;#nt;constructor({audio:e=null,defaultIcon:t=null,bodyLimit:r=100,defaultOnClick:i=function(e){e.preventDefault(),window.focus&&window.focus(),this.close()}}={}){if(!(e instanceof HTMLAudioElement)&&"string"!=typeof e&&null!==e)throw new TypeError("audio must be an instance of HTMLAudioElement or null.");if(null!==t&&"string"!=typeof t)throw new TypeError("defaultIcon must be a string or null.");if(!Number.isFinite(r)||r<0)throw new TypeError("bodyLimit must be a non-negative number.");if("function"!=typeof i)throw new TypeError("defaultOnClick must be a function.");this.#rt="string"!=typeof e?e:new Audio(e),this.#st=t,this.#it=r,this.#nt=i}requestPerm(){const e=this;return new Promise((t,r)=>{e.isCompatible()?"default"===Notification.permission?Notification.requestPermission().then(r=>{this.#tt=!0,e.#et="granted"===r,t(e.#et)}).catch(r):(this.#tt=!0,e.#et="granted"===Notification.permission,t(e.#et)):(this.#tt=!0,e.#et=!1,t(!1))})}isCompatible(){return"Notification"in window}send(e,t={}){if(!this.#tt)throw new Error("You must call requestPerm() before sending a notification.");if("string"!=typeof e)throw new TypeError("title must be a string.");if("object"!=typeof t||null===t)throw new TypeError("config must be a non-null object.");if(!this.#et)return null;const{icon:r=this.#st||void 0,vibrate:i=[200,100,200]}=t,s={...t};"string"==typeof r&&(s.icon=r),Array.isArray(i)&&(s.vibrate=i),"string"==typeof s.body&&(s.body=re(s.body,this.#it));const n=new Notification(e,s);return n.addEventListener("show",()=>{this.#rt instanceof HTMLAudioElement&&(this.#rt.currentTime=0,this.#rt.play().catch(e=>console.error(e)))}),"function"==typeof this.#nt&&n.addEventListener("click",this.#nt),n}wasPermissionRequested(){return this.#tt}isAllowed(){return this.#et}getAudio(){return this.#rt}setAudio(e){if(!(e instanceof HTMLAudioElement)&&"string"!=typeof e&&null!==e)throw new TypeError("sound must be an instance of HTMLAudioElement or null.");this.#rt="string"!=typeof e?e:new Audio(e)}getBodyLimit(){return this.#it}setBodyLimit(e){if(!Number.isFinite(e)||e<0)throw new TypeError("bodyLimit must be a non-negative number.");this.#it=e}getDefaultAvatar(){return this.#st}setDefaultAvatar(e){if("string"!=typeof e&&null!==e)throw new TypeError("defaultIcon must be a string or null.");this.#st=e}getDefaultOnClick(){return this.#nt}setDefaultOnClick(e){if("function"!=typeof e)throw new TypeError("defaultOnClick must be a function.");this.#nt=e}};function Ft(e,t){if(!E(e))throw new TypeError("The first argument must be a non-null object.");if("function"!=typeof t)throw new TypeError("The second argument must be a function.");const r=Object.entries(e).filter(t);return Object.fromEntries(r)}function zt(e,t){if(void 0!==t.obj&&"function"!=typeof t.obj)throw new TypeError("filter.obj must be a function if provided.");if(void 0!==t.value&&"function"!=typeof t.value)throw new TypeError("filter.value must be a function if provided.");if(void 0!==t.array&&"function"!=typeof t.array)throw new TypeError("filter.array must be a function if provided.");let r;r=e instanceof Map?new Map:e instanceof Set?new Set:{};const i=(s=e)instanceof Map?Array.from(s.entries()):s instanceof Set?Array.from(s.values()).map(e=>[void 0,e]):Object.entries(s);var s;const n=(e,r)=>{const i=[];for(let s=0;s<e.length;s++){const o=e[s];if(Array.isArray(o))i.push(n(o,r));else if(E(o)){const r=zt(o,t);(void 0===t.obj||t.obj(r,s,e))&&i.push(r)}else(void 0===t.value||t.value([r,o],s,e))&&i.push(o)}return i};for(let e=0;e<i.length;e++){const[s,o]=i[e];if(Array.isArray(o)){const a=n(o,s);(void 0===t.array||t.array([s,a],e,i))&&(r instanceof Map||r instanceof Set?r instanceof Map?r.set(s,a):r.add(a):r[s]=a)}else if(E(o)){const n=zt(o,t);(void 0===t.obj||t.obj(n,e,i))&&(r instanceof Map?r.set(s,n):r instanceof Set?r.add(n):r[s]=n)}else(void 0===t.value||t.value([s,o],e,i))&&(r instanceof Map?r.set(s,o):r instanceof Set?r.add(o):r[s]=o)}return r}function Bt(e,t,r){if(!Array.isArray(t))throw new TypeError("The second argument must be an array.");if(void 0!==r&&!Array.isArray(r))throw new TypeError("The third argument must be an array.");return Ft(e,([e,i])=>t.length>0?t.some(t=>{if(Array.isArray(t)){const[r,s]=t,n=e===r,o="function"==typeof s?s(i):i===s;return n&&o}const s=e===t,n=void 0===r||r.some(e=>"function"==typeof e?e(i):e===i);return s&&n}):void 0!==r&&r.some(e=>"function"==typeof e?e(i):e===i))}const Wt=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("string"!=typeof e)throw new TypeError(`Expected "${t}" to be a string, but received ${typeof e}.`)},qt=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("function"!=typeof e)throw new TypeError(`Expected "${t}" to be a function, but received ${typeof e}.`)},Vt=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError(`Expected "${t}" to be a plain object, but received ${null===e?"null":Array.isArray(e)?"array":typeof e}.`)},Ut=(e,t=!1)=>!t&&void 0===e,Kt=(e,t=!1)=>Ut(e,t)||"string"==typeof e||!t&&null===e,Jt=(e,t=!1)=>Ut(e,t)||"number"==typeof e||!t&&null===e,Gt=(e,t=!1)=>Ut(e,t)||"boolean"==typeof e||!t&&null===e,Yt=(e,t)=>!!Ut(e)||(qt(t,"valueValidator"),Array.isArray(e)&&e.every(t)),Xt=new Map;class Qt extends Error{constructor(e,t,r){if(Wt(e,"message"),Wt(t,"url"),"string"!=typeof r)throw new TypeError(`Expected "stage" to be a string, but received ${typeof r}.`);super(e),this.name="MediaLoadingError",this.url=t,this.stage=r}}const Zt=async e=>{Wt(e,"str");const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-1",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("").substring(0,8)},er=(e,t="image/jpeg")=>{if(!(e instanceof Uint8Array)&&"string"!=typeof e)throw new TypeError(`Expected "data" to be an instance of Uint8Array or a string, but received ${typeof e}.`);Wt(t,"format");const r=e=>{const t=URL.createObjectURL(e),r=Xt.get(t);return Xt.set(t,"number"==typeof r?r+1:1),t};if(e instanceof Uint8Array)return r(new Blob([e],{type:t}));if("string"==typeof e&&e.startsWith("data:")){const i=e.split(",")[1],s=atob(i),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return r(new Blob([n],{type:t}))}return"string"==typeof e?e:""},tr=async e=>{if(Wt(e,"url"),!e.startsWith("blob:"))return e;try{const t=await fetch(e),r=await t.blob();return await new Promise((e,t)=>{const i=new FileReader;i.onloadend=()=>e(String(i.result)),i.onerror=t,i.readAsDataURL(r)})}catch(t){return console.warn(`[TinyAudioUtils] Failed to convert Blob URL to Base64 on export: ${e}`,t),e}},rr=e=>{Vt(e,"content"),e&&Array.isArray(e.picture)&&e.picture.forEach(e=>{if("string"==typeof e.data&&e.data.startsWith("blob:")){const t=Xt.get(e.data)??0;t>1?Xt.set(e.data,t-1):Xt.delete(e.data),t<=1&&URL.revokeObjectURL(e.data)}})},ir=(e,t=!1)=>{if(v(e)){if(4!==b(e)){if(t)return!1;throw new TypeError("Invalid fetch data: Object must be an MediaContentFetchData.")}sr(e.common),Vt(e.native,"_fetchData.native"),Vt(e.format,"_fetchData.format"),Vt(e.quality,"_fetchData.quality");for(const r in e.native){const i=e.native[r];if(!Yt(i,e=>"string"==typeof e.id)){if(t)return!1;throw new TypeError(`Invalid native data: "${r}" must be an array of native fetch data.`)}}}return!0},sr=e=>{if(Vt(e,"common"),ir(e._fetchData),!Kt(e.title))throw new TypeError('Invalid metadata: "title" must be a string or null.');if(!Kt(e.album))throw new TypeError('Invalid metadata: "album" must be a string or null.');if(!Kt(e.albumartist))throw new TypeError('Invalid metadata: "albumartist" must be a a string or null.');if(!Kt(e.artist))throw new TypeError('Invalid metadata: "artist" must be a string or null.');if(!Gt(e.compilation))throw new TypeError('Invalid metadata: "compilation" must be a boolean or null.');if(!Gt(e.podcast))throw new TypeError('Invalid metadata: "podcast" must be a boolean or null.');if(!Gt(e.gapless))throw new TypeError('Invalid metadata: "gapless" must be a boolean or null.');if(!Gt(e.showMovement))throw new TypeError('Invalid metadata: "showMovement" must be a boolean or null.');if(!Jt(e.averageLevel))throw new TypeError('Invalid metadata: "averageLevel" must be a number or null.');if(!Jt(e.peakLevel))throw new TypeError('Invalid metadata: "peakLevel" must be a number or null.');if(!Jt(e.hdVideo))throw new TypeError('Invalid metadata: "hdVideo" must be a number or null.');if(!Jt(e.stik))throw new TypeError('Invalid metadata: "stik" must be a number or null.');if(!Jt(e.playCounter))throw new TypeError('Invalid metadata: "playCounter" must be a number or null.');if(!Jt(e.tvSeason))throw new TypeError('Invalid metadata: "tvSeason" must be a number or null.');if(!Jt(e.tvEpisode))throw new TypeError('Invalid metadata: "tvEpisode" must be a number or null.');if(!Jt(e.year))throw new TypeError('Invalid metadata: "year" must be a number or null.');if(!Jt(e.bpm))throw new TypeError('Invalid metadata: "bpm" must be a number or null.');if(!Jt(e.originalyear))throw new TypeError('Invalid metadata: "originalyear" must be a number or null.');if(!Jt(e.movementTotal))throw new TypeError('Invalid metadata: "movementTotal" must be a number or null.');if(!Kt(e.date))throw new TypeError('Invalid metadata: "date" must be a string or null.');if(!Kt(e.originaldate))throw new TypeError('Invalid metadata: "originaldate" must be a string or null.');if(!Kt(e.releasedate))throw new TypeError('Invalid metadata: "releasedate" must be a string or null.');if(!Kt(e.albumsort))throw new TypeError('Invalid metadata: "albumsort" must be a string or null.');if(!Kt(e.titlesort))throw new TypeError('Invalid metadata: "titlesort" must be a string or null.');if(!Kt(e.work))throw new TypeError('Invalid metadata: "work" must be a string or null.');if(!Kt(e.artistsort))throw new TypeError('Invalid metadata: "artistsort" must be a string or null.');if(!Kt(e.albumartistsort))throw new TypeError('Invalid metadata: "albumartistsort" must be a string or null.');if(!Kt(e.composersort))throw new TypeError('Invalid metadata: "composersort" must be a string or null.');if(!Kt(e.grouping))throw new TypeError('Invalid metadata: "grouping" must be a string or null.');if(!Kt(e.longDescription))throw new TypeError('Invalid metadata: "longDescription" must be a string or null.');if(!Kt(e.totaltracks))throw new TypeError('Invalid metadata: "totaltracks" must be a string or null.');if(!Kt(e.totaldiscs))throw new TypeError('Invalid metadata: "totaldiscs" must be a string or null.');if(!Kt(e.mood))throw new TypeError('Invalid metadata: "mood" must be a string or null.');if(!Kt(e.media))throw new TypeError('Invalid metadata: "media" must be a string or null.');if(!Kt(e.tvShow))throw new TypeError('Invalid metadata: "tvShow" must be a string or null.');if(!Kt(e.tvShowSort))throw new TypeError('Invalid metadata: "tvShowSort" must be a string or null.');if(!Kt(e.tvEpisodeId))throw new TypeError('Invalid metadata: "tvEpisodeId" must be a string or null.');if(!Kt(e.tvNetwork))throw new TypeError('Invalid metadata: "tvNetwork" must be a string or null.');if(!Kt(e.podcasturl))throw new TypeError('Invalid metadata: "podcasturl" must be a string or null.');if(!Kt(e.releasestatus))throw new TypeError('Invalid metadata: "releasestatus" must be a string or null.');if(!Kt(e.releasecountry))throw new TypeError('Invalid metadata: "releasecountry" must be a string or null.');if(!Kt(e.script))throw new TypeError('Invalid metadata: "script" must be a string or null.');if(!Kt(e.language))throw new TypeError('Invalid metadata: "language" must be a string or null.');if(!Kt(e.copyright))throw new TypeError('Invalid metadata: "copyright" must be a string or null.');if(!Kt(e.license))throw new TypeError('Invalid metadata: "license" must be a string or null.');if(!Kt(e.encodedby))throw new TypeError('Invalid metadata: "encodedby" must be a string or null.');if(!Kt(e.encodersettings))throw new TypeError('Invalid metadata: "encodersettings" must be a string or null.');if(!Kt(e.barcode))throw new TypeError('Invalid metadata: "barcode" must be a string or null.');if(!Kt(e.asin))throw new TypeError('Invalid metadata: "asin" must be a string or null.');if(!Kt(e.website))throw new TypeError('Invalid metadata: "website" must be a string or null.');if(!Kt(e.originalalbum))throw new TypeError('Invalid metadata: "originalalbum" must be a string or null.');if(!Kt(e.originalartist))throw new TypeError('Invalid metadata: "originalartist" must be a string or null.');if(!Kt(e.key))throw new TypeError('Invalid metadata: "key" must be a string or null.');if(!Kt(e.movement))throw new TypeError('Invalid metadata: "movement" must be a string or null.');if(!Kt(e.podcastId))throw new TypeError('Invalid metadata: "podcastId" must be a string or null.');if(!Yt(e.albumartists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "albumartists" must be an array of strings.');if(!Yt(e.genre,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "genre" must be an array of strings.');if(!Yt(e.label,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "label" must be an array of strings.');if(!Yt(e.composer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "composer" must be an array of strings.');if(!Yt(e.artists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "artists" must be an array of strings.');if(!Yt(e.lyricist,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "lyricist" must be an array of strings.');if(!Yt(e.writer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "writer" must be an array of strings.');if(!Yt(e.conductor,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "conductor" must be an array of strings.');if(!Yt(e.remixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "remixer" must be an array of strings.');if(!Yt(e.arranger,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "arranger" must be an array of strings.');if(!Yt(e.engineer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "engineer" must be an array of strings.');if(!Yt(e.publisher,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "publisher" must be an array of strings.');if(!Yt(e.producer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "producer" must be an array of strings.');if(!Yt(e.djmixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "djmixer" must be an array of strings.');if(!Yt(e.mixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "mixer" must be an array of strings.');if(!Yt(e.technician,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "technician" must be an array of strings.');if(!Yt(e.subtitle,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "subtitle" must be an array of strings.');if(!Yt(e.description,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "description" must be an array of strings.');if(!Yt(e.discsubtitle,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "discsubtitle" must be an array of strings.');if(!Yt(e.releasetype,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "releasetype" must be an array of strings.');if(!Yt(e.isrc,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "isrc" must be an array of strings.');if(!Yt(e.performer_instrument,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "performer_instrument" must be an array of strings.');if(!Yt(e.notes,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "notes" must be an array of strings.');if(!Yt(e.category,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "category" must be an array of strings.');if(!Yt(e.keywords,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "keywords" must be an array of strings.');if(!Yt(e.catalognumber,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "catalognumber" must be an array of strings.');if(!Yt(e.picture,e=>e&&"object"==typeof e&&(void 0===e.description||"string"==typeof e.description)&&(void 0===e.name||"string"==typeof e.name)&&(void 0===e.type||"string"==typeof e.type)&&"string"==typeof e.format&&(e.data instanceof Uint8Array||"string"==typeof e.data)))throw new TypeError('Invalid metadata: "picture" must be an array of pictures.');if(!Yt(e.comment,e=>null!==e&&"object"==typeof e&&Kt(e.descriptor)&&Kt(e.language)&&Kt(e.text)))throw new TypeError('Invalid metadata: "comment" must be an array of valid IComment objects.');if(!Yt(e.lyrics,e=>null!==e&&"object"==typeof e&&Kt(e.text)&&Kt(e.descriptor)&&Kt(e.language)&&(!Array.isArray(e)||Yt(e.syncText,e=>null!==e&&"object"==typeof e&&Kt(e.text)&&Jt(e.timestamp)))&&(e=>void 0===e||null!==e&&"object"==typeof e&&Jt(e.notSynchronized)&&Jt(e.mpegFrameNumber)&&Jt(e.milliseconds))(e.timeStampFormat)&&(e=>void 0===e||null!==e&&"object"==typeof e&&Jt(e.other)&&Jt(e.lyrics)&&Jt(e.text)&&Jt(e.movement_part)&&Jt(e.events)&&Jt(e.chord)&&Jt(e.trivia_pop))(e.contentType)))throw new TypeError('Invalid metadata: "lyrics" must be an array of valid ILyricsTag objects.');if(!Yt(e.rating,e=>null!==e&&"object"==typeof e&&Kt(e.source)&&Jt(e.rating)))throw new TypeError('Invalid metadata: "rating" must be an array of valid IRating objects.');const t=(e,t)=>{if(!Ut(t)&&null!==t){if("object"!=typeof t)throw new TypeError(`Invalid metadata: "${e}" must be an object or null.`);if("number"!=typeof t.no&&null!==t.no)throw new TypeError(`Invalid metadata: "${e}.no" must be a number or null.`);if("number"!=typeof t.of&&null!==t.of)throw new TypeError(`Invalid metadata: "${e}.of" must be a number or null.`)}};t("disk",e.disk),t("track",e.track),t("movementIndex",e.movementIndex)},nr=async(e,t,r=!0)=>{Wt(e,"url"),qt(t,"parseFile");const i=await fetch(e);if(!i.ok)throw new Error(`Failed to fetch audio file: ${i.status} ${i.statusText}`);const s=await i.blob(),n=await t(s);if(!n||"object"!=typeof n.common)throw new TypeError('Invalid metadata: "common" property is missing.');void 0!==typeof n.common["performer:instrument"]&&(n.common.performer_instrument=n.common["performer:instrument"]),ir(n);const o=n.common;sr(o);const a=o?.picture?.map(e=>({...e,data:r?er(e.data,e.format):e.data}))??[];n.common={...n.common,picture:a.map(e=>({...e,data:""}))},r&&Object.keys(n.native).forEach(e=>{n.native[e]=n.native[e].map(e=>{if(e.value&&"object"==typeof e.value&&e.value.data instanceof Uint8Array){const t=o?.picture?.findIndex(t=>t.data===e.value.data&&t.format===e.value.format&&t.description===e.value.description&&t.name===e.value.name)??-1;if(a[t])return{...e,value:{...e.value,data:""}}}return e})});const l=zt({title:o?.title,album:o?.album,albumartist:o?.albumartist,albumartists:o?.albumartists,genre:o?.genre,label:o?.label,composer:o?.composer,year:o?.year,artist:o?.artist,artists:o?.artists,disk:o?.disk?{no:o.disk.no,of:o.disk.of}:void 0,track:o?.track?{no:o.track.no,of:o.track.of}:void 0,movementIndex:o?.movementIndex?{no:o.movementIndex.no,of:o.movementIndex.of}:void 0,picture:a,date:o?.date,originaldate:o?.originaldate,originalyear:o?.originalyear,releasedate:o?.releasedate,comment:o?.comment,lyrics:o?.lyrics,albumsort:o?.albumsort,titlesort:o?.titlesort,work:o?.work,artistsort:o?.artistsort,albumartistsort:o?.albumartistsort,composersort:o?.composersort,lyricist:o?.lyricist,writer:o?.writer,conductor:o?.conductor,remixer:o?.remixer,arranger:o?.arranger,engineer:o?.engineer,publisher:o?.publisher,producer:o?.producer,djmixer:o?.djmixer,mixer:o?.mixer,technician:o?.technician,grouping:o?.grouping,subtitle:o?.subtitle,description:o?.description,longDescription:o?.longDescription,discsubtitle:o?.discsubtitle,totaltracks:o?.totaltracks,totaldiscs:o?.totaldiscs,movementTotal:o?.movementTotal,compilation:o?.compilation,rating:o?.rating,bpm:o?.bpm,mood:o?.mood,media:o?.media,catalognumber:o?.catalognumber,tvShow:o?.tvShow,tvShowSort:o?.tvShowSort,tvSeason:o?.tvSeason,tvEpisode:o?.tvEpisode,tvEpisodeId:o?.tvEpisodeId,tvNetwork:o?.tvNetwork,podcast:o?.podcast,podcasturl:o?.podcasturl,releasestatus:o?.releasestatus,releasetype:o?.releasetype,releasecountry:o?.releasecountry,script:o?.script,language:o?.language,copyright:o?.copyright,license:o?.license,encodedby:o?.encodedby,encodersettings:o?.encodersettings,gapless:o?.gapless,barcode:o?.barcode,isrc:o?.isrc,asin:o?.asin,website:o?.website,performer_instrument:o?.performer_instrument,averageLevel:o?.averageLevel,peakLevel:o?.peakLevel,notes:o?.notes,originalalbum:o?.originalalbum,originalartist:o?.originalartist,key:o?.key,category:o?.category,hdVideo:o?.hdVideo,keywords:o?.keywords,movement:o?.movement,podcastId:o?.podcastId,showMovement:o?.showMovement,stik:o?.stik,playCounter:o?.playCounter},{value:([e,t])=>null!=t,obj:e=>b(e)>0,array:([e,t])=>t.length>0});return l._fetchData=n,l},or=async(e,t={},r={},i=e=>{if(!(e instanceof Blob))throw new TypeError('Expected "data" to be a Blob.');return new Promise((e,t)=>t(new TypeError("parseFile library not found.")))},s={},n=!0,o="null")=>{if("string"!=typeof e&&!(e instanceof HTMLMediaElement))throw new TypeError("Source must be a string or an HTMLMediaElement.");if(Vt(t,"defaultMetadata"),Vt(r,"metadata"),qt(i,"parseFile"),Vt(s,"callbacks"),s.onProgress&&"function"!=typeof s.onProgress)throw new TypeError("callbacks.onProgress must be a function.");if(s.onError&&"function"!=typeof s.onError)throw new TypeError("callbacks.onError must be a function.");if("string"!=typeof o&&"function"!=typeof o)throw new TypeError("unknownArtist must be a string or a function returning a string.");let a,l="";const h=(t,r)=>{if(Wt(t,"stage"),void 0!==r&&!(r instanceof Event))throw new TypeError('Expected "event" to be an Event or undefined.');s.onProgress&&s.onProgress({event:r,status:"loading",stage:t,url:l||(e instanceof HTMLMediaElement?e.src:"unknown")})},u=(t,r)=>{if(!(t instanceof Error))throw new TypeError('Expected "error" to be an Error.');Wt(r,"stage"),s.onError&&s.onError({error:t instanceof Error?t:new Error(String(t)),url:l||(e instanceof HTMLMediaElement?e.src:"unknown"),stage:r})};try{h("INITIALIZING"),"string"==typeof e?(l=e,a=new Audio(l)):(a=e,l=a.src);try{await new Promise((e,t)=>{const r=e=>h("DOWNLOADING",e),i=()=>{n(),e(void 0)},s=e=>{n(),t(new Error(`HTMLMediaElement failed to load: ${e.message||"Unknown error"}`))},n=()=>{a.removeEventListener("progress",r),a.removeEventListener("loadedmetadata",i),a.removeEventListener("error",s)};a.addEventListener("progress",r),a.addEventListener("loadedmetadata",i),a.addEventListener("error",s),a.readyState>=1&&(n(),e(void 0))}),h("METADATA_LOADED")}catch(e){throw new Qt(e instanceof Error?e.message:"UNKNOWN ERROR",l,"METADATA")}const c={id:r.id||await Zt(l),duration:Math.floor(1e3*a.duration),url:l,weight:r.weight??1};let d={};h("EXTRACTING_ID3");try{d=await nr(l,i,n)}catch(e){u(e instanceof Error?e:new Error("Unknown Error"),"ID3"),console.warn(`[TinyAudioUtils] ID3 extraction failed for ${l}. Falling back to filename.`)}const p=e=>{Wt(e,"url");try{return(e.split(/[?#]/)[0].split("/").pop()??"").replace(/\.[^/.]+$/,"")||"Unknown Track"}catch{return"Unknown Track"}},m=e=>{const t={...e};return v(t._fetchData)&&(v(d._fetchData)&&(t._fetchData={...d._fetchData}),v(e._fetchData)&&(void 0!==e._fetchData.common&&(t._fetchData.common=e._fetchData.common),void 0!==e._fetchData.native&&(t._fetchData.native=e._fetchData.native),void 0!==e._fetchData.format&&(t._fetchData.format=e._fetchData.format),void 0!==e._fetchData.quality&&(t._fetchData.quality=e._fetchData.quality))),t},f={...c,...m(t),...d,...m(r),title:d.title||r.title||p(l),artist:d.artist||r.artist||("string"==typeof o?o:String(o()))};return s.onProgress&&s.onProgress({status:"success",stage:"COMPLETE",url:l}),f}catch(e){if(e instanceof Qt)throw e;const t=new Qt(e instanceof Error?e.message:"UNKNOWN ERROR",l,"INITIALIZING");throw u(t,"INITIALIZING"),t}},ar=le("TinyAfterScrollWatcher"),lr=class{#ot;get scrollTarget(){return ar(this.#u),this.#ot}#at=null;#lt=[];get afterScrollQueueSize(){return ar(this.#u),this.#lt.length}#ht=100;#ut=new Set;#ct=new Set;#u=!1;get destroyed(){return this.#u}constructor(e,t=100){if(!(e instanceof Element||e instanceof Window))throw new TypeError("scrollTarget must be an Element or the Window object.");this.#ot=e,this._checkTimer=this._checkTimer.bind(this),this.#ot.addEventListener("scroll",this._checkTimer),this.#ht=t}_checkTimer=()=>{this.#at&&clearTimeout(this.#at),this.#at=setTimeout(()=>{this.#at=null,this.#dt()},this.#ht)};get inactivityTime(){return ar(this.#u),this.#ht}set inactivityTime(e){if(ar(this.#u),"number"!=typeof e||e<=0||!Number.isFinite(e))throw new Error("inactivityTime must be a positive number in milliseconds.");this.#ht=e}#dt(){if(!this.#u){for(const e of this.#ct)"function"==typeof e&&e();for(;this.#lt.length;){const e=this.#lt.pop();"function"==typeof e&&e()}}}doAfterScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.lastScrollTime=Date.now(),this.#lt.push(e)}onStop(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ct.add(e)}offStop(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ct.delete(e)}onScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ot.addEventListener("scroll",e),this.#ut.add(e)}offScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ut.has(e)&&(this.#ot.removeEventListener("scroll",e),this.#ut.delete(e))}destroy(){if(!this.#u){this.#ot.removeEventListener("scroll",this._checkTimer);for(const e of this.#ut)this.#ot.removeEventListener("scroll",e);this.#ut.clear(),this.#ct.clear(),this.#u=!0}}},hr=le("UltraRandomMsgGen"),ur=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua"],cr=["😂","🌈","🤖","💥","🐸","🍕","🦄","🧠","🧬","🚀","🫠","💫","🍩","👾","🎉","🥴","🐙","🧃","🪐","🎈","🧸","👻","🥳","🍭","💖","😺","🌮","🪅","🎮","🥓","🍮","🍬","🍓","🍒","🥝","🥑","🍄","🌊","☁️","🌟","🌙","🧚","🐾","🐥","🐼","🐨","🐳","✨","🧁","🌸","🍃","💎","🎐","🎀","🫧","☄️","🛸","🔮"],dr=["pudding","bean","snuggle","bloop","jelly","unicorn","floof","giggle","bubble","muffin","puff","pickle","goblin","waffle","sprinkle","cupcake","fizzle","marshmallow","duckling","sock","cloud","teacup","nugget","gnome","hug","moonbean","crayon","jiggle","glitter","carrot","goober"],pr=["wiggles","bounces","flies","splats","scoots","giggles","wigglesnacks","twirls","boops","pops","sings","hugs","floats","glows","flaps","mlems","dances","puddles","nomnoms","wigglejumps","sniffs","tumbles","slides","chirps","burps","sparkles","waddles","rambles","blinks","mews"],mr=["fluffy","silly","yummy","squishy","wobbly","magical","tiny","sleepy","wiggly","bubbly","glittery","fuzzy","jiggly","sparkly","giggly","crunchy","goofy","soft","mushy","sweet","loopy","floaty","bonkers","chewy","ticklish","dreamy","pastel","cozy","teensy","grumbly"],fr=["Boop!","Wiggle achieved.","Oops, {noun} everywhere!","Tiny {adj} {noun}, big {adj} {noun}.","Snuggle initiated with a {adj} {noun}.","{adj} vibes only, powered by {noun}.","No {noun}, no {noun}.","Bounce first, {verb} later.","Mlem. {verb}. {noun}.","{noun} go brrr and {verb}.","Why not? {noun} did. Then {noun} followed.","A {adj} {noun} just {verb} near the {adj} window.","That {adj} {noun} stole my {noun}!","Look, a {adj} {noun} trying to {verb} again!","Every {noun} deserves a {adj} nap.","The {adj} {noun} is my {adj} spirit animal.","Someone call the {noun}, it’s {verb}ing and {verb}ing again!","Don’t touch the {adj} {noun}. It {verb}s loudly.","{noun} forgot how {noun}s work and just {verb}ed.","There once was a {adj} {noun} who loved to {verb} with a {adj} {noun} all day.","Apparently, {noun}s are banned from {verb}ing and {verb}ing in the {noun} library.","That {adj} noise? Just a {noun} learning to {verb} on a {adj} {noun}.","I saw a {adj} {noun} {verb} so hard, it became a {adj} muffin.","The {adj} {noun} met a {adj} pickle and everything {verb}ed.","{noun}s are like {noun}: {adj}, unpredictable, and wiggly.","Don’t judge a {adj} {noun} by its ability to {verb}, or by its {adj} hat.","All I wanted was peace, but a {adj} {noun} with a {adj} {noun} had other plans.","One {adj} morning, a {adj} {noun} decided it was finally time to {verb}, but halfway through, it tripped on a {noun} and turned into a {adj} marshmallow.","I tried to be {adj} today, but then a {noun} {verb}ed across my {noun} and typed “asdfgh{noun}” repeatedly.","If you think you’ve seen everything, wait until a {adj} {noun} {verb}s on a {noun} wearing {adj} socks with tiny {noun}s.","No one ever believed the stories about the ancient {adj} {noun} who could {verb} with such {adj} grace that entire {noun}s turned pink out of embarrassment.","A curious {adj} {noun} wandered into a {noun} shop, not knowing that its destiny involved twelve {adj} {noun}s, one rubber {noun}, and a suspiciously quiet {adj} llama.","In a land where every {adj} {noun} was made of pudding and the sky was {adj} whipped cream, one brave {adj} {noun} set out to discover the legendary Spoon of {noun}s, facing obstacles like bouncing {noun}s, sassy {noun}s, and the Great Wobble of the {noun}.","Once upon a {adj} time, long before the {noun}s learned to {verb}, there existed a tiny {adj} {noun} who dreamed of swimming in a pool made entirely of {adj} glitter pudding while {verb}ing off-key lullabies to passing {noun}s with monocles.","The Council of {noun}s gathered in {adj} secret when the sacred {adj} {noun} started to {verb} uncontrollably, threatening the entire {adj} dessert-based civilization with spontaneous {noun} jiggles and uncontainable {noun} fits across the {noun}.","Hey... do you ever wonder if {noun}s dream of {noun}s?","Okay but hear me out: what if the {adj} {noun} could actually {verb} backwards?","Can we talk about the {noun} that just {verb}ed and vanished?","So I was talking to a {noun}, and it told me to stop being {adj}. Rude.","Not to alarm you, but there’s a {adj} {noun} behind you doing the {verb}.","Why does this {noun} keep staring at me like I owe it pudding?","Is this a safe space to admit I accidentally {verb}ed a {noun}?","I just walked into the room and someone shouted “{adj} {noun}!” — what did I miss?","Wait... we were supposed to bring a {noun}? No one told me!","Okay but what if the {adj} {noun} has feelings too?","Be honest, do I look like a {noun} that forgot how to {verb}?",'If I say "oops", do I still have to explain why the {noun} is glowing?',"I don’t know what’s going on but I brought snacks and a confused {noun}.","Do you think pudding knows it’s pudding? Just a thought.","Is this about the time I {verb}ed the {adj} {noun} by accident? Because I can explain.","Wait, are we talking about {noun}s or am I on the wrong chat again?",'What is this group even about? I just saw "pudding" and joined.',"Hi! I have no idea what’s happening but I’m here and I brought a {noun}.","I blinked and now there’s a {adj} {noun} in charge of everything.","Can someone please explain why the {noun} is floating and chanting?","Okay who gave the {noun} access to glitter and emotional support pickles?","I came for a calm discussion and now there’s a {adj} battle between {noun}s.","Not sure if I’m early, late, or inside a {noun} dream.","I was gone for 3 minutes and now someone’s riding a {noun} into the pudding realm.","This isn’t the pudding appreciation group, is it? ...oh no.","So... who summoned the {adj} {noun} this time? Be honest.","I came here for vibes and stayed for the {noun}s.","Does anyone else hear faint giggling or is that just the {adj} {noun} again?","I feel like I missed step one, two, and also three of this conversation.","All I asked was “what’s up?” and now I’m emotionally attached to a {noun}.",'Me: "I’ll be normal today." Also me: *{verb}s into a meeting riding a {adj} {noun}*','"It’s just pudding," they said. "It can’t hurt you," they said. They were wrong.',"I said one nice thing to a {noun} and now it follows me everywhere.","Can we take a moment to appreciate how the {adj} {noun} is just vibing?","Who put a tiny hat on the {noun}? Because that’s adorable.","My life has been different ever since the {noun} started {verb}ing.","Raise your hand if you’ve ever been personally attacked by a {adj} {noun}.",'"Don’t be weird," they said. So I became a {noun} instead.',"Do {noun}s have feelings? Asking for a {adj} friend.","I trusted the {noun} and all I got was a glitter-covered sock.","Plot twist: the {adj} {noun} was inside us all along.","In the glow of the {adj} moon, the {noun} began to {verb}.","A sprinkle of {adj} dust made the {noun} {verb} through the air.","The {noun} whispered a {adj} secret that made everyone {verb}.","Everything felt {adj} and {adj}, especially when the {noun} {verb}ed.","The {noun} is {verb}ing! The {noun} is {verb}ing! AAAAA!","Glitch in the {noun}: the {adj} {noun} just {verb}ed out of existence.","The {adj} {noun} {verb} and {verb} all over the {adj} {noun}!","Oops! {noun}s {verb}ed into the {adj} {noun} while {verb}ing crazily.","{adj}, {adj}, and more {adj} {noun}s just {verb}ed by!","Why does the {adj} {noun} keep {verb}ing and {verb}ing without stopping?","Look! A {adj} {noun}, a {adj} {noun}, and a {noun} all {verb}ing together!","Sometimes, the {noun} just {verb}s, then {verb}s again, and never stops being {adj}.","{noun}, {noun}, and {noun} — all {verb}ing and {verb}ing in a {adj} {noun}.","I saw a {adj} {noun} {verb}, then another {noun} {verb}ing with a {adj} {noun}.","The {noun} {verb}s {verb} while the {adj} {noun} {verb}s and the {noun} just {verb}s.","Can a {adj} {noun} {verb} {verb} without a {adj} {noun} watching?","Whoa! The {adj} {noun} just {verb}ed... and then {verb}ed again!","Hey... did you see that {adj} {noun} {verb} over there?","Umm, the {noun} is {verb}ing but also {verb}ing and {verb}ing!","Lol! {noun}s {verb} so {adj}ly, it’s impossible not to giggle.",'"Hey! What’s up?" asked the {adj} {noun}, who {verb}ed loudly.','"I’m just a {adj} {noun} trying to {verb}, you know?"','"Did you see the {adj} {noun} that just {verb}ed in the pudding?"','"No way! The {noun} {verb}s better than me!"','"Wait, the {adj} {noun} said it would {verb}, but it {verb}ed instead!"',"Once upon a {adj} {noun}, a group of {adj} {noun}s {verb}ed through the {adj} forest, singing {adj} songs and eating {noun}s made of pudding.","The legend tells of a {adj} {noun} who could {verb} faster than any {noun} ever seen, leaving trails of {adj} sparkles behind.","Every day, the {adj} {noun} would {verb} around the {adj} meadow, trying to convince the {noun}s to join the grand pudding party.","No one knows why the {adj} {noun} suddenly {verb}ed and then {verb}ed again, but everyone agrees it was the cutest thing they ever saw.","In the kingdom of {adj} {noun}s, only the bravest {noun} dared to {verb} the giant pudding monster, armed with nothing but {adj} smiles and jellybeans.","{adj} {noun} {verb} {verb} {verb} {noun} {verb} {adj} {noun} {verb} {noun}!","{noun} {noun} {verb} {adj} {noun} and then {verb} {verb} the {adj} {noun}.","{verb} the {adj} {noun}, then {verb} the {noun} while {verb}ing {adj}ly.","Can the {adj} {noun} {verb} and {verb} the {adj} {noun} at the same time?","{noun} {verb} {noun} {verb}, but the {adj} {noun} {verb}s better.","Boop! The {adj} {noun} just {verb}ed in the pudding.","Bloop bloop, the {noun} is {verb}ing all over again!","Mlem mlem, a {adj} {noun} {verb}s quietly in the corner.","Splat! {noun} {verb}ed right on the {adj} {noun}.","Yum! A {adj} {noun} just {verb}ed in my mouth.","Do {noun}s really {verb} when nobody’s watching?","Why does the {adj} {noun} always {verb} at midnight?","Can a {noun} be too {adj} to {verb} properly?","Is it normal for a {adj} {noun} to {verb} three times in a row?","Who taught the {noun} to {verb} like that?","Wait, did the {adj} {noun} just {verb} itself?","I can’t believe the {noun} {verb}ed into a {adj} {noun}!","Suddenly, a {adj} {noun} appeared and started to {verb} wildly.","That {noun} was {verb}ing so {adj}ly it broke the pudding meter.","Everyone’s talking about the {adj} {noun} that {verb}ed out of nowhere."];class yr{static#pt=ur;static#mt=cr;static#ft=dr;static#yt=pr;static#gt=mr;static#wt=fr;static#bt(e,t){if(!Array.isArray(e))throw new TypeError(`${t} must be an array of strings`);if(!e.every(e=>"string"==typeof e))throw new TypeError(`${t} must contain only strings`);if(0===e.length)throw new Error(`${t} cannot be empty`)}static get defaultWords(){return[...this.#pt]}static set defaultWords(e){this.#bt(e,"defaultWords"),this.#pt=[...e]}static get defaultEmojis(){return[...this.#mt]}static set defaultEmojis(e){this.#bt(e,"defaultEmojis"),this.#mt=[...e]}static get defaultNouns(){return[...this.#ft]}static set defaultNouns(e){this.#bt(e,"defaultNouns"),this.#ft=[...e]}static get defaultVerbs(){return[...this.#yt]}static set defaultVerbs(e){this.#bt(e,"defaultVerbs"),this.#yt=[...e]}static get defaultAdjectives(){return[...this.#gt]}static set defaultAdjectives(e){this.#bt(e,"defaultAdjectives"),this.#gt=[...e]}static get defaultTemplates(){return[...this.#wt]}static set defaultTemplates(e){this.#bt(e,"defaultTemplates"),this.#wt=[...e]}#u=!1;get destroyed(){return this.#u}#vt={minLength:10,maxLength:300,readable:!0,useEmojis:!0,includeNumbers:!0,includeSymbols:!0,allowWeirdSpacing:!1,emojiSet:[],wordSet:[],mode:"mixed",grammar:{templates:[],nouns:[],verbs:[],adjectives:[]},repeatWords:!0,emojiPlacement:"inline",line:{minLength:20,maxLength:120,emojiChance:.3}};get config(){return hr(this.#u),structuredClone(this.#vt)}#Et="!@#$%^&*()-_=+[]{}|;:,.<>?/\\~".split("");get symbols(){return hr(this.#u),structuredClone(this.#Et)}constructor(e={}){const{minLength:t,maxLength:r,readable:i,useEmojis:s,includeNumbers:n,includeSymbols:o,allowWeirdSpacing:a,emojiSet:l,wordSet:h,mode:u,grammar:c,repeatWords:d,emojiPlacement:p,paragraphs:m,line:f}=e;if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.minLength must be an integer >= 1");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new TypeError("config.maxLength must be an integer >= 1");if(void 0!==t&&void 0!==r&&t>r)throw new RangeError("config.minLength cannot be greater than config.maxLength");if(void 0!==i&&"boolean"!=typeof i)throw new TypeError("config.readable must be a boolean");if(void 0!==s&&"boolean"!=typeof s)throw new TypeError("config.useEmojis must be a boolean");if(void 0!==n&&"boolean"!=typeof n)throw new TypeError("config.includeNumbers must be a boolean");if(void 0!==o&&"boolean"!=typeof o)throw new TypeError("config.includeSymbols must be a boolean");if(void 0!==a&&"boolean"!=typeof a)throw new TypeError("config.allowWeirdSpacing must be a boolean");if(void 0!==l&&!Array.isArray(l))throw new TypeError("config.emojiSet must be an array of strings");if(void 0!==h&&!Array.isArray(h))throw new TypeError("config.wordSet must be an array of strings");if(void 0!==u&&!["mixed","readable","chaotic","natural"].includes(u))throw new RangeError('config.mode must be one of: "mixed", "readable", "chaotic", "natural');if(void 0!==c){if("object"!=typeof c||null===c)throw new TypeError("config.grammar must be an object");const{templates:e,nouns:t,verbs:r,adjectives:i}=c;if(void 0!==e&&!Array.isArray(e))throw new TypeError("config.grammar.templates must be an array of strings");if(void 0!==t&&!Array.isArray(t))throw new TypeError("config.grammar.nouns must be an array of strings");if(void 0!==r&&!Array.isArray(r))throw new TypeError("config.grammar.verbs must be an array of strings");if(void 0!==i&&!Array.isArray(i))throw new TypeError("config.grammar.adjectives must be an array of strings")}if(void 0!==d&&"boolean"!=typeof d)throw new TypeError("config.repeatWords must be a boolean");if(void 0!==p&&!["inline","end","none"].includes(p))throw new RangeError('config.emojiPlacement must be one of: "inline", "end", "none"');if(void 0!==m){if("object"!=typeof m)throw new TypeError("config.paragraphs must be an object or null");const{min:e,max:t}=m;if(void 0!==e&&(!Number.isInteger(e)||e<1))throw new TypeError("config.paragraphs.min must be an integer >= 1");if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.paragraphs.max must be an integer >= 1");if(void 0!==e&&void 0!==t&&e>t)throw new RangeError("config.paragraphs.min cannot be greater than config.paragraphs.max")}if(void 0!==f){if("object"!=typeof f||null===f)throw new TypeError("config.line must be an object");const{minLength:e,maxLength:t,emojiChance:r}=f;if(void 0!==e&&(!Number.isInteger(e)||e<1))throw new TypeError("config.line.minLength must be an integer >= 1");if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.line.maxLength must be an integer >= 1");if(void 0!==e&&void 0!==t&&e>t)throw new RangeError("config.line.minLength cannot be greater than config.line.maxLength");if(void 0!==r&&("number"!=typeof r||r<0||r>1))throw new RangeError("config.line.emojiChance must be a number between 0 and 1")}this.#vt.emojiSet=[...yr.#mt],this.#vt.wordSet=[...yr.#pt],this.#vt.grammar.templates=[...yr.#wt],this.#vt.grammar.nouns=[...yr.#ft],this.#vt.grammar.verbs=[...yr.#yt],this.#vt.grammar.adjectives=[...yr.#gt],Object.assign(this.#vt,e)}configure(e={}){return hr(this.#u),Object.assign(this.#vt,e),this}setGrammarTemplates(...e){return hr(this.#u),this.#vt.grammar.templates=e.flat(),this}addGrammarTemplates(...e){return hr(this.#u),this.#vt.grammar.templates.push(...e.flat()),this}setGrammarNouns(...e){return hr(this.#u),this.#vt.grammar.nouns=e.flat(),this}addGrammarNouns(...e){return hr(this.#u),this.#vt.grammar.nouns.push(...e.flat()),this}setGrammarVerbs(...e){return hr(this.#u),this.#vt.grammar.verbs=e.flat(),this}addGrammarVerbs(...e){return hr(this.#u),this.#vt.grammar.verbs.push(...e.flat()),this}setGrammarAdjectives(...e){return hr(this.#u),this.#vt.grammar.adjectives=e.flat(),this}addGrammarAdjectives(...e){return hr(this.#u),this.#vt.grammar.adjectives.push(...e.flat()),this}removeGrammarTemplates(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.templates=this.#vt.grammar.templates.filter(e=>!t.has(e)),this}removeGrammarNouns(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.nouns=this.#vt.grammar.nouns.filter(e=>!t.has(e)),this}removeGrammarVerbs(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.verbs=this.#vt.grammar.verbs.filter(e=>!t.has(e)),this}removeGrammarAdjectives(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.adjectives=this.#vt.grammar.adjectives.filter(e=>!t.has(e)),this}setWords(...e){return hr(this.#u),this.#vt.wordSet=e.flat(),this}addWords(...e){return hr(this.#u),this.#vt.wordSet.push(...e.flat()),this}removeWords(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.wordSet=this.#vt.wordSet.filter(e=>!t.has(e)),this}setEmojis(...e){return hr(this.#u),this.#vt.emojiSet=e.flat(),this}addEmojis(...e){return hr(this.#u),this.#vt.emojiSet.push(...e.flat()),this}removeEmojis(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.emojiSet=this.#vt.emojiSet.filter(e=>!t.has(e)),this}_getRandomItem(e){return e[Math.floor(Math.random()*e.length)]}_generateChunk(){const{wordSet:e,emojiSet:t,includeNumbers:r,includeSymbols:i,useEmojis:s,readable:n,mode:o,emojiPlacement:a}=this.#vt;if("natural"===o)return this._generateNaturalSentence();const l=[];return(n||"readable"===o||"mixed"===o)&&l.push(this._getRandomItem(e)),"chaotic"!==o&&"mixed"!==o||l.push(Math.random().toString(36).slice(2)),r&&l.push(Math.floor(99999*Math.random()).toString()),i&&l.push(this._getRandomItem(this.#Et)),"inline"===a&&s&&t.length&&l.push(this._getRandomItem(t)),this._getRandomItem(l)}_generateNaturalSentence(){const{templates:e,nouns:t,verbs:r,adjectives:i}=this.#vt.grammar;return this._getRandomItem(e).replace(/{noun}/g,()=>this._getRandomItem(t)).replace(/{verb}/g,()=>this._getRandomItem(r)).replace(/{adj}/g,()=>this._getRandomItem(i))}_generateLine(e,t){const{allowWeirdSpacing:r,repeatWords:i,readable:s,emojiSet:n,useEmojis:o,emojiPlacement:a,line:l}=this.#vt,h=[];for(t??=new Set;h.join(" ").length<e;){let e=this._generateChunk();!i&&t.has(e)||(t.add(e),r&&(Math.random()<.1&&(e="\n"+e),Math.random()<.1&&(e=" "+e),Math.random()<.05&&(e=e.toUpperCase())),h.push(e))}let u=h.join(s?" ":"");return"end"===a&&o&&n.length&&Math.random()<(l?.emojiChance||0)&&(u+=" "+this._getRandomItem(n)),u}_generateParagraphLines(e){const{line:t}=this.#vt,r=[],i=new Set;let s=0;for(;s<e;){const n=Math.floor(Math.random()*(t.maxLength-t.minLength+1)+t.minLength),o=Math.min(n,e-s);r.push(this._generateLine(o,i)),s+=o}return r}generate(){hr(this.#u);const{minLength:e,maxLength:t,paragraphs:r}=this.#vt,i=Math.floor(Math.random()*(t-e+1))+e;if(r&&"object"==typeof r){const e=Math.floor(Math.random()*(r.max-r.min+1))+r.min,t=Math.floor(i/e),s=[];for(let r=0;r<e;r++){const e=this._generateParagraphLines(t);s.push(e.join("\n"))}return s.join("\n\n")}return this._generateParagraphLines(i).join("\n")}destroy(){this.destroyed||(this.#Et=[],this.#vt.emojiSet=[],this.#vt.wordSet=[],this.#vt.grammar.templates=[],this.#vt.grammar.nouns=[],this.#vt.grammar.verbs=[],this.#vt.grammar.adjectives=[],this.#u=!0)}}const gr=yr;e();const wr=le("TinySmartScroller"),br=e().EventEmitter;class vr extends br{static Utils={...n,TinyHtml:Pt};#Tt=new WeakMap;#St=new WeakMap;#xt=new WeakMap;#At=new WeakMap;#Ct=new WeakMap;#It=new WeakMap;#Dt=null;#kt=null;#Mt=new Set(["IMG","IFRAME","VIDEO"]);#Lt=null;#Nt=!1;#_t=!1;#Pt=!1;#Rt=!1;#jt=!1;#Ot=!1;#$t=!1;#Ht=!1;#Ft="";#zt=!1;#u=!1;#Bt=!1;#Wt=!1;#qt=!1;#Vt=!1;#Ut=0;#Kt=0;#Jt=0;#Gt=0;#Yt=0;#Xt;#Qt;#F;#Zt=new Set;constructor(e,{extraScrollBoundary:t=0,autoScrollBottom:r=!0,observeMutations:i=!0,preserveScrollOnLayoutShift:s=!0,debounceTime:n=100,querySelector:o=null,attributeFilter:a=["class","style","src","data-*","height","width"]}={}){if(super(),!(e instanceof Element||e===window))throw new TypeError("TinySmartScroller: 'target' must be a DOM Element or 'window', but got "+typeof e);if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`TinySmartScroller: 'extraScrollBoundary' must be a valid number, received ${t}`);if("boolean"!=typeof r)throw new TypeError("TinySmartScroller: 'autoScrollBottom' must be a boolean, received "+typeof r);if("boolean"!=typeof i)throw new TypeError("TinySmartScroller: 'observeMutations' must be a boolean, received "+typeof i);if("boolean"!=typeof s)throw new TypeError("TinySmartScroller: 'preserveScrollOnLayoutShift' must be a boolean, received "+typeof s);if("number"!=typeof n||n<0||Number.isNaN(n))throw new TypeError(`TinySmartScroller: 'debounceTime' must be a non-negative number, received ${n}`);if(null!==o&&"string"!=typeof o)throw new TypeError("TinySmartScroller: 'querySelector' must be a string or null, received "+typeof o);if(!(null===a||Array.isArray(a)||a instanceof Set))throw new TypeError("TinySmartScroller: 'attributeFilter' must be an array, Set, or null. Got "+typeof a);let l;this.#F=e,this.#Qt=e instanceof Window?document.documentElement:e,this.#zt=e instanceof Window,this.#Wt=r,this.#qt=i,this.#Vt=s,this.#Ut=n,this.#Yt=t,this.#Ft=o||"",this.#Xt=new Set(a||void 0),this.#Lt=()=>{this._scrollDataUpdater(),clearTimeout(l),l=setTimeout(()=>this._onScroll(),this.#Ut)},(this.#zt?window:this.#Qt).addEventListener("scroll",this.#Lt,{passive:!0}),this.#qt&&(this._observeMutations(),this._observeResizes(this.#Qt.children)),this._scrollDataUpdater()}getSimpleOnHeight(e=[]){if(wr(this.#u),!Array.isArray(e))throw new TypeError("getSimpleOnHeight(filter): filter must be an array of tag names");return(t,r,i)=>{if(e.length>0&&!e.includes(t.tagName)||i.now!==i.old)return;const s=r.old;return{height:r.now.height-s.height,width:0}}}addSimpleOnHeight(e){if(wr(this.#u),!Array.isArray(e))throw new TypeError("addSimpleOnHeight(filter): filter must be an array of tag names");const t=this.getSimpleOnHeight(e);return this.onSize(t),t}getLoadTags(){return wr(this.#u),Array.from(this.#Mt)}addLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("addLoadTag(tag): tag must be a string");this.#Mt.add(e.toUpperCase())}removeLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("removeLoadTag(tag): tag must be a string");this.#Mt.delete(e.toUpperCase())}hasLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("hasLoadTag(tag): tag must be a string");return this.#Mt.has(e.toUpperCase())}resetLoadTags(e=!1){if(wr(this.#u),"boolean"!=typeof e)throw new TypeError("resetLoadTags(addDefault): addDefault must be a boolean");this.#Mt.clear(),e&&(this.#Mt.add("IMG"),this.#Mt.add("IFRAME"),this.#Mt.add("VIDEO"))}getAttributeFilters(){return wr(this.#u),Array.from(this.#Xt)}addAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("addAttributeFilter(attr): attr must be a string");this.#Xt.add(e)}removeAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("removeAttributeFilter(attr): attr must be a string");this.#Xt.delete(e)}hasAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("hasAttributeFilter(attr): attr must be a string");return this.#Xt.has(e)}resetAttributeFilters(e=!1){if(wr(this.#u),"boolean"!=typeof e)throw new TypeError("resetAttributeFilters(addDefault): addDefault must be a boolean");this.#Xt.clear(),e&&["class","style","src","data-*","height","width"].forEach(e=>this.#Xt.add(e))}onSize(e){if(wr(this.#u),"function"!=typeof e)throw new TypeError("onSize(handler): handler must be a function");this.#Zt.add(e)}offSize(e){if(wr(this.#u),"function"!=typeof e)throw new TypeError("offSize(handler): handler must be a function");this.#Zt.delete(e)}_scrollDataUpdater(){const e=new Map;return this.#Qt.querySelectorAll(this.#Ft||"*").forEach(t=>{const r=this.#xt.get(t)??!1;this.#At.set(t,r);const i=Pt.isInContainer(this.#Qt,t);this.#xt.set(t,i),e.set(t,{oldIsVisible:r,isVisible:i})}),e}_onScroll(){if(this.#u)return;const e=this._scrollDataUpdater(),t=this.#Qt,r=t.scrollTop,i=t.scrollHeight,s=t.clientHeight,n={scrollTop:r,scrollHeight:i,clientHeight:s};let o=null,a=null;const l=0===r,h=r+s>=i-1,u=r<=0+this.#Yt,c=r+s>=i-1-this.#Yt;l&&h?o="all":l?o="top":h&&(o="bottom"),u&&c?a="all":u?a="top":c&&(a="bottom"),this.#_t=this.#Ot??!1,this.#Nt=this.#jt??!1,this.#Pt=this.#$t??!1,this.#Rt=this.#Ht??!1,this.#Ot=l,this.#jt=h,this.#$t=u,this.#Ht=c,this.#Bt=!(this.#Wt&&this.#jt),this.#Gt=i-r-s,this.emit("onScrollBoundary",{status:o,...n,scrollCache:e}),this.emit("onExtraScrollBoundary",{status:a,...n,scrollCache:e}),this.#Bt?this.emit("onScrollPause",{...n,scrollCache:e}):this.emit("onAutoScroll",{...n,scrollCache:e})}_fixScroll(e=[]){if(this.#u)return;if(!Array.isArray(e))throw new TypeError("_fixScroll: targets must be an array of Elements");const t=this.#Qt.scrollHeight,r=this.#Qt.scrollTop,i=this.#Qt.scrollHeight-this.#Qt.scrollTop-this.#Qt.clientHeight,s=this.#Qt.scrollHeight-t,n=()=>{const t={height:0,width:0};for(const r of e){const e=this.#Tt.get(r)||{height:0,width:0},i=this.#St.get(r)||{height:0,width:0};this.#Zt.forEach(s=>{const n=s(r,{old:e,now:i},{old:this.#Jt,now:this.#Kt});if(this.#xt.get(r)||this.#Ct.get(r)){if(void 0!==n&&"object"!=typeof n)throw new Error("_fixScroll: size filter must return an object or undefined");if(void 0===n)return;t.height=n.height,t.width=n.width}})}if("number"!=typeof t.height&&t.height<0)throw new Error("_fixScroll: invalid scrollSize.height value");if("number"!=typeof t.width&&t.width<0)throw new Error("_fixScroll: invalid scrollSize.width value");if(0!==t.height||0!==t.width)for(const t of e)this.#Ct.set(t,this.#xt.get(t)??!1),this.#It.set(t,this.#At.get(t)??!1);return t};if(this.#Jt>0&&Pt.hasScroll(this.#Qt).v&&this.#Wt&&this.#Vt&&!this.#jt&&!this.#Ot){const e=n();this.#Qt.scrollTop=r+s+e.height,e.width>0&&(this.#Qt.scrollLeft=this.#Qt.scrollLeft+e.width)}else!this.#Bt&&this.#Wt?(n(),this.scrollToBottom()):this.#Wt||this.#jt||(n(),this.#Qt.scrollTop=this.#Qt.scrollHeight-this.#Qt.clientHeight-i)}_observeMutations(){this.#kt=new MutationObserver(e=>{this.#u||(this._scrollDataUpdater(),this.#Jt=this.#Kt,this.#Kt=this.#Qt.childElementCount,e.forEach(e=>{e.addedNodes.forEach(e=>{if(e instanceof Element&&1===e.nodeType&&(this._observeResizes([e]),this._listenLoadEvents(e),this.#Ft)){const t=e.querySelectorAll(this.#Ft);this._observeResizes(t),this._listenLoadEvents(t)}})}),this._fixScroll())}),this.#kt.observe(this.#Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:this.#Xt.size>0?Array.from(this.#Xt):void 0})}_observeResizes(e){this.#Dt||(this.#Dt=new ResizeObserver(e=>{if(this.#u)return;this._scrollDataUpdater();const t=[];for(const r of e){const e=r.target,i=this.#St.get(e);i&&this.#Tt.set(e,i);const{width:s,height:n}=r.contentRect;this.#St.set(e,{width:s,height:n}),t.push(e)}this._fixScroll(t)})),Array.from(e).forEach(e=>{if(!this.#Dt)throw new Error("_observeResizes: ResizeObserver instance is not initialized");this.#Dt.observe(e)})}_listenLoadEvents(e){this.#u||(e instanceof NodeList?Array.from(e):[e]).forEach(e=>{this.#Mt.has(e.tagName)&&(e.complete||e.addEventListener("load",()=>{this._scrollDataUpdater(),!this.#Bt&&this.#Wt&&this.scrollToBottom()}))})}get target(){return this.#F}get targetElement(){return this.#Qt}getOldSize(e){return wr(this.#u),this.#Tt.get(e)??null}getNewSize(e){return wr(this.#u),this.#St.get(e)??null}wasVisible(e){return wr(this.#u),this.#At.get(e)??!1}isVisible(e){return wr(this.#u),this.#xt.get(e)??!1}wasTimedVisible(e){return wr(this.#u),this.#It.get(e)??!1}isTimedVisible(e){return wr(this.#u),this.#Ct.get(e)??!1}setExtraScrollBoundary(e){if(wr(this.#u),"number"!=typeof e||Number.isNaN(e))throw new TypeError("setExtraScrollBoundary(value): value must be a valid number");this.#Yt=e}getExtraScrollBoundary(){return wr(this.#u),this.#Yt}getLastKnownScrollBottomOffset(){return wr(this.#u),this.#Gt}scrollToBottom(){wr(this.#u),this.#Qt.scrollTop=this.#Qt.scrollHeight}scrollToTop(){wr(this.#u),this.#Qt.scrollTop=0}isAtCustomBottom(){return wr(this.#u),this.#Ht}isAtCustomTop(){return wr(this.#u),this.#$t}isAtBottom(){return wr(this.#u),this.#jt}isAtTop(){return wr(this.#u),this.#Ot}isPastAtBottom(){return wr(this.#u),this.#Nt}isPastAtTop(){return wr(this.#u),this.#_t}isPastAtCustomTop(){return wr(this.#u),this.#Pt}isPastAtCustomBottom(){return wr(this.#u),this.#Rt}isScrollPaused(){return wr(this.#u),this.#Bt}isWindow(){return wr(this.#u),this.#zt}isDestroyed(){return this.#u}getAutoScrollBottom(){return wr(this.#u),this.#Wt}getObserveMutations(){return wr(this.#u),this.#qt}getPreserveScrollOnLayoutShift(){return wr(this.#u),this.#Vt}getDebounceTime(){return wr(this.#u),this.#Ut}getElemAmount(){return wr(this.#u),this.#Kt}getPrevElemAmount(){return wr(this.#u),this.#Jt}getQuerySelector(){return wr(this.#u),this.#Ft}destroy(){if(this.#u)return;this.#kt&&(this.#kt.disconnect(),this.#kt=null),this.#Dt&&(this.#Dt.disconnect(),this.#Dt=null);const e=this.#zt?window:this.#Qt;this.#Lt&&e.removeEventListener("scroll",this.#Lt),this.#Tt=new WeakMap,this.#St=new WeakMap,this.#xt=new WeakMap,this.#At=new WeakMap,this.#Ct=new WeakMap,this.#It=new WeakMap,this.removeAllListeners(),this.#Zt.clear(),this.#Mt.clear(),this.#u=!0}}const Er=vr,Tr=class{#G;#er;#tr;constructor(e,{openTag:t="[",closeTag:r="]"}={}){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement))throw new TypeError("Element must be an input or textarea.");if("string"!=typeof t)throw new TypeError("openTag must be a string.");if("string"!=typeof r)throw new TypeError("closeTag must be a string.");this.#G=e,this.#er=t,this.#tr=r}getOpenTag(){return this.#er}getCloseTag(){return this.#tr}setOpenTag(e){if("string"!=typeof e)throw new TypeError("Open tag must be a string.");this.#er=e}setCloseTag(e){if("string"!=typeof e)throw new TypeError("Close tag must be a string.");this.#tr=e}ensureFocus(){return document.activeElement!==this.#G&&this.#G.focus(),this}focus(){return this.#G.focus(),this}getSelectionRange(){return{start:this.#G.selectionStart??NaN,end:this.#G.selectionEnd??NaN}}setSelectionRange(e,t,r=!0){if("number"!=typeof e||"number"!=typeof t)throw new TypeError("start and end must be numbers.");if("boolean"!=typeof r)throw new TypeError("preserveScroll must be a boolean.");const i=this.#G.scrollTop,s=this.#G.scrollLeft;return this.#G.setSelectionRange(e,t),r&&(this.#G.scrollTop=i,this.#G.scrollLeft=s),this}getValue(){return this.#G.value}setValue(e){if("string"!=typeof e)throw new TypeError("Value must be a string.");return this.#G.value=e,this}getSelectedText(){const{start:e,end:t}=this.getSelectionRange();return this.#G.value.slice(e,t)}insertText(e,{newCursor:t="end",autoSpacing:r=!1,autoSpaceLeft:i=r,autoSpaceRight:s=r}={}){if("string"!=typeof e)throw new TypeError("Text must be a string.");if(!["start","end","preserve"].includes(t))throw new TypeError("newCursor must be one of 'start', 'end', or 'preserve'.");if("boolean"!=typeof r)throw new TypeError("autoSpacing must be a boolean.");if("boolean"!=typeof i)throw new TypeError("autoSpaceLeft must be a boolean.");if("boolean"!=typeof s)throw new TypeError("autoSpaceRight must be a boolean.");const{start:n,end:o}=this.getSelectionRange(),a=this.#G.value,l=a[n-1]||"",h=a[o]||"",u=`${i&&l&&!/\s/.test(l)?" ":""}${e}${s&&h&&!/\s/.test(h)?" ":""}`,c=a.slice(0,n)+u+a.slice(o);this.setValue(c);let d=n;return"end"===t?d=n+u.length:"preserve"===t&&(d=n),this.setSelectionRange(d,d),this}deleteSelection(){return this.insertText(""),this}transformSelection(e){if("function"!=typeof e)throw new TypeError("transformer must be a function.");const{start:t}=this.getSelectionRange(),r=e(this.getSelectedText());return this.insertText(r),this.setSelectionRange(t,t+r.length),this}surroundSelection(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("prefix and suffix must be strings.");const r=this.getSelectedText();return this.insertText(`${e}${r}${t}`),this}moveCaret(e){if("number"!=typeof e)throw new TypeError("offset must be a number.");const{start:t}=this.getSelectionRange(),r=Math.max(0,t+e);return this.setSelectionRange(r,r),this}selectAll(){return this.setSelectionRange(0,this.#G.value.length),this}expandSelection(e,t){if("number"!=typeof e||"number"!=typeof t)throw new TypeError("before and after must be numbers.");const{start:r,end:i}=this.getSelectionRange(),s=Math.max(0,r-e),n=Math.min(this.#G.value.length,i+t);return this.setSelectionRange(s,n),this}replaceAll(e,t){if(!(e instanceof RegExp))throw new TypeError("regex must be a RegExp.");if("function"!=typeof t)throw new TypeError("replacer must be a function.");const r=this.#G.value.replace(e,t);return this.setValue(r),this}replaceInSelection(e,t){if(!(e instanceof RegExp))throw new TypeError("regex must be a RegExp.");if("function"!=typeof t)throw new TypeError("replacer must be a function.");const{start:r,end:i}=this.getSelectionRange(),s=this.#G.value,n=s.slice(r,i).replace(e,t),o=s.slice(0,r)+n+s.slice(i);return this.setValue(o),this.setSelectionRange(r,r+n.length),this}toggleCode(e){if("string"!=typeof e)throw new TypeError("codeName must be a string.");const t=this.getSelectedText();if(t.startsWith(e)&&t.endsWith(e)){const r=t.slice(e.length,t.length-e.length);this.insertText(r)}else this.insertText(`${e}${t}${e}`);return this}_insertAttr(e){let t="";if(Array.isArray(e)){if(!e.every(e=>"string"==typeof e))throw new TypeError("All entries in attributes array must be strings.");t=e.map(e=>`${e}`).join(" ")}else{if("object"!=typeof e||null===e)throw new TypeError("attributes must be an object or an array of strings.");t=Object.entries(e).map(([e,t])=>{if("string"!=typeof t)throw new TypeError("All entries in attributes object must be strings.");return`${e}${t.length>0?`="${t}"`:""}`}).join(" ")}return t}wrapWithTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this._insertAttr(t),i=r?`${this.#er}${e} ${r}${this.#tr}`:`${this.#er}${e}${this.#tr}`,s=`${this.#er}/${e}${this.#tr}`;return this.surroundSelection(i,s),this}insertTag(e,t="",r={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");if("string"!=typeof t)throw new TypeError("content must be a string.");const i=this._insertAttr(r),s=i?`${this.#er}${e} ${i}${this.#tr}`:`${this.#er}${e}${this.#tr}`,n=`${this.#er}/${e}${this.#tr}`;return this.insertText(`${s}${t}${n}`),this}insertSelfClosingTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this._insertAttr(t),i=r?`${this.#er}${e} ${r}${this.#tr}`:`${this.#er}${e}${this.#tr}`;return this.insertText(i),this}toggleTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this.getSelectedText(),i=new RegExp(`^\\[${e}(\\s+[^\\]]*)?\\]`),s=new RegExp(`\\[/${e}\\]$`),n=i.test(r),o=s.test(r);if(n&&o){const e=r.replace(i,"").replace(s,"");this.insertText(e)}else{const i=this._insertAttr(t),s=i?`${this.#er}${e} ${i}${this.#tr}`:`${this.#er}${e}${this.#tr}`,n=`${this.#er}/${e}${this.#tr}`;this.insertText(`${s}${r}${n}`)}return this}},Sr=class{#rr=!1;#ir=!1;#sr=null;#nr=null;constructor(){void 0!==navigator.clipboard&&null!==navigator.clipboard&&(this.#ir=!0,this.#sr=e=>navigator.clipboard.writeText(e),this.#nr=e=>navigator.clipboard.write([new ClipboardItem({[e.type]:e})])),this.#rr=void 0!==document.execCommand&&null!==document.execCommand}setCopyText(e){if("function"!=typeof e)throw new TypeError("setCopyText expected a function that returns Promise<void>.");this.#sr=e}setCopyBlob(e){if("function"!=typeof e)throw new TypeError("setCopyBlob expected a function that returns Promise<void>.");this.#nr=e}copyText(e){if("string"!=typeof e)throw new TypeError("copyText expected a string.");if(this.#sr)return this.#sr(e);if(this.#rr){const t=document.body,r=document.createElement("input");return r.style.position="fixed",r.style.opacity="0",r.value=e,t.append(r),r.select(),r.setSelectionRange(0,99999),document.execCommand("Copy"),r.remove(),new Promise(e=>e(void 0))}throw new Error("Clipboard API not found!")}copyBlob(e){if(!(e instanceof Blob))throw new TypeError("copyBlob expected a Blob instance.");return new Promise((t,r)=>{if(this.#nr)return this.#nr(e).then(t).catch(r);throw new Error("Clipboard API not found!")})}_handleBlob(e,t){return t.getType(e)}_handleText(e,t){return this._handleBlob(e,t).then(e=>e.text())}_readData(e=0,t=null,r=null,i=!1){return new Promise((s,n)=>{this._read(e).then(o=>{if(!o)return s(null);const a=[];let l=!0;const h=async(e,s)=>{if(l)if(null!==t&&"custom"!==t||"string"!=typeof r||!(!i&&e.startsWith(r)||i&&e===r))if(null!==t&&"text"!==t||"text/plain"!==e){if(null===t){l=!1;const t=await this._handleBlob(e,s);t&&a.push(t)}}else{l=!1;const t=await this._handleText(e,s);t&&a.push(t)}else{l=!1;const t=await this._handleBlob(e,s);t&&a.push(t)}},u=[],c=e=>{if(!(e instanceof ClipboardItem))throw new Error("Expected ClipboardItem when reading data.");for(const t in e.types)u.push(h(e.types[t],e))};if("number"==typeof e&&!Number.isNaN(e)&&Number.isFinite(e)&&e>-1)c(o),Promise.all(u).then(()=>{a[0]?s(a[0]):s(null)}).catch(n);else if(Array.isArray(o)){for(const e in o)c(o[e]);Promise.all(u).then(()=>s(a)).catch(n)}}).catch(n)})}async readText(e=0){const t=await this._readData(e,"text");if("string"!=typeof t)throw new Error("Failed to read text: expected string result.");return t}async readCustom(e=null,t=!1,r=0){const i=await this._readData(r,"custom",e,t);if(!(i instanceof Blob))throw new Error("Failed to read custom data: expected Blob.");return i}async readAllTexts(){const e=await this._readData(null,"text");if(!Array.isArray(e))throw new Error("Expected array of strings when reading all texts.");if(!e.every(e=>"string"==typeof e))throw new Error("Some values returned were not strings.");return e}async readAllCustom(e=null,t=!1){const r=await this._readData(null,"custom",e,t);if(!Array.isArray(r))throw new Error("Expected array of blobs when reading all custom items.");if(!r.every(e=>e instanceof Blob))throw new Error("Some values returned were not Blob instances.");return r}async readAllData(e=null,t=null){const r=await this._readData(null,e,t);if(!Array.isArray(r))throw new Error("Expected array result when reading all data.");return r}_read(e){return new Promise((t,r)=>{this.#ir||r(new Error("Clipboard API not found!")),navigator.clipboard.read().then(r=>{if("number"==typeof e){if(Number.isNaN(e)||!Number.isFinite(e)||e<0)throw new Error(`Invalid index value: ${e}`);r[e]?t(r[e]):t(null)}t(r)}).catch(r)})}async readIndex(e){const t=await this._read(e);if(null!==t&&!(t instanceof ClipboardItem))throw new Error(`Value at index ${e} is not a ClipboardItem.`);return t}async readAll(){const e=await this._read(null);if(!Array.isArray(e))throw new Error("Expected array result from clipboard read.");for(const t of e)if(!(t instanceof ClipboardItem))throw new Error("Invalid item type found in clipboard result.");return e}isExecCommandAvailable(){return this.#rr}isNavigatorClipboardAvailable(){return this.#ir}getCopyTextFunc(){return this.#sr}getCopyBlobFunc(){return this.#nr}};class xr{static _rca(e,t,r){let i=127,s=128;void 0===e&&(e=24),void 0===t&&(t="rgb"),!0===r&&(i=55,s=200);const n=2*Math.PI/e,o=[];for(let r=0;r<e;++r){const e=Math.sin(n*r+2)*i+s,a=Math.sin(n*r+0)*i+s,l=Math.sin(n*r+4)*i+s;switch(t){case"hex":o.push({hex:this.rgbToHex(Math.round(e),Math.round(a),Math.round(l))});break;case"rgb":o.push({r:e,g:a,b:l});break;case"hsl":const[t,r,i]=this.rgbaToHsl(Math.round(e),Math.round(a),Math.round(l));o.push({h:t,s:r,l:i})}}return o}static rcaRgb(e,t){return xr._rca(e,"rgb",t)}static rcaHsl(e,t){return xr._rca(e,"hsl",t)}static rcaHex(e,t){return xr._rca(e,"hex",t)}static randomColor(){return`#${Math.floor(16777216*Math.random()).toString(16).padStart(6,"0")}`}static parseInput(e,t){if("string"==typeof e){if((e=e.trim().toLowerCase()).startsWith("#"))return this.hexToRgba(e);if(e.startsWith("rgb"))return this.rgbStringToRgbaArray(e);if(e.startsWith("hsl"))return this.hslStringToRgbaArray(e)}if("number"==typeof e)return this.intToRgba(e);if(Array.isArray(e)&&(3===e.length||4===e.length)&&e.every(e=>"number"==typeof e)){if(t){const[t,r,i,s]=e;if(t<=360&&r<=100&&i<=100)return this.hslToRgba(t,r,i,s)}return[...e,1].slice(0,4)}throw new Error("Unsupported color format.")}static hslToInt(e,t,r){const[i,s,n]=xr.hslToRgba(e,t,r);return xr.rgbToInt(i,s,n)}static hslToHex(e,t,r){const[i,s,n]=xr.hslToRgba(e,t,r);return xr.rgbToHex(i,s,n)}static hslStringToRgbaArray(e){const t=e.match(/[\d.]+/g)?.map(Number);if(!t||t.length<3)return[0,0,0,1];const[r,i,s,n=1]=t;return this.hslToRgba(r,i,s,n)}static hslToRgba(e,t,r,i=1){r/=100;const s=t=>(t+e/30)%12,n=(t/=100)*Math.min(r,1-r),o=e=>r-n*Math.max(-1,Math.min(s(e)-3,Math.min(9-s(e),1)));return[Math.round(255*o(0)),Math.round(255*o(8)),Math.round(255*o(4)),i]}static hslToRgb(e,t,r,i=1){return xr.hslToRgba(e,t,r,i).slice(0,3)}static hexToInt(e){return parseInt(e.replace(/^#/,""),16)}static hexToHsl(e){const[t,r,i,s]=xr.hexToRgba(e);return xr.rgbaToHsl(t,r,i,s)}static hexToHsla(e){const[t,r,i,s]=xr.hexToRgba(e);return xr.rgbaToHsla(t,r,i,s)}static hexToRgba(e){3===(e=e.replace(/^#/,"")).length&&(e=e.split("").map(e=>e+e).join(""));const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t,1]}static hexToRgb(e){return this.hexToRgba(e).slice(0,3)}static rgbToHex(e,t,r){return"#"+[e,t,r].map(e=>e.toString(16).padStart(2,"0")).join("")}static rgbToInt(e,t,r){return e<<16|t<<8|r}static rgbaToHsla(e,t,r,i=1){e/=255,t/=255,r/=255;const s=Math.max(e,t,r),n=Math.min(e,t,r);let o=0,a=0,l=(s+n)/2;const h=s-n;if(0!==h){switch(a=h/(1-Math.abs(2*l-1)),s){case e:o=(t-r)/h+(t<r?6:0);break;case t:o=(r-e)/h+2;break;case r:o=(e-t)/h+4}o*=60}return[Math.round(o),Math.round(100*a),Math.round(100*l),i]}static rgbaToHsl(e,t,r,i){return this.rgbaToHsla(e,t,r,i).slice(0,3)}static rgbStringToRgbaArray(e){const t=e.match(/[\d.]+/g)?.map(Number);return t?[...t,1].slice(0,4):[]}static intToHsl(e){const[t,r,i,s]=xr.intToRgba(e);return xr.rgbaToHsl(t,r,i,s)}static intToHsla(e){const[t,r,i,s]=xr.intToRgba(e);return xr.rgbaToHsla(t,r,i,s)}static intToHex(e){return"#"+e.toString(16).padStart(6,"0")}static intToRgba(e){return[e>>16&255,e>>8&255,255&e,1]}#or="#000000";#ar=[0,0,0,0];#lr;constructor(e=null,t=!1){this.#lr=t,null!=e&&this.setColor(e)}setColor(e){this.#or=e;const t=this.#lr&&Array.isArray(e)&&e[0]<=360&&e[1]<=100&&e[2]<=100;this.#ar=xr.parseInput(e,t)}toHslaArray(){const[e,t,r,i]=this.#ar;return xr.rgbaToHsla(e,t,r,i)}toHslString(){const[e,t,r]=this.#ar,[i,s,n]=xr.rgbaToHsl(e,t,r);return`hsl(${i}, ${s}%, ${n}%)`}toHslaString(){const[e,t,r,i]=this.#ar,[s,n,o,a]=xr.rgbaToHsla(e,t,r,i);return`hsla(${s}, ${n}%, ${o}%, ${a??1})`}toRgbaArray(){return[...this.#ar]}toRgbString(){const[e,t,r]=this.#ar;return`rgb(${e}, ${t}, ${r})`}toRgbaString(){const[e,t,r,i]=this.#ar;return`rgba(${e}, ${t}, ${r}, ${i??1})`}toHex(){const[e,t,r]=this.#ar;return xr.rgbToHex(e,t,r)}toInt(){const[e,t,r]=this.#ar;return xr.rgbToInt(e,t,r)}getOriginal(){return this.#or}}const Ar=xr,Cr=(e,t=100)=>{if("function"!=typeof e)throw new TypeError("Expected 'getValue' to be a function.");if(!Number.isFinite(t)||t<=0)throw new TypeError("Expected 'checkInterval' to be a positive number.");return new Promise(r=>{const i=setInterval(()=>{e()&&(clearInterval(i),r())},t)})},Ir=(e,t=!0)=>{if("function"!=typeof e)throw new TypeError('The argument "baseFunction" must be a function.');let r=null;const i={ended:!1,failed:!1,loading:!1};return{callback:async(...s)=>(null!==r||(i.loading=!0,r=(async()=>{try{const n=await e(...s);return i.ended=!0,i.failed=!1,i.loading=!1,t&&(r=null),n}catch(e){throw i.ended=!0,i.failed=!0,i.loading=!1,t&&(r=null),e}})()),r),getActivePromise:()=>r,resetActivePromise:()=>{i.ended=!1,i.failed=!1,i.loading=!1,r=null},isEnded:()=>i.ended,isFailed:()=>i.failed,isLoading:()=>i.loading}},Dr=le("TinyTimeout"),kr=class{#hr=!1;#ur;#cr;#dr=null;#pr=new Map;constructor({cooldownWatcherTime:e=5e3,allowAutoConfigChange:t=!1}={}){if(!Number.isFinite(e)||e<=0)throw new TypeError("Expected 'cooldownWatcherTime' to be a positive number.");if("boolean"!=typeof t)throw new TypeError("Expected 'allowAutoConfigChange' to be a boolean.");this.#cr=e,this.#ur=t,this.setCooldownWatcherTime(e)}isDestroyed(){return this.#hr}getAllowAutoConfigChange(){return Dr(this.#hr),this.#ur}getCooldownWatcherTime(){return Dr(this.#hr),this.#cr}setAllowAutoConfigChange(e){if(Dr(this.#hr),"boolean"!=typeof e)throw new TypeError("Expected 'value' to be a boolean.");this.#ur=e}setCooldownWatcherTime(e){if(Dr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if(!Number.isFinite(e)||e<=0)throw new TypeError("Expected 'value' to be a positive number.");this.#cr=e,this.#dr&&clearInterval(this.#dr),this.#dr=setInterval(()=>{this.#pr.forEach(e=>{e.now>0&&e.now--})},this.#cr)}set(e,t,r,i=null){if(Dr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if("string"!=typeof e||""===e.trim())throw new TypeError("Expected 'id' to be a non-empty string.");if("function"!=typeof t)throw new TypeError("Expected 'callback' to be a function.");if(!Number.isFinite(r)||r<0)throw new TypeError("Expected 'value' to be a non-negative number.");if(null!==i&&(!Number.isFinite(i)||i<0))throw new TypeError("Expected 'limit' to be null or a non-negative number.");let s=this.#pr.get(e);(!s||this.#ur&&r!==s.value)&&(s={value:r,now:0},this.#pr.set(e,s));const n=s.value*s.now;return s.now++,setTimeout(t,"number"==typeof i?Math.min(n,i):n)}waitForTrue(e,t=100){if(Dr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if("function"!=typeof e)throw new TypeError("Expected 'getValue' to be a function.");if(null!==t&&(!Number.isFinite(t)||t<=0))throw new TypeError("Expected 'checkInterval' to be null or a positive number.");return Cr(e,t??this.#cr)}destroy(){this.#hr||(this.#dr&&clearInterval(this.#dr),this.#dr=null,this.#pr.clear(),this.#hr=!0)}},Mr=le("TinyLocalStorage"),Lr=new Map,Nr=new Map,_r=new Set(["string","boolean","object","array",String,Boolean,Number,Object,Array,BigInt,Symbol]),Pr=e().EventEmitter;class Rr extends Pr{static hasJsonType(e){return Lr.has(e)&&Nr.has(e)||_r.has(e)}static registerJsonType(e,t,r,i=!1){if(_r.has(e))throw new Error(`Cannot register type "${e}" because it is frozen.`);Lr.set(e,t),Nr.set(e,r),i&&_r.add(e)}static deleteJsonType(e){if(_r.has(e))throw new Error(`Cannot remove type "${e}" because it is frozen.`);let t=!1;return Lr.delete(e)&&(t=!0),Nr.delete(e)&&(t=!0),t}static encodeSpecialJson(e){if(void 0===e)return{__undefined__:!0};if(null===e)return{__null__:!0};for(const[t,r]of Lr.entries())if("string"!=typeof t&&e instanceof t||typeof e===t)return r(e,Rr.encodeSpecialJson);if(Array.isArray(e))return e.map(Rr.encodeSpecialJson);if(v(e)){const t={};for(const r in e)t[r]=Rr.encodeSpecialJson(e[r]);return t}return e}static decodeSpecialJson(e){const t=v(e);if(t){if(e.__undefined__)return;if(e.__null__)return null}if(Array.isArray(e))return e.map(Rr.decodeSpecialJson);if(t){for(const[t,r]of Nr.entries())if(r.check&&r.check(e))return r.decode(e,Rr.decodeSpecialJson);const t={};for(const r in e)t[r]=Rr.decodeSpecialJson(e[r]);return t}return e}#u=!1;get destroyed(){return this.#u}#mr=window.localStorage;#fr=null;#ee=0;#yr=e=>this.emit("storage",e);constructor(e){if(super(),void 0!==e&&"string"!=typeof e)throw new TypeError("TinyLocalStorage: dbName must be a string if provided.");"string"==typeof e&&(this.#fr=`LSDB::${e}`),window.addEventListener("storage",this.#yr)}#gr(e){if("string"==typeof e&&e.startsWith("LSDB::"))throw new Error(`TinyLocalStorage: Key "${e}" may conflict with reserved dbKeys.`)}updateStorageVersion(e,t){if(Mr(this.#u),"string"!=typeof this.#fr)throw new Error("TinyLocalStorage: Database key is not initialized. Set a valid dbName in the constructor.");if("number"!=typeof e||Number.isNaN(e)||e<1)throw new TypeError("TinyLocalStorage: version must be a positive number.");if("function"!=typeof t)throw new TypeError("TinyLocalStorage: onUpgrade must be a function.");const r=parseInt(localStorage.getItem(this.#fr),10)||0;if("number"!=typeof r||Number.isNaN(r)||r<0)throw new TypeError("TinyLocalStorage: saved version in localStorage is not a valid number.");if(e<r)throw new Error(`TinyLocalStorage: Cannot downgrade database version from ${r} to ${e}.`);e>r&&(t(r,e),localStorage.setItem(this.#fr,String(e)),this.#ee=e)}getDbKey(){return Mr(this.#u),this.#fr}getVersion(){return Mr(this.#u),this.#ee}setLocalStorage(e){if(Mr(this.#u),!(e instanceof Storage))throw new TypeError("Argument must be a valid instance of Storage.");this.#mr=e}localStorageExists(){return Mr(this.#u),this.#mr instanceof Storage}#wr(e,t){if("string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return Rr.encodeSpecialJson(t)}setJson(e,t){if(Mr(this.#u),this.#gr(e),!(v(t)||Array.isArray(t)||t instanceof Map||t instanceof Set))throw new TypeError("The storage value is not a valid JSON-compatible structure.");const r=this.#wr(e,t);return this.emit("setJson",e,t),this.#mr.setItem(e,JSON.stringify(r))}#br(e,t){if("string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");const r=this.#mr.getItem(e),i={obj:()=>({}),array:()=>[],map:()=>new Map,set:()=>new Set},s="function"==typeof i[t]?i[t]():null;let n;try{n=JSON.parse(r)}catch{return s}return{decoded:Rr.decodeSpecialJson(n),fallback:s}}getJson(e,t){Mr(this.#u);const{decoded:r,fallback:i}=this.#br(e,t);return r instanceof Map||r instanceof Set||Array.isArray(r)||v(r)?r:i}setDate(e,t){if(Mr(this.#u),this.#gr(e),!(t instanceof Date))throw new TypeError("Value must be a Date.");const r=this.#wr(e,t);return this.emit("setDate",e,t),this.#mr.setItem(e,JSON.stringify(r))}getDate(e){Mr(this.#u);const t=this.#br(e).decoded;return t instanceof Date?t:null}setRegExp(e,t){if(Mr(this.#u),this.#gr(e),!(t instanceof RegExp))throw new TypeError("Value must be a RegExp.");const r=this.#wr(e,t);return this.emit("setRegExp",e,t),this.#mr.setItem(e,JSON.stringify(r))}getRegExp(e){Mr(this.#u);const t=this.#br(e).decoded;return t instanceof RegExp?t:null}setBigInt(e,t){if(Mr(this.#u),this.#gr(e),"bigint"!=typeof t)throw new TypeError("Value must be a BigInt.");const r=this.#wr(e,t);return this.emit("setBigInt",e,t),this.#mr.setItem(e,JSON.stringify(r))}getBigInt(e){Mr(this.#u);const t=this.#br(e).decoded;return"bigint"==typeof t?t:null}setSymbol(e,t){if(Mr(this.#u),this.#gr(e),"symbol"!=typeof t)throw new TypeError("Value must be a Symbol.");const r=this.#wr(e,t);return this.emit("setSymbol",e,t),this.#mr.setItem(e,JSON.stringify(r))}getSymbol(e){Mr(this.#u);const t=this.#br(e).decoded;return"symbol"==typeof t?t:null}getValue(e){return Mr(this.#u),this.#br(e).decoded??null}setItem(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.emit("setItem",e,t),this.#mr.setItem(e,t)}getItem(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.#mr.getItem(e)}setString(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("string"!=typeof t)throw new TypeError("Value must be a string.");return this.emit("setString",e,t),this.#mr.setItem(e,JSON.stringify({__string__:!0,value:t}))}getString(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");let t=this.#mr.getItem(e);try{if(t=JSON.parse(t),!v(t)||!t.__string__||"string"!=typeof t.value)return null;t=t.value}catch{t=null}return"string"==typeof t?t:null}setNumber(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("number"!=typeof t)throw new TypeError("Value must be a number.");return this.emit("setNumber",e,t),this.#mr.setItem(e,String(t))}getNumber(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");let t=this.#mr.getItem(e);return"number"==typeof t||"string"==typeof t&&t.length>0&&(t=parseFloat(t),!Number.isNaN(t))?t:null}setBool(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("boolean"!=typeof t)throw new TypeError("Value must be a boolean.");return this.emit("setBool",e,t),this.#mr.setItem(e,String(t))}getBool(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");const t=this.#mr.getItem(e);if("boolean"==typeof t)return t;if("string"==typeof t){if("true"===t)return!0;if("false"===t)return!1}return null}removeItem(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.emit("removeItem",e),this.#mr.removeItem(e)}clearLocalStorage(){return Mr(this.#u),this.#mr.clear()}destroy(){this.#u||(window.removeEventListener("storage",this.#yr),this.removeAllListeners(),this.#u=!0)}}Rr.registerJsonType(Map,(e,t)=>({__map__:!0,data:Array.from(e.entries()).map(([e,r])=>[e,t(r)])}),{check:e=>e.__map__,decode:(e,t)=>new Map(e.data.map(([e,r])=>[e,t(r)]))},!0),Rr.registerJsonType(Set,(e,t)=>({__set__:!0,data:Array.from(e).map(t)}),{check:e=>e.__set__,decode:(e,t)=>new Set(e.data.map(t))},!0),Rr.registerJsonType(Date,e=>({__date__:!0,value:e.toISOString()}),{check:e=>e.__date__,decode:e=>new Date(e.value)},!0),Rr.registerJsonType(RegExp,e=>({__regexp__:!0,source:e.source,flags:e.flags}),{check:e=>e.__regexp__,decode:e=>new RegExp(e.source,e.flags)},!0),Rr.registerJsonType("number",e=>({__number__:!0,value:e.toString()}),{check:e=>e.__number__,decode:e=>Number(e.value)},!0),Rr.registerJsonType("bigint",e=>({__bigint__:!0,value:e.toString()}),{check:e=>e.__bigint__,decode:e=>BigInt(e.value)},!0),Rr.registerJsonType("symbol",e=>({__symbol__:!0,key:Symbol.keyFor(e)??e.description??null}),{check:e=>e.__symbol__,decode:e=>{const t=e.key;return null!=t?Symbol.for(t):Symbol()}},!0);const jr=Rr,Or=le("TinyIframeEvents"),$r=new WeakMap,Hr=e().EventEmitter,Fr=class extends Hr{#vr;get targetWindow(){return Or(this.#hr),this.#vr}#Er;get targetIframeElement(){return Or(this.#hr),this.#Er}#Tr;get targetOrigin(){return Or(this.#hr),this.#Tr}#Sr;get selfType(){return Or(this.#hr),this.#Sr}#hr=!1;#xr=!1;get ready(){return Or(this.#hr),this.#xr}onReady(e){Or(this.#hr),this.#xr?e():this.once(this.#Ar,e)}#Cr=null;#Ir=[];#Dr;#kr;#Ar;#Mr=null;constructor({targetIframe:e,targetOrigin:t=window.location.origin,secretEventName:r="__tinyIframeEvent__",handshakeEventName:i="__tinyIframeHandshake__",readyEventName:s="__tinyIframeReady__"}={}){if(super(),!(void 0===e||e instanceof HTMLIFrameElement&&e.contentWindow))throw new TypeError('[TinyIframeEvents] Invalid "targetIframe": expected HTMLIFrameElement, received '+typeof e);if("string"!=typeof t)throw new TypeError('[TinyIframeEvents] Invalid "targetOrigin": expected string, received '+typeof t);if(this.#Er=e,this.#vr=e?.contentWindow??window.parent,this.#Tr=t,this.#Sr=e?"parent":"iframe",this.#Dr=r,this.#kr=i,this.#Ar=s,$r.has(this.#vr))throw new Error("Duplicate window reference.");this._boundWindowMessage=this.#Lr.bind(this),this._boundPortMessage=this.#Nr.bind(this),this.#_r(),$r.set(this.#vr,this)}get secretEventName(){return Or(this.#hr),this.#Dr}set secretEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: secretEventName must be a string.");this.#Dr=e}get handshakeEventName(){return Or(this.#hr),this.#kr}set handshakeEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: handshakeEventName must be a string.");this.#kr=e}get readyEventName(){return Or(this.#hr),this.#Ar}set readyEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: readyEventName must be a string.");this.#Ar=e}#_r(){"parent"===this.#Sr?(this.#Mr=()=>{if(this.#hr)return;this.#Cr&&this.#Cr.close();const e=new MessageChannel;this.#Cr=e.port1,this.#Cr.onmessage=this._boundPortMessage,this.#xr=!1,this.#vr.postMessage({type:this.#kr},this.#Tr,[e.port2])},this.#Er&&(this.#Er.addEventListener("load",this.#Mr),this.#Mr())):window.addEventListener("message",this._boundWindowMessage,!1)}#Lr(e){const t=e.data,r=e.ports;v(t)&&t.type===this.#kr&&0!==r.length&&(this.#Cr=r[0],this.#Cr.onmessage=this._boundPortMessage,window.removeEventListener("message",this._boundWindowMessage),this.#Cr.postMessage({type:`${this.#kr}_ACK`}),this.#Pr())}#Nr(e){const t=e.data;if(v(t)&&t.type===`${this.#kr}_ACK`)return void this.#Pr();if(!v(t)||!t[this.#Dr])return;const r=t.eventName,i=t.payload,s=t.direction;"string"!=typeof r||"iframe"===this.#Sr&&"iframe"!==s||"parent"===this.#Sr&&"parent"!==s||this.emit(`win:${r}`,i,e)}#Pr(){this.#xr||(this.#xr=!0,this.#Rr(),this.emit(this.#Ar))}#Rr(){for(;this.#Ir.length>0;){const e=this.#Ir.shift();e&&this.#Cr&&this.#Cr.postMessage(e)}}winEmit(e,t){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("Event name must be a string.");if(this.#hr)throw new Error("Cannot emit: instance has been destroyed.");const r={[this.#Dr]:!0,eventName:e,payload:t,direction:"parent"===this.#Sr?"iframe":"parent"};this.#xr&&this.#Cr?this.#Cr.postMessage(r):this.#Ir.push(r)}isDestroyed(){return this.#hr}destroy(){this.#hr||(this.#xr=!1,window.removeEventListener("message",this._boundWindowMessage),this.#Er&&this.#Mr&&this.#Er.removeEventListener("load",this.#Mr),this.#Cr&&(this.#Cr.close(),this.#Cr=null),this.removeAllListeners(),this.#Ir=[],$r.delete(this.#vr),this.#hr=!0)}},zr=le("TinyNewWinEvents"),Br=new WeakMap,Wr=e().EventEmitter,qr=class extends Wr{#jr;#Tr;#Ir=[];#xr=!1;#Or=!1;#$r=null;#Ar="__TNE_READY__";#Hr="__TNE_ROUTE__";#u=!1;get destroyed(){return this.#u}get readyEventName(){return zr(this.#u),this.#Ar}set readyEventName(e){if(zr(this.#u),"string"!=typeof e)throw new TypeError("TinyNewWinEvents: readyEventName must be a string.");this.#Ar=e}get routeEventName(){return zr(this.#u),this.#Hr}set routeEventName(e){if(zr(this.#u),"string"!=typeof e)throw new TypeError("TinyNewWinEvents: routeEventName must be a string.");this.#Hr=e}constructor({targetOrigin:e,url:t,name:r,features:i}={}){if(super(),"string"==typeof r&&"_blank"===r)throw new Error('TinyNewWinEvents: The window name "_blank" is not supported. Please use a custom name to allow tracking.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('TinyNewWinEvents: The "targetOrigin" option must be a string.');if(void 0!==t&&"string"!=typeof t)throw new TypeError('TinyNewWinEvents: The "url" option must be a string.');if(void 0!==i&&"string"!=typeof i)throw new TypeError('TinyNewWinEvents: The "features" option must be a string if provided.');if(void 0===t?this.#jr=window.opener:(this.#jr="string"==typeof t?window.open(t,r,i):t,this.#Or=!0),!this.#jr||Br.has(this.#jr))throw new Error("Invalid or duplicate window reference.");this.#Tr=e??window.location.origin,this._handleMessage=this.#Fr.bind(this),window.addEventListener("message",this._handleMessage,!1),this.#Or||(this.#zr(this.#Ar,null),this.#Br())}getWin(){return zr(this.#u),this.#jr}#Fr(e){if(!e.source||this.#jr&&e.source!==this.#jr)return;const{type:t,route:r,payload:i}=e.data||{};if(t===this.#Ar)return this.#xr=!0,this.#Rr(),this.#Br(),void(this.#Or&&this.#zr(this.#Ar,null));t===this.#Hr&&this.emit(`win:${r}`,i,e)}#Rr(){for(;this.#Ir.length;){const e=this.#Ir.shift();if(e){const{route:t,payload:r}=e;this.winEmit(t,r)}}}#zr(e,t,r=""){this.#jr&&this.#jr.closed||this.#jr?.postMessage({type:e,route:r,payload:t},this.#Tr)}close(){if(zr(this.#u),!this.#Or)throw new Error("Only host can close the window.");this.#jr&&!this.#jr.closed&&this.#jr.close()}winEmit(e,t){if(zr(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");if(this.isDestroyed())throw new Error("Cannot emit: instance has been destroyed.");this.#xr?this.#zr(this.#Hr,t,e):this.#Ir.push({route:e,payload:t})}isConnected(){return zr(this.#u),!(!this.#xr||!this.#jr||this.#jr.closed)}#Br(){this.#jr&&!this.#$r&&(this.#$r=setInterval(()=>{this.#jr?.closed&&(this.emit("WINDOW_REF_CLOSED"),this.destroy())},500),Br.set(this.#jr,this.#$r))}onClose(e){zr(this.#u),this.on("WINDOW_REF_CLOSED",e)}offClose(e){zr(this.#u),this.off("WINDOW_REF_CLOSED",e)}isDestroyed(){return!this.#jr}destroy(){this.#jr&&(this.#$r&&(clearInterval(this.#$r),this.#$r=null,Br.delete(this.#jr)),window.removeEventListener("message",this._handleMessage),this.#Ir=[],this.#xr=!1,this.#jr=null,this.removeAllListeners(),this.#u=!0)}},Vr=class{#u=!1;get destroyed(){return this.#u}#Wr;#qr;#Vr;#Ur=0;#Kr=0;#Jr;#Gr=null;#Yr=null;get lineHeight(){return this.#Wr}get maxRows(){return this.#qr-1}get extraHeight(){return this.#Vr}get currentHeight(){return this.#Ur}get currentRows(){return this.#Kr}get textarea(){return this.#Jr}constructor(e,t={}){if(!(e instanceof HTMLTextAreaElement))throw new Error("TinyTextarea: Provided element is not a <textarea>.");if("object"!=typeof t||null===t)throw new TypeError("TinyTextarea: Options must be an object if provided.");if("maxRows"in t&&"number"!=typeof t.maxRows)throw new TypeError("TinyTextarea: `maxRows` must be a number.");if("extraHeight"in t&&"number"!=typeof t.extraHeight)throw new TypeError("TinyTextarea: `extraHeight` must be a number.");if("onResize"in t&&"function"!=typeof t.onResize)throw new TypeError("TinyTextarea: `onResize` must be a function.");if("onInput"in t&&"function"!=typeof t.onInput)throw new TypeError("TinyTextarea: `onInput` must be a function.");this.#Jr=e,this.#qr=(t.maxRows??5)+1,this.#Vr=t.extraHeight??0,this.#Gr=t.onResize??null,this.#Yr=t.onInput??null,this.#Wr=this.#Xr(),e.style.overflowY="hidden",e.style.resize="none",this._handleInput=()=>this.#Qr(),e.addEventListener("input",this._handleInput),this.#Qr()}#Qr(){this.#Jr.style.height="auto";const e=window.getComputedStyle(this.#Jr),t=parseFloat(e.paddingTop)||0,r=parseFloat(e.paddingBottom)||0,i=(this.#Jr.value.match(/\n/g)||[]).length,s=this.#Jr.scrollHeight,n=this.#Wr*this.#qr,o=Math.ceil(Math.min(s,n)-t-r+this.#Vr),a=this.#qr-1,l=i<a?i+1:a;this.#Jr.style.height=`${o}px`,this.#Jr.style.overflowY=s>n?"auto":"hidden",this.#Ur=o;const h={breakLines:i,rows:l,height:o,scrollHeight:s,maxHeight:n,lineHeight:this.#Wr,maxRows:a};l!==this.#Kr&&(this.#Kr=l,"function"==typeof this.#Gr&&this.#Gr({...h})),"function"==typeof this.#Yr&&this.#Yr(h)}#Xr(){const e=window.getComputedStyle(this.#Jr),t=parseFloat(e.lineHeight);return Number.isNaN(t)?1.2*parseFloat(e.fontSize):t}getData(){return{rows:this.#Kr,height:this.#Ur}}refresh(){this.#Qr()}destroy(){this.destroyed||(this.#Jr.removeEventListener("input",this._handleInput),this.#u=!0)}},Ur=le("TinyGamepad");class Kr{#hr=!1;#Zr=new Set;#ei=new Map;#ti=new Map;#ri=null;#ii=[];#si={};#ni=[];#oi=null;#ai=null;#li;#hi;#ui;#ci;#di;#pi;#mi;#fi;#yi=[];#gi=0;#wi=0;#bi=[];#vi=0;#Ei=null;#Ti=new Set;#Si=new Set;#xi=new Map;#Ai=new Map;#Ci=new Map;static#Ii={" ":"Space","\n":"Enter","\r":"Enter","\t":"Tab","-":"Minus",_:"Minus","=":"Equal","+":"Equal","[":"BracketLeft","{":"BracketLeft","]":"BracketRight","}":"BracketRight","\\":"Backslash","|":"Backslash",";":"Semicolon",":":"Semicolon","'":"Quote",'"':"Quote",",":"Comma","<":"Comma",".":"Period",">":"Period","/":"Slash","?":"Slash","`":"Backquote","~":"Backquote"};static addSpecialKey(e,t){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);if("string"!=typeof t)throw new TypeError("Invalid code type: expected string, got "+typeof t);Kr.#Ii[e]=t}static removeSpecialKey(e){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);delete Kr.#Ii[e]}static getSpecialKey(e){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);return Kr.#Ii[e]}static getAllSpecialKeys(){return{...Kr.#Ii}}static stringToKeys(e){if("string"!=typeof e)throw new TypeError("Invalid text type: expected string, got "+typeof e);if(!e.length)throw new Error("Invalid text: cannot be empty");return Array.from(e).map(e=>{const t=e.toUpperCase();if(t>="A"&&t<="Z")return`Key${t}`;if(t>="0"&&t<="9")return`Digit${t}`;const r=Kr.#Ii[e];if(void 0!==r)return r;throw new Error(`Unsupported character: "${e}"`)})}constructor({expectedId:e=null,inputMode:t="both",ignoreIds:r=[],deadZone:i=.1,axisActiveSensitivity:s=.3,timeoutComboKeys:n=500,allowMouse:o=!1,elementBase:a=window}={}){if(null!==e&&"string"!=typeof e)throw new TypeError('"expectedId" must be a string or null, received: '+typeof e);if(!["keyboard-only","gamepad-only","both"].includes(t))throw new TypeError(`"inputMode" must be 'keyboard-only', 'gamepad-only', or 'both', received: ${t}`);if(!Array.isArray(r)||!r.every(e=>"string"==typeof e))throw new TypeError('"ignoreIds" must be an array of strings');if("number"!=typeof i||i<0||i>1)throw new RangeError(`"deadZone" must be a number between 0 and 1, received: ${i}`);if("number"!=typeof s||s<0||s>1)throw new RangeError(`"axisActiveSensitivity" must be a number between 0 and 1, received: ${s}`);if("number"!=typeof n||n<0)throw new RangeError(`"timeoutComboKeys" must be a positive number, received: ${n}`);if("boolean"!=typeof o)throw new TypeError('"allowMouse" must be a boolean, received: '+typeof o);if(!(a instanceof Window||a instanceof Element))throw new TypeError('"elementBase" must be a Window or Element instance');this.#ci=e,this.#li=t,this.#hi=new Set(r),this.#ui=i,this.#di=o,this.#pi=a,this.#mi=n,this.#fi=s,["gamepad-only","both"].includes(this.#li)&&this.#Di(),["keyboard-only","both"].includes(this.#li)&&this.#ki()}#Mi=e=>this.#Li(e.gamepad);#Ni=e=>this.#_i(e.gamepad);#Di(){window.addEventListener("gamepadconnected",this.#Mi),window.addEventListener("gamepaddisconnected",this.#Ni)}#Li(e){this.#hr||this.#hi.has(e.id)||this.#ci&&e.id!==this.#ci||this.#ri||(this.#ri=e,this.#ci=e.id,this.#Pi(),this.#Ri("connected",{id:e.id,gp:e,timestamp:e.timestamp}))}#_i(e){this.#hr||this.#ri&&e.id===this.#ri.id&&(this.#ri=null,this.#oi&&(cancelAnimationFrame(this.#oi),this.#oi=null),this.#Ri("disconnected",{id:e.id,gp:e,timestamp:e.timestamp}))}#Pi(){const e=()=>{this.#hr||(this.#ji(),this.#oi=requestAnimationFrame(e))};e()}#ji(){if(this.#hr)return;const e=navigator.getGamepads(),t=Array.from(e).find(e=>e&&e.id===this.#ci);t&&(this.#ri=t,t.buttons.forEach((e,r)=>{const i=`Button${r}`,s=this.#ii[r]?.pressed||!1;let n,o,a=!1;e.pressed&&!s?(o=1,n="down"):!e.pressed&&s?(o=0,n="up"):e.pressed&&s&&(o=1,n="hold"),e.pressed&&e.value>0&&e.value<1&&1!==e.value&&(o=e.value,a=!0),"number"==typeof o&&"string"==typeof n&&this.#Oi({key:i,source:"gamepad-button",value:o,value2:NaN,type:n,gp:t,isPressure:a,pressed:e.pressed,prevPressed:s,timestamp:t.timestamp,id:t.id}),this.#ii[r]={pressed:e.pressed,value:"number"==typeof o?o:this.#ii[r]?.value,value2:NaN}}),t.axes.forEach((e,r)=>{Math.abs(e)<this.#ui&&(e=0);const i=`Axis${r}`;e!==(this.#ni[r]??0)&&this.#Oi({key:i,source:"gamepad-analog",value:e,value2:NaN,type:"change",timestamp:t.timestamp,id:t.id,gp:t}),this.#ni[r]=e}))}#$i=e=>{if(!this.#hr){if(!(e instanceof KeyboardEvent))throw new Error("Expected KeyboardEvent in keydown listener.");this.#Zr.has(e.code)||(this.#Zr.add(e.code),this.#Oi({event:e,key:e.code,source:"keyboard",value:1,value2:NaN,type:"down",pressed:!0,prevPressed:this.#si[e.code]?.pressed??!1,id:"native_keyboard",timestamp:e.timeStamp}),this.#si[e.code]={pressed:!0})}};#Hi=e=>{if(!this.#hr){if(!(e instanceof KeyboardEvent))throw new Error("Expected KeyboardEvent in keyup listener.");this.#Zr.has(e.code)&&(this.#Zr.delete(e.code),this.#Oi({event:e,key:e.code,source:"keyboard",value:0,value2:NaN,type:"up",pressed:!1,prevPressed:this.#si[e.code]?.pressed??!1,id:"native_keyboard",timestamp:e.timeStamp}),this.#si[e.code]={pressed:!1})}};#Fi=e=>{if(this.#hr)return;if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mousedown listener.");const t=`Mouse${e.button}`;this.#Zr.add(t),this.#Oi({event:e,key:t,source:"mouse",value:1,value2:NaN,type:"down",pressed:!0,prevPressed:this.#si[t]?.pressed??!1,id:"native_mouse",timestamp:e.timeStamp}),this.#si[t]={pressed:!0}};#zi=e=>{if(this.#hr)return;if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mouseup listener.");const t=`Mouse${e.button}`;this.#Zr.delete(t),this.#Oi({event:e,key:t,source:"mouse",value:0,value2:NaN,type:"up",pressed:!1,prevPressed:this.#si[t]?.pressed??!1,id:"native_mouse",timestamp:e.timeStamp}),this.#si[t]={pressed:!1}};#Bi=e=>{if(!this.#hr){if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mousemove listener.");if(0!==e.movementX||0!==e.movementY){const t="MouseMove",r=this.#si[t]??{pressed:!1,value:0,value2:0};this.#Oi({event:e,key:t,source:"mouse",value:e.movementX+(r.value??0),value2:e.movementY+(r.value??0),id:"native_mouse",type:"move",pressed:!0,prevPressed:null,timestamp:e.timeStamp}),this.#si[t]={pressed:!1,value:e.movementX,value2:e.movementY}}}};#ki(){this.#pi.addEventListener("keydown",this.#$i),this.#pi.addEventListener("keyup",this.#Hi),this.#di&&(this.#pi.addEventListener("mousedown",this.#Fi),this.#pi.addEventListener("mouseup",this.#zi),this.#pi.addEventListener("mousemove",this.#Bi));const e=()=>{this.#hr||(this.#Zr.forEach(e=>{const t=e.startsWith("Mouse")?"mouse":"keyboard";this.#Oi({key:e,source:t,id:`native_${t}`,value:1,value2:NaN,type:"hold",pressed:!0,prevPressed:this.#si[e]?.pressed??!1,timestamp:NaN})}),this.#ai=requestAnimationFrame(e))};e()}#Oi(e){if(this.#hr)return;const t=this.#ti.get("input-*")||[],{pressed:r,key:i}=e,s=i.startsWith("Axis"),n="boolean"==typeof r&&r||s&&(e.value>this.#fi||e.value<-Math.abs(this.#fi)),o=s?`${i}${e.value>0?"+":e.value<0?"-":""}`:i;let a=null;if("move"!==e.type&&"hold"!==e.type){if(n){if(!s&&!this.#Ti.has(i)||s&&!this.#Ti.has(i)&&!this.#Ti.has(`${i}+`)&&!this.#Ti.has(`${i}-`)){0===this.#vi&&(this.#vi=Date.now()),this.#Ti.add(o),a=!0,this.#bi.push(o),this.#yi.length<1&&(this.#Ei&&clearTimeout(this.#Ei),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#mi));const e=this.#ti.get("mapped-key-start")??[];for(const t of e)t({key:o,activeTime:this.#vi})}}else if(!s&&this.#Ti.has(i)||s&&(this.#Ti.has(i)||this.#Ti.has(`${i}+`)||this.#Ti.has(`${i}-`))){this.#Ti.delete(i),this.#Ti.delete(`${i}+`),this.#Ti.delete(`${i}-`),a=!1;const e=this.#ti.get("mapped-key-end")??[];for(const t of e)t({key:o,activeTime:this.#vi})}for(const{sequence:e,callback:t,triggered:r}of this.#Ai.values()){const i=this.#Ai.get(e.join("+"));if(!i)continue;const s=e.every((e,t)=>this.#bi[t]===e);s&&!r?(i.triggered=!0,t(this.#vi)):!s&&r&&(i.triggered=!1)}}for(const[r,l]of this.#ei.entries()){const h=e=>"string"==typeof l&&e===l||Array.isArray(l)&&l.findIndex((t,r)=>e===l[r])>-1,u=h(o),c=s&&h(`${i}+`),d=s&&h(`${i}-`);if(u||c||d){if(n&&u){if(a||!this.#Si.has(r)){0===this.#wi&&(this.#wi=Date.now()),this.#Si.add(r),0===this.#gi&&(this.#gi=Date.now()),this.#Ei&&clearTimeout(this.#Ei),this.#yi.push(r),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#mi);const e=this.#ti.get("mapped-input-start")??[];for(const t of e)t({logicalName:r,activeTime:this.#wi,comboTime:this.#gi})}}else if(!a||this.#Si.has(r)){this.#Si.delete(r),this.#Si.size<1&&(this.#wi=0);const e=this.#ti.get("mapped-input-end")??[];for(const t of e)t({logicalName:r,activeTime:this.#wi,comboTime:this.#gi})}for(const{sequence:e,callback:t,triggered:r}of this.#xi.values()){const i=this.#xi.get(e.join("+"));if(!i)continue;const s=Array.from(this.#Si),n=e.every((e,t)=>s[t]===e);n&&!r?(i.triggered=!0,t(this.#wi)):!n&&r&&(i.triggered=!1)}}const p=[];if(s&&0===e.value){const{value:t}=this.#Ci.get(`${i}-`)??{value:0,value2:NaN},{value:r}=this.#Ci.get(`${i}+`)??{value:0,value2:NaN};e.value!==t&&p.push(`${i}-`),e.value!==r&&p.push(`${i}+`)}else p.push(o);p.forEach(i=>{if(!("*"===l||l===i||Array.isArray(l)&&l.includes(i)))return;const s=this.#ti.get(`input-${e.type}-${r}`)||[],n=this.#ti.get(`input-${r}`)||[];if(n.length<1&&s.length<1&&t.length<1)return;const o={...e,key:i,logicalName:r};for(const e of t)e(o);for(const e of n)e(o);for(const e of s)e(o);this.#Ci.set(i,{value:e.value,value2:e.value2})})}}#Ri(e,t){const r=this.#ti.get(e)||[];for(const e of r)e(t)}#Wi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e);let s=this.#ti.get(i);Array.isArray(s)||(s=[],this.#ti.set(i,s)),s.push(t)}#qi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=s=>{this.#Vi(e,i,r),t(s)};this.#Wi(e,i,r)}#Ui(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e),s=this.#ti.get(i)??[];s.unshift(t),this.#ti.set(i,s)}#Vi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e),s=this.#ti.get(i);Array.isArray(s)&&this.#ti.set(i,s.filter(e=>e!==t))}awaitInputMapping({timeout:e=1e4,eventName:t="MappingInput",canMove:r=!1}={}){return Ur(this.#hr),new Promise((i,s)=>{if("number"!=typeof e||Number.isNaN(e)||e<0)return s(new TypeError(`Invalid "timeout": expected a positive number, got ${e}`));if("string"!=typeof t||!t.trim())return s(new TypeError(`Invalid "eventName": expected a non-empty string, got ${t}`));if("boolean"!=typeof r)return s(new TypeError(`Invalid "canMove": expected a boolean, got ${r}`));const n={key:null,source:null},o=({key:e,type:s,source:l,gp:h,value:u})=>{(r||"move"!==s)&&(n.key=e,n.source=l,n.gp=h,clearTimeout(a),this.offInputStart(t,o),this.offInputChange(t,o),r&&this.offInputMove(t,o),i(n))},a=setTimeout(()=>i(n),e);this.mapInput(t,"*"),this.onInputStart(t,o),this.onInputChange(t,o),r&&this.onInputMove(t,o)})}mapInput(e,t){if(Ur(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError(`Invalid "physicalInput": expected string or array of strings, got ${JSON.stringify(t)}`);this.#ei.set(e,t)}unmapInput(e){if(Ur(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);this.#ei.delete(e)}hasMappedInput(e){if(Ur(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);return this.#ei.has(e)}getMappedInput(e){if(Ur(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);const t=this.#ei.get(e);if(!t)throw new Error(`No physical input mapped for logicalName: "${e}"`);return t}clearMapInputs(){Ur(this.#hr),this.#ei.clear()}registerInputSequence(e,t){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);if("function"!=typeof t)throw new TypeError("'callback' must be a function, got: "+typeof t);if(0===e.length)throw new Error("'sequence' must contain at least one input name.");const r=e.join("+");this.#xi.set(r,{sequence:e,callback:t,triggered:!1})}unregisterInputSequence(e){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");this.#xi.delete(t)}unregisterAllInputSequences(){Ur(this.#hr),this.#xi.clear()}hasInputSequence(e){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");return this.#xi.has(t)}registerKeySequence(e,t){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);if("function"!=typeof t)throw new TypeError("'callback' must be a function, got: "+typeof t);if(0===e.length)throw new Error("'sequence' must contain at least one input name.");const r=e.join("+");this.#Ai.set(r,{sequence:e,callback:t,triggered:!1})}unregisterKeySequence(e){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");this.#Ai.delete(t)}unregisterAllKeySequences(){Ur(this.#hr),this.#Ai.clear()}hasKeySequence(e){if(Ur(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");return this.#Ai.has(t)}renewComboMapped(){Ur(this.#hr),this.#Ei&&(clearTimeout(this.#Ei),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#mi))}resetComboMapped(){Ur(this.#hr),this.#Ei&&clearTimeout(this.#Ei),this.#bi=[],this.#Ei=null,this.#vi=0,this.#yi=[],this.#gi=0}onMappedKeyStart(e){return Ur(this.#hr),this.#Wi("",e,"mapped-key-start")}onceMappedKeyStart(e){return Ur(this.#hr),this.#qi("",e,"mapped-key-start")}prependMappedKeyStart(e){return Ur(this.#hr),this.#Ui("",e,"mapped-key-start")}offMappedKeyStart(e){return Ur(this.#hr),this.#Vi("",e,"mapped-key-start")}offAllMappedKeyStart(){Ur(this.#hr),this.#ti.delete("mapped-key-start")}onMappedKeyEnd(e){return Ur(this.#hr),this.#Wi("",e,"mapped-key-end")}onceMappedKeyEnd(e){return Ur(this.#hr),this.#qi("",e,"mapped-key-end")}prependMappedKeyEnd(e){return Ur(this.#hr),this.#Ui("",e,"mapped-key-end")}offMappedKeyEnd(e){return Ur(this.#hr),this.#Vi("",e,"mapped-key-end")}offAllMappedKeyEnd(){Ur(this.#hr),this.#ti.delete("mapped-key-end")}onMappedInputStart(e){return Ur(this.#hr),this.#Wi("",e,"mapped-input-start")}onceMappedInputStart(e){return Ur(this.#hr),this.#qi("",e,"mapped-input-start")}prependMappedInputStart(e){return Ur(this.#hr),this.#Ui("",e,"mapped-input-start")}offMappedInputStart(e){return Ur(this.#hr),this.#Vi("",e,"mapped-input-start")}offAllMappedInputStart(){Ur(this.#hr),this.#ti.delete("mapped-input-start")}onMappedInputEnd(e){return Ur(this.#hr),this.#Wi("",e,"mapped-input-end")}onceMappedInputEnd(e){return Ur(this.#hr),this.#qi("",e,"mapped-input-end")}prependMappedInputEnd(e){return Ur(this.#hr),this.#Ui("",e,"mapped-input-end")}offMappedInputEnd(e){return Ur(this.#hr),this.#Vi("",e,"mapped-input-end")}offAllMappedInputEnd(){Ur(this.#hr),this.#ti.delete("mapped-input-end")}onInput(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-{logicalName}")}onceInput(e,t){return Ur(this.#hr),this.#qi(e,t,"input-{logicalName}")}prependInput(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-{logicalName}")}offInput(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-{logicalName}")}onInputStart(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-down-{logicalName}")}onceInputStart(e,t){return Ur(this.#hr),this.#qi(e,t,"input-down-{logicalName}")}prependInputStart(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-down-{logicalName}")}offInputStart(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-down-{logicalName}")}onInputEnd(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-up-{logicalName}")}onceInputEnd(e,t){return Ur(this.#hr),this.#qi(e,t,"input-up-{logicalName}")}prependInputEnd(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-up-{logicalName}")}offInputEnd(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-up-{logicalName}")}onInputHold(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-hold-{logicalName}")}onceInputHold(e,t){return Ur(this.#hr),this.#qi(e,t,"input-hold-{logicalName}")}prependInputHold(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-hold-{logicalName}")}offInputHold(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-hold-{logicalName}")}onInputChange(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-change-{logicalName}")}onceInputChange(e,t){return Ur(this.#hr),this.#qi(e,t,"input-change-{logicalName}")}prependInputChange(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-change-{logicalName}")}offInputChange(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-change-{logicalName}")}onInputMove(e,t){return Ur(this.#hr),this.#Wi(e,t,"input-move-{logicalName}")}onceInputMove(e,t){return Ur(this.#hr),this.#qi(e,t,"input-move-{logicalName}")}prependInputMove(e,t){return Ur(this.#hr),this.#Ui(e,t,"input-move-{logicalName}")}offInputMove(e,t){return Ur(this.#hr),this.#Vi(e,t,"input-move-{logicalName}")}getCalls(e,t="all"){if(Ur(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i=`${{all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t]}${e}`,s=this.#ti.get(i);return Array.isArray(s)?[...s]:[]}offAllInputs(e,t="all"){if(Ur(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i={all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t];i&&this.#ti.delete(`${i}${e}`)}getCallSize(e,t="all"){if(Ur(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i={all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t],s=this.#ti.get(`${i}${e}`);return Array.isArray(s)?s.length:0}#Ki={type:"dual-rumble",params:{startDelay:0,duration:200,weakMagnitude:.5,strongMagnitude:1}};get defaultHapticEffect(){return Ur(this.#hr),{type:this.#Ki.type,params:{...this.#Ki.params}}}setDefaultHapticEffect(e,t){if(Ur(this.#hr),"string"!=typeof e)throw new TypeError(`"type" must be a valid GamepadHapticEffectType string, received ${e}`);if("object"!=typeof t||null===t)throw new TypeError(`"params" must be a non-null object, received ${t}`);this.#Ki.type=e,this.#Ki.params=t}hasHapticEffect(){Ur(this.#hr);const e=this.#ri;return!!e&&e.vibrationActuator instanceof GamepadHapticActuator}vibrate(e,t){if(Ur(this.#hr),void 0!==e&&("object"!=typeof e||null===e))throw new TypeError(`"params" must be an object if provided, received ${e}`);if(void 0!==t&&"string"!=typeof t)throw new TypeError(`"type" must be a valid GamepadHapticEffectType string if provided, received ${t}`);const r=this.#ri;if(!r)return new Promise(e=>e("complete"));const i=r.vibrationActuator;return i instanceof GamepadHapticActuator?i.playEffect(t??this.#Ki.type,{...this.#Ki.params,...e}):new Promise(e=>e("complete"))}ignoreId(e){if(Ur(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"id" must be a non-empty string, received ${e}`);this.#hi.add(e)}unignoreId(e){if(Ur(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"id" must be a non-empty string, received ${e}`);this.#hi.delete(e)}onConnected(e){return Ur(this.#hr),this.#Wi("",e,"connected")}onceConnected(e){return Ur(this.#hr),this.#qi("",e,"connected")}prependConnected(e){return Ur(this.#hr),this.#Ui("",e,"connected")}offConnected(e){return Ur(this.#hr),this.#Vi("",e,"connected")}offAllConnected(){Ur(this.#hr),this.#ti.delete("connected")}onDisconnected(e){return Ur(this.#hr),this.#Wi("",e,"disconnected")}onceDisconnected(e){return Ur(this.#hr),this.#qi("",e,"disconnected")}prependDisconnected(e){return Ur(this.#hr),this.#Ui("",e,"disconnected")}offDisconnected(e){return Ur(this.#hr),this.#Vi("",e,"disconnected")}offAllDisconnected(){Ur(this.#hr),this.#ti.delete("disconnected")}hasGamepad(){return Ur(this.#hr),this.#ri instanceof Gamepad}getGamepad(){if(Ur(this.#hr),!this.#ri)throw new Error("No gamepad is currently connected.");return this.#ri}hasLastButtonState(e){return Ur(this.#hr),!!this.#ii[e]}getLastButtonState(e){if(Ur(this.#hr),!this.#ii[e])throw new Error(`No last button state found for index ${e}`);return{...this.#ii[e]}}exportConfig(){return Ur(this.#hr),{expectedId:this.#ci,ignoreIds:Array.from(this.#hi),deadZone:this.#ui,timeoutComboKeys:this.#mi,axisActiveSensitivity:this.#fi,inputMap:Array.from(this.#ei.entries())}}importConfig(e){if(Ur(this.#hr),"string"!=typeof e&&("object"!=typeof e||null===e))throw new TypeError(`"json" must be a string or a non-null object, received: ${e}`);const t="string"==typeof e?JSON.parse(e):e;if(void 0!==t.expectedId&&"string"!=typeof t.expectedId&&null!==t.expectedId)throw new TypeError('"expectedId" must be a string or null if provided');if(void 0!==t.ignoreIds&&!Array.isArray(t.ignoreIds))throw new TypeError('"ignoreIds" must be an array if provided');if(void 0!==t.deadZone&&"number"!=typeof t.deadZone)throw new TypeError('"deadZone" must be a number if provided');if(void 0!==t.timeoutComboKeys&&"number"!=typeof t.timeoutComboKeys)throw new TypeError('"timeoutComboKeys" must be a number if provided');if(void 0!==t.axisActiveSensitivity&&"number"!=typeof t.axisActiveSensitivity)throw new TypeError('"axisActiveSensitivity" must be a number if provided');if(void 0!==t.inputMap&&!Array.isArray(t.inputMap))throw new TypeError('"inputMap" must be an array if provided');void 0!==t.expectedId&&(this.#ci=t.expectedId),Array.isArray(t.ignoreIds)&&(this.#hi=new Set(t.ignoreIds)),"number"==typeof t.deadZone&&(this.#ui=t.deadZone),"number"==typeof t.timeoutComboKeys&&(this.#mi=t.timeoutComboKeys),"number"==typeof t.axisActiveSensitivity&&(this.#fi=t.axisActiveSensitivity),Array.isArray(t.inputMap)&&(this.#ei=new Map(t.inputMap))}get mappedKeyStartCalls(){Ur(this.#hr);const e=this.#ti.get("mapped-key-start");return Array.isArray(e)?[...e]:[]}get mappedKeyEndCalls(){Ur(this.#hr);const e=this.#ti.get("mapped-key-end");return Array.isArray(e)?[...e]:[]}get comboMappedKeys(){return Ur(this.#hr),[...this.#bi]}get comboMappedInputs(){return Ur(this.#hr),[...this.#yi]}get keySequenceSize(){return Ur(this.#hr),this.#Ai.size}get keySequences(){Ur(this.#hr);const e=[];for(const[,t]of this.#Ai.entries())e.push(t.callback);return e}get activeMappedKeys(){return Ur(this.#hr),[...this.#Ti]}get mappedInputStartCalls(){Ur(this.#hr);const e=this.#ti.get("mapped-input-start");return Array.isArray(e)?[...e]:[]}get mappedInputEndCalls(){Ur(this.#hr);const e=this.#ti.get("mapped-input-end");return Array.isArray(e)?[...e]:[]}get inputSequenceSize(){return Ur(this.#hr),this.#xi.size}get inputSequences(){Ur(this.#hr);const e=[];for(const[,t]of this.#xi.entries())e.push(t.callback);return e}get activeMappedInputs(){return Ur(this.#hr),[...this.#Si]}get mappedInputs(){Ur(this.#hr);const e={};for(const[t,r]of this.#ei.entries())e[t]=r;return e}get mappedInputSize(){return Ur(this.#hr),this.#ei.size}get connectedCalls(){Ur(this.#hr);const e=this.#ti.get("connected");return Array.isArray(e)?[...e]:[]}get disconnectedCalls(){Ur(this.#hr);const e=this.#ti.get("disconnected");return Array.isArray(e)?[...e]:[]}get ignoredDeviceIds(){return Ur(this.#hr),[...this.#hi]}get heldKeys(){return Ur(this.#hr),[...this.#Zr]}get eventsSize(){Ur(this.#hr);let e=0;return this.#ti.forEach(t=>{e+=t.length}),e}get callSize(){return Ur(this.#hr),this.#ti.size}get connectedCallSize(){Ur(this.#hr);const e=this.#ti.get("connected");return Array.isArray(e)?e.length:0}get disconnectedCallSize(){Ur(this.#hr);const e=this.#ti.get("disconnected");return Array.isArray(e)?e.length:0}get mappedKeyStartCallSize(){Ur(this.#hr);const e=this.#ti.get("mapped-key-start");return Array.isArray(e)?e.length:0}get mappedKeyEndCallSize(){Ur(this.#hr);const e=this.#ti.get("mapped-key-end");return Array.isArray(e)?e.length:0}get mappedInputStartCallSize(){Ur(this.#hr);const e=this.#ti.get("mapped-input-start");return Array.isArray(e)?e.length:0}get mappedInputEndCallSize(){Ur(this.#hr);const e=this.#ti.get("mapped-input-end");return Array.isArray(e)?e.length:0}get lastButtonStates(){Ur(this.#hr);const e=[];return this.#ii.forEach(t=>{e.push({...t})}),e}get lastAxes(){return Ur(this.#hr),[...this.#ni]}get inputMode(){return Ur(this.#hr),this.#li}get elementBase(){return Ur(this.#hr),this.#pi}get timeComboInputs(){return Ur(this.#hr),this.#gi}get timeComboKeys(){return Ur(this.#hr),this.#vi}get timeMappedInputs(){return Ur(this.#hr),this.#wi}get timeoutComboKeys(){return Ur(this.#hr),this.#mi}set timeoutComboKeys(e){if(Ur(this.#hr),"number"!=typeof e||e<0||!Number.isFinite(e))throw new TypeError("Timeout combo keys must be a non-negative finite number.");this.#mi=e}get axisActiveSensitivity(){return Ur(this.#hr),this.#fi}set axisActiveSensitivity(e){if(Ur(this.#hr),"number"!=typeof e||e<0||e>1)throw new RangeError("Axis sensitivity must be a number between 0 and 1.");this.#fi=e}get deadZone(){return Ur(this.#hr),this.#ui}set deadZone(e){if(Ur(this.#hr),"number"!=typeof e||e<0||e>1)throw new RangeError("Dead zone must be a number between 0 and 1.");this.#ui=e}get expectedId(){return Ur(this.#hr),this.#ci}set expectedId(e){if(Ur(this.#hr),"string"!=typeof e)throw new TypeError("Expected device id be a string.");this.#ci=e}get isDestroyed(){return this.#hr}destroy(){this.#hr||(this.#oi&&cancelAnimationFrame(this.#oi),this.#ai&&cancelAnimationFrame(this.#ai),this.#oi=null,this.#ai=null,["keyboard-only","both"].includes(this.#li)&&(this.#pi.removeEventListener("keydown",this.#$i),this.#pi.removeEventListener("keyup",this.#Hi),this.#di&&(this.#pi.removeEventListener("mousedown",this.#Fi),this.#pi.removeEventListener("mouseup",this.#zi),this.#pi.removeEventListener("mousemove",this.#Bi))),["gamepad-only","both"].includes(this.#li)&&(window.removeEventListener("gamepadconnected",this.#Mi),window.removeEventListener("gamepaddisconnected",this.#Ni)),this.resetComboMapped(),this.#ei.clear(),this.#ti.clear(),this.#Zr.clear(),this.#Si.clear(),this.#Ti.clear(),this.#xi.clear(),this.#Ai.clear(),this.#hi.clear(),this.#Ci.clear(),this.#ii=[],this.#ni=[],this.#si={},this.#ri=null,this.#ci=null,this.#di=!1,this.#wi=0,this.#hr=!0)}}const Jr=Kr,Gr=le("TinyDayNightCycle"),Yr=class{#Ji=!0;#Gi=86400;#Yi=3600;#Xi=60;#Qi=new Map;#Zi=[];#es;#ts;#rs={main:null};#is=0;#ss=0;#ns=0;#os="";#as=1;#ls=1;#hs=1;#hr=!1;#us=[31,31,31,31,31,31,31,31,31,31,31,31];#cs={default:{},day:{},night:{},hours:{},seasons:{}};#ds={min:60,max:180};#ps=0;get daySize(){return Gr(this.#hr),this.#Gi}get autoSizeAdjuste(){return Gr(this.#hr),this.#Ji}set autoSizeAdjuste(e){if(Gr(this.#hr),"boolean"!=typeof e)throw new TypeError("autoSizeAdjuste must be a boolean.");this.#Ji=e}set daySize(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("daySize must be a positive finite number.");const t=this.#Yi/this.#Gi,r=this.#Xi/this.#Gi;this.#Gi=e,this.#Ji&&(this.#Yi=e*t,this.#Xi=e*r)}get hourSize(){return Gr(this.#hr),this.#Yi}set hourSize(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("hourSize must be a positive finite number.");const t=this.#Gi/this.#Yi,r=this.#Xi/this.#Yi;this.#Yi=e,this.#Ji&&(this.#Gi=e*t,this.#Xi=e*r)}get minuteSize(){return Gr(this.#hr),this.#Xi}set minuteSize(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("minuteSize must be a positive finite number.");const t=this.#Yi/this.#Xi,r=this.#Gi/this.#Xi;this.#Xi=e,this.#Ji&&(this.#Yi=e*t,this.#Gi=e*r)}get isDestroyed(){return this.#hr}get currentSeconds(){return Gr(this.#hr),this.#is}set currentSeconds(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentSeconds must be a finite number, received "+typeof e);if(e<0||e>=this.#Gi)throw new RangeError(`currentSeconds must be between 0 and 86399, received ${e}`);this.#is=Math.floor(e),this.#ss=Math.floor(e/this.#Xi),this.#ns=Math.floor(e/this.#Yi)}get currentMinutes(){return Gr(this.#hr),this.#ss}set currentMinutes(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentMinutes must be a finite number, received "+typeof e);if(e<0||e>=1440)throw new RangeError(`currentMinutes must be between 0 and 1439, received ${e}`);this.#ss=Math.floor(e),this.#ns=Math.floor(e/this.#Xi),this.#is=Math.floor(e*this.#Xi)}get currentHours(){return Gr(this.#hr),this.#ns}set currentHours(e){if(Gr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentHours must be a finite number, received "+typeof e);if(e<0||e>=24)throw new RangeError(`currentHours must be between 0 and less than 24, received ${e}`);this.#ns=Math.floor(e),this.#ss=Math.floor(e*this.#Xi),this.#is=Math.floor(e*this.#Yi)}get moons(){return Gr(this.#hr),this.#Zi.map(e=>this.getMoon(e))}get seasons(){return Gr(this.#hr),Array.from(this.#Qi.keys())}get dayStart(){return Gr(this.#hr),this.#es}get nightStart(){return Gr(this.#hr),this.#ts}get weather(){return Gr(this.#hr),{...this.#rs}}get currentSeason(){return Gr(this.#hr),this.#os}get currentDay(){return Gr(this.#hr),this.#as}get currentMonth(){return Gr(this.#hr),this.#ls}get currentYear(){return Gr(this.#hr),this.#hs}get monthDays(){return Gr(this.#hr),[...this.#us]}get weatherDuration(){return Gr(this.#hr),{...this.#ds}}get weatherTimeLeft(){return Gr(this.#hr),this.#ps}set dayStart(e){if(Gr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("dayStart must be a positive non-zero number, received "+typeof e);this.#es=e}set nightStart(e){if(Gr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("nightStart must be a positive non-zero number, received "+typeof e);this.#ts=e}set weather(e){if(Gr(this.#hr),"object"!=typeof e||null===e||Array.isArray(e)||!Object.values(e).every(e=>"string"==typeof e))throw new TypeError("weather must be a object with strings, received "+typeof e);this.#rs=e}set currentSeason(e){if(Gr(this.#hr),"string"!=typeof e||!this.#Qi.has(e))throw new TypeError(`currentSeason must be one of ${Array.from(this.#Qi).map(e=>e[0]).join(", ")}, received ${e}`);this.#os=e}set currentDay(e){if(Gr(this.#hr),"number"!=typeof e||e<1||e>this.#us[this.#ls-1])throw new TypeError("currentDay must be a valid day number, received "+typeof e);this.#as=e}set currentMonth(e){if(Gr(this.#hr),"number"!=typeof e||"number"!=typeof this.#us[e-1])throw new TypeError("currentMonth must be a valid month number, received "+typeof e);this.#ls=e}set currentYear(e){if(Gr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("currentYear must be a positive number non-zero, received "+typeof e);this.#hs=e}set monthDays(e){if(Gr(this.#hr),!Array.isArray(e))throw new TypeError("monthDays must be a array");if(!e.every(e=>"number"==typeof e))throw new TypeError("monthDays must have number values");this.#us=[...e]}set weatherDuration(e){if(Gr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("weatherDuration must be a non-null object");if("number"!=typeof e.min||"number"!=typeof e.max)throw new TypeError("weatherDuration.min and weatherDuration.max must be numbers");this.#ds={...e}}set weatherTimeLeft(e){if(Gr(this.#hr),"number"!=typeof e)throw new TypeError("weatherTimeLeft must be a number, received "+typeof e);this.#ps=e}get weatherConfig(){Gr(this.#hr);const e={},t={};for(const t in this.#cs.hours)e[t]={...this.#cs.hours[t]};for(const e in this.#cs.seasons)t[e]={...this.#cs.seasons[e]};return{default:{...this.#cs.default},day:{...this.#cs.day},night:{...this.#cs.night},hours:e,seasons:t}}set weatherConfig(e){if(Gr(this.#hr),"object"!=typeof e||null===e)throw new TypeError(`weatherConfig must be a non-null object, received ${e}`);const t=["default","day","night","hours","seasons"];for(const r of t)if(!(r in e))throw new TypeError(`weatherConfig is missing required property "${r}".`);const r={},i={},s=(e,t)=>{if("object"!=typeof e||null===e)throw new TypeError(`${t} must be an object, received ${e}`);for(const r in e){const i=typeof e[r];if("number"!==i&&"function"!==i)throw new TypeError(`${t}["${r}"] must be a number or function, received ${i}`)}};for(const t in e.hours)s(e.hours[t],`hours["${t}"]`),r[t]={...e.hours[t]};for(const t in e.seasons)s(e.seasons[t],`seasons["${t}"]`),i[t]={...e.seasons[t]};const n=(e,t)=>(s(e,t),{...e});this.#cs={default:n(e.default,"default"),day:n(e.day,"day"),night:n(e.night,"night"),hours:r,seasons:i}}constructor(e=6,t=18){this.#es=e,this.#ts=t}addSeason(e,t){if(Gr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);if(!Array.isArray(t)||!t.every(e=>"number"==typeof e))throw new TypeError("Season values must be an array of numbers");this.#Qi.set(e,t)}removeSeason(e){if(Gr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);this.#Qi.delete(e),this.#os===e&&(this.#os="")}hasSeason(e){if(Gr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);return this.#Qi.has(e)}getSeason(e){if(Gr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);const t=this.#Qi.get(e);if(!t)throw new Error(`Season "${e}" not found`);return[...t]}setTime({hour:e=0,minute:t=0,second:r=0}){Gr(this.#hr),this.currentSeconds=(e*this.#Yi+t*this.#Xi+r)%this.#Gi}addTime({hours:e=0,minutes:t=0,seconds:r=0}){Gr(this.#hr);let i=this.currentSeconds+e*this.#Yi+t*this.#Xi+r;for(;i>=this.#Gi;)i-=this.#Gi,this.nextDay();for(;i<0;)i+=this.#Gi,this.prevDay();this.currentSeconds=i,this.updateWeatherTimer((e*this.#Yi+t*this.#Xi+r)/this.#Xi)}getTime({withSeconds:e=!1,hourSize:t=this.#Yi,minuteSize:r=this.#Xi}={}){Gr(this.#hr);const i=Math.floor(this.currentSeconds/t),s=Math.floor(this.currentSeconds%t/r),n=this.currentSeconds%r;return{hour:i,minute:s,second:n,formatted:`${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`+(e?`:${n.toString().padStart(2,"0")}`:"")}}isDay(){return Gr(this.#hr),this.#es<this.#ts?this.#ss>=this.#es*this.#Xi&&this.#ss<this.#ts*this.#Xi:this.#ss>=this.#es*this.#Xi||this.#ss<this.#ts*this.#Xi}minutesUntilDay(){return this.timeUntil(this.#es,"minutes")}secondsUntilDay(){return this.timeUntil(this.#es,"seconds")}hoursUntilDay(){return this.timeUntil(this.#es,"hours")}minutesUntilNight(){return this.timeUntil(this.#ts,"minutes")}secondsUntilNight(){return this.timeUntil(this.#ts,"seconds")}hoursUntilNight(){return this.timeUntil(this.#ts,"hours")}timeUntil(e,t){Gr(this.#hr);let r=e*this.#Yi-this.#is;switch(r<=0&&(r+=this.#Gi),t){case"minutes":return r/this.#Xi;case"hours":return r/this.#Yi;default:return r}}setTo(e){Gr(this.#hr),"day"===e?this.setTime({hour:this.#es}):"night"===e&&this.setTime({hour:this.#ts})}nextDay(e=1){Gr(this.#hr);for(let t=0;t<e;t++){this.#as++;const e=this.#us[this.#ls-1];if(Number.isNaN(e)||!Number.isFinite(e))throw new Error("Invalid month day count: monthDays must be a finite number.");this.#as>e&&(this.#as=1,this.#ls++,this.#ls>this.#us.length&&(this.#ls=1,this.#hs++)),this.updateSeason(),this.advanceMoons(1)}}prevDay(e=1){Gr(this.#hr);for(let t=0;t<e;t++)this.#as--,this.#as<1&&(this.#ls--,this.#ls<1&&(this.#ls=this.#us.length,this.#hs--),this.#as=this.#us[this.#ls-1]||30),this.updateSeason(),this.rewindMoons(1)}updateSeason(){Gr(this.#hr),this.#Qi.forEach((e,t)=>{e.includes(this.#ls)&&(this.#os=t)})}setWeatherConfig(e){Gr(this.#hr),this.#cs={...this.#cs,...e}}setWeatherDuration(e,t){Gr(this.#hr),this.#ds.min=e,this.#ds.max=t}updateWeatherTimer(e){Gr(this.#hr),this.#ps-=e,this.#ps<=0&&this.chooseNewWeather()}forceWeather({where:e="main",type:t,duration:r=null}){Gr(this.#hr);const i=this.#rs;i[e]=t,this.weather=i,this.#ps=r??this._randomInRange(this.#ds.min,this.#ds.max)}chooseNewWeather({customWeather:e,where:t="main"}={}){Gr(this.#hr);let r={};const i=e=>{for(const[t,i]of Object.entries(e)){let e=i;"function"==typeof e&&(e=e({hour:Math.floor(this.#ss/this.#Xi),minute:this.#ss%this.#Xi,currentMinutes:this.#ss,isDay:this.isDay(),season:this.#os,weather:this.#rs})),"number"!=typeof e||Number.isNaN(e)||(r[t]=(r[t]||0)+e)}};i(this.#cs.default||{});for(const e in this.#cs.hours){const[t,r]=e.split("-").map(e=>{const[t,r]=e.split(":").map(Number);return t*this.#Xi+(r||0)}),s=this.#ss;(t<=r?s>=t&&s<=r:s>=t||s<=r)&&i(this.#cs.hours[e])}this.isDay()&&this.#cs.day?i(this.#cs.day):!this.isDay()&&this.#cs.night&&i(this.#cs.night),this.#cs.seasons?.[this.#os]&&i(this.#cs.seasons[this.#os]),e&&"object"==typeof e&&i(e);const s=Object.entries(r).filter(([,e])=>e>0);if(!s.length)return this.#rs[t]=null,null;const n=s.reduce((e,[,t])=>e+t,0);let o=Math.random()*n;for(const[e,r]of s){if(o<r)return this.#rs[t]=e,this.#ps=this._randomInRange(this.#ds.min,this.#ds.max),e;o-=r}return this.#rs[t]=null,null}_randomInRange(e,t){return Math.floor(Math.random()*(t-e+1))+e}addMoon(e,t,r,i=0){Gr(this.#hr);const s=Math.max(1,t);return this.#Zi.push({name:e,cycleLength:s,currentPhase:(i%s+s)%s,phaseNames:r}),this.#Zi.length-1}removeMoon(e){Gr(this.#hr),this.#Zi=this.#Zi.filter(t=>t.name!==e)}advanceMoons(e=1){for(const t in this.#Zi)this.advanceMoon(parseInt(t),e)}rewindMoons(e=1){for(const t in this.#Zi)this.rewindMoon(parseInt(t),e)}advanceMoon(e,t=1){Gr(this.#hr);const r=this.#Zi[e];if(!r)throw new RangeError(`No moon found at index ${e}`);r.currentPhase=(r.currentPhase+t)%r.cycleLength}rewindMoon(e,t=1){Gr(this.#hr);const r=this.#Zi[e];if(!r)throw new RangeError(`No moon found at index ${e}`);r.currentPhase=(r.currentPhase-t+r.cycleLength)%r.cycleLength}moonExists(e){return Gr(this.#hr),!!this.#Zi[e]}getMoon(e){let t;if(Gr(this.#hr),"number"==typeof e){if(t=this.#Zi[e],!t)throw new RangeError(`No moon found at index ${e}`)}else{if(!e||"object"!=typeof e||"string"!=typeof e.name||"number"!=typeof e.cycleLength||"number"!=typeof e.currentPhase)throw new TypeError("Invalid moon reference. Expected a number index or a MoonRaw object, received "+typeof e);t=e}return{name:t.name,phaseIndex:t.currentPhase,phaseName:t.phaseNames?t.phaseNames[t.currentPhase]??String(t.currentPhase):String(t.currentPhase),cycleLength:t.cycleLength}}destroy(){this.#hr||(this.#Qi.clear(),this.#Zi.length=0,this.#es=0,this.#ts=0,this.#is=0,this.#ss=0,this.#ns=0,this.#as=1,this.#ls=1,this.#hs=1,this.#ps=0,this.#os="",this.#rs={main:null},this.#us=[],this.#cs.default={},this.#cs.day={},this.#cs.night={},this.#cs.hours={},this.#cs.seasons={},this.#ds={min:0,max:0},this.#hr=!0)}},Xr=le("TinyAdvancedRaffle"),Qr=e().EventEmitter;class Zr extends Qr{#hr=!1;#ms;#fs;#ys=[];#gs=[];#ws=[];#bs=new Map;#vs=new Set;#Es=new Map;#Ts;#Ss=new Map;#xs=new Map;get isDestroyed(){return this.#hr}get freq(){return Xr(this.#hr),Object.fromEntries(this.#xs)}get size(){return Xr(this.#hr),this.#Ss.size}get normalization(){return Xr(this.#hr),this.#ms}set normalization(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("normalization must be a non-empty string (e.g., 'relative', 'softmax').");this.#ms=e}get seed(){return Xr(this.#hr),this.#fs}set seed(e){if(Xr(this.#hr),null!==e&&("number"!=typeof e||!Number.isFinite(e)))throw new TypeError("seed must be a finite number or null.");this.#fs=e,null!==e&&(this.#Ts=this._makeSeededRng(e))}get globalModifiers(){return Xr(this.#hr),[...this.#ys]}set globalModifiers(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>"function"==typeof e))throw new TypeError("globalModifiers must be an array of functions (WeightsCallback).");this.#ys=e}get temporaryModifiers(){return Xr(this.#hr),[...this.#gs]}set temporaryModifiers(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>e&&"function"==typeof e.fn&&Number.isInteger(e.uses)&&e.uses>0))throw new TypeError("temporaryModifiers must be an array of objects { fn: function, uses: positive integer }.");this.#gs=e}get conditionalRules(){return Xr(this.#hr),[...this.#ws]}set conditionalRules(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>"function"==typeof e))throw new TypeError("conditionalRules must be an array of functions (WeightsCallback).");this.#ws=e}get pitySystems(){return Xr(this.#hr),Object.fromEntries(this.#bs)}set pitySystems(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e&&"number"==typeof e.threshold&&"number"==typeof e.increment&&"number"==typeof e.cap&&"number"==typeof e.counter&&"number"==typeof e.currentAdd)))throw new TypeError("pitySystems must be a Map<string, Pity> with all numeric fields.");this.#bs=e}get exclusions(){return Xr(this.#hr),Array.from(this.#vs)}set exclusions(e){if(Xr(this.#hr),!(e instanceof Set&&[...e].every(e=>"string"==typeof e)))throw new TypeError("exclusions must be a Set<string>.");this.#vs=e}get groups(){Xr(this.#hr);const e={};return this.#Es.forEach((t,r)=>e[r]=Array.from(t)),e}set groups(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e instanceof Set&&[...e].every(e=>"string"==typeof e))))throw new TypeError("groups must be a Map<string, Set<string>>.");this.#Es=e}get rng(){return Xr(this.#hr),this.#Ts}set rng(e){if(Xr(this.#hr),"function"!=typeof e||"number"!=typeof e())throw new TypeError("rng must be a function returning a number (RngGenerator).");this.#Ts=e}get items(){Xr(this.#hr);const e={};return this.#Ss.forEach((t,r)=>{e[r]={...t,groups:Array.from(t.groups)}}),e}set items(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e&&"string"==typeof e.id&&"string"==typeof e.label&&"number"==typeof e.baseWeight&&e.groups instanceof Set&&"boolean"==typeof e.locked&&"object"==typeof e.meta)))throw new TypeError("items must be a Map<string, ItemData> with valid item structures.");this.clearList(),this.#Ss=e}constructor(e={}){super();const{rng:t=null,seed:r=null,normalization:i="relative"}=e;this.#ms=i,this.#fs=r,"function"==typeof t?this.#Ts=t:null!==this.#fs?this.#Ts=this._makeSeededRng(this.#fs):this.#Ts=Math.random,this.#fs=r??null}hasItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#Ss.has(e)}addItem(e,t={}){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");if("object"!=typeof t||null===t)throw new TypeError("opts must be an object");let{weight:r=1,label:i=e,meta:s={},groups:n=[]}=t;if("number"!=typeof r||!Number.isFinite(r)||r<0)throw new TypeError("weight must be a non-negative number");if("string"!=typeof i)throw new TypeError("label must be a string");if("object"!=typeof s||null===s)throw new TypeError("meta must be an object");if(!(Array.isArray(n)||n instanceof Set))throw new TypeError("groups must be an array or a Set of strings");n=Array.isArray(n)?n:[...n];for(const e of n)if("string"!=typeof e)throw new TypeError("groups must contain only strings");const o={id:e,label:i,baseWeight:Math.max(0,Number(r)||0),meta:{...s},groups:new Set(n),locked:!1};this.#Ss.set(e,o);for(const t of n)this._ensureGroup(t).add(e);return this.emit("itemAdded",o),o}removeItem(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");const t=this.#Ss.get(e);if(!t)return!1;for(const r of t.groups){const t=this.#Es.get(r);t&&t.delete(e)}return this.#Ss.delete(e),this.emit("itemRemoved",e),this.resetFreq(e),this.resetPity(e),!0}setBaseWeight(e,t){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");if("number"!=typeof t||!Number.isFinite(t)||t<0)throw new TypeError("weight must be a non-negative number");const r=this.#Ss.get(e);if(!r)throw new Error("Item not found");r.baseWeight=Math.max(0,Number(t)||0),this.emit("weightChanged",{id:e,weight:r.baseWeight})}getItem(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");return this.#Ss.get(e)??null}listItems(){return Xr(this.#hr),Array.from(this.#Ss.values()).map(e=>({...e}))}clearList(){Xr(this.#hr),this.#Ss.clear(),this.clearFreqs(),this.clearPities()}hasGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");return this.#ys.includes(e)}addGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");this.#ys.push(e)}removeGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");this.#ys=this.#ys.filter(t=>t!==e)}hasTemporaryModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");return this.#gs.some(t=>t.fn===e)}addTemporaryModifier(e,t=1){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");if("number"!=typeof t||Number.isNaN(t))throw new TypeError("uses must be a number");this.#gs.push({fn:e,uses:Math.max(1,Math.floor(t))})}removeTemporaryModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");const t=this.#gs.length;return this.#gs=this.#gs.filter(t=>t.fn!==e),this.#gs.length!==t}hasConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");return this.#ws.includes(e)}addConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");this.#ws.push(e)}removeConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");const t=this.#ws.length;return this.#ws=this.#ws.filter(t=>t!==e),this.#ws.length!==t}hasPity(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#bs.has(e)}configurePity(e,t){if(Xr(this.#hr),!this.#Ss.has(e))throw new Error("Item not found");if("object"!=typeof t||null===t)throw new TypeError("cfg must be an object");const{threshold:r,increment:i,cap:s=1/0}=t;if("number"!=typeof r||r<=0)throw new TypeError("threshold must be a positive number");if("number"!=typeof i)throw new TypeError("increment must be a number");if("number"!=typeof s)throw new TypeError("cap must be a number");this.#bs.set(e,{threshold:Math.max(1,r),increment:Number(i)||0,cap:Number(s)||1/0,counter:0,currentAdd:0})}resetPity(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("itemId must be a non-empty string");const t=this.#bs.get(e);t&&(t.counter=0,t.currentAdd=0)}clearPities(){Xr(this.#hr),this.#bs.clear()}hasExclusion(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#vs.has(e)}excludeItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#vs.add(e)}includeItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#vs.delete(e)}_ensureGroup(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("name must be a string");let t=this.#Es.get(e);return t||(t=new Set,this.#Es.set(e,t)),t}hasInGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Es.get(t);return!!r&&r.has(e)}addToGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Ss.get(e);if(!r)throw new Error("Item missing");r.groups.add(t),this._ensureGroup(t).add(e)}removeFromGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Es.get(t);r&&r.delete(e);const i=this.#Ss.get(e);i&&i.groups.delete(t)}clearFreqs(){Xr(this.#hr),this.#xs.clear()}resetFreq(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#xs.delete(e)}computeEffectiveWeights(e={}){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("computeEffectiveWeights: parameter 'context' must be a non-null object, got "+typeof e);if("previousDraws"in e&&!Array.isArray(e.previousDraws))throw new TypeError("computeEffectiveWeights: context.previousDraws must be an array if provided, got "+typeof e.previousDraws);if("metadata"in e&&void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata))throw new TypeError("computeEffectiveWeights: context.metadata must be a non-null object if provided, got "+typeof e.metadata);const t=new Map;for(const[e,r]of this.#Ss)t.set(e,r.baseWeight);for(const r of this.#ys){const i=r(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const r of this.#gs){const i=r.fn(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const r of this.#ws){const i=r(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const[e,r]of this.#bs)if(t.has(e)&&r.counter>r.threshold){r.currentAdd=Math.min(r.cap,r.currentAdd+r.increment);const i=t.get(e);i&&t.set(e,i+r.currentAdd)}for(const e of this.#vs)t.delete(e);for(const[e,r]of Array.from(t.entries()))r>0||t.delete(e);return t}_weightsToDistribution(e){if(!(e instanceof Map))throw new TypeError("_weightsToDistribution: parameter 'weights' must be a Map, got "+typeof e);for(const[t,r]of e){if("string"!=typeof t)throw new TypeError("_weightsToDistribution: weights Map key must be string, got "+typeof t);if("number"!=typeof r||!Number.isFinite(r)||r<0)throw new TypeError(`_weightsToDistribution: weights Map value must be finite non-negative number, got ${r} for key ${t}`)}const t=Array.from(e.entries()).map(([e,t])=>({id:e,weight:t}));if(0===t.length)return[];if("softmax"===this.#ms){const e=Math.max(...t.map(e=>e.weight)),r=t.map(t=>Math.exp(t.weight-e)),i=r.reduce((e,t)=>e+t,0);let s=0;return t.map((e,t)=>{const n=r[t]/i;return s+=n,{id:e.id,weight:e.weight,p:n,cumulative:s}})}{const e=t.reduce((e,t)=>e+t.weight,0);let r=0;return t.map(t=>{const i=t.weight/e;return r+=i,{id:t.id,weight:t.weight,p:i,cumulative:r}})}}drawOne(e={}){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("drawOne: parameter 'opts' must be a non-null object, got "+typeof e);if("previousDraws"in e&&!Array.isArray(e.previousDraws))throw new TypeError("drawOne: opts.previousDraws must be an array if provided, got "+typeof e.previousDraws);if("metadata"in e&&void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata))throw new TypeError("drawOne: opts.metadata must be a non-null object if provided, got "+typeof e.metadata);const t={previousDraws:e.previousDraws??[],metadata:e.metadata??{},activeModifiers:[...this.#gs]},r=this.computeEffectiveWeights(t),i=this._weightsToDistribution(r);if(!i.length)return null;const s=this.#Ts(),n=i.find(e=>s<=e.cumulative)??i[i.length-1];for(const[e,t]of this.#bs)e===n.id?(t.counter=0,t.currentAdd=0):t.counter++;this._consumeTemporaryModifiers();const o=this.#Ss.get(n.id);if(!o)return null;const a={id:o.id,label:o.label,meta:{...o.meta},prob:n.p};return this.emit("draw",a),a&&this.#xs.set(a.id,(this.#xs.get(a.id)||0)+1),a}_consumeTemporaryModifiers(){for(let e=this.#gs.length-1;e>=0;--e){const t=this.#gs[e];t.uses-=1,t.uses<=0&&this.#gs.splice(e,1)}}drawMany(e=1,t={}){if(Xr(this.#hr),!Number.isInteger(e)||e<=0)throw new TypeError(`drawMany: parameter 'count' must be a positive integer, got ${e}`);if("object"!=typeof t||null===t)throw new TypeError("drawMany: parameter 'opts' must be a non-null object, got "+typeof t);if("withReplacement"in t&&"boolean"!=typeof t.withReplacement)throw new TypeError("drawMany: opts.withReplacement must be boolean if provided, got "+typeof t.withReplacement);if("ensureUnique"in t&&"boolean"!=typeof t.ensureUnique)throw new TypeError("drawMany: opts.ensureUnique must be boolean if provided, got "+typeof t.ensureUnique);if("metadata"in t&&void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata))throw new TypeError("drawMany: opts.metadata must be a non-null object if provided, got "+typeof t.metadata);if("previousDraws"in t&&!Array.isArray(t.previousDraws))throw new TypeError("drawMany: opts.previousDraws must be an array if provided, got "+typeof t.previousDraws);const r=t.withReplacement??!0,i=t.ensureUnique??!1,s=[],n=t.previousDraws??[];if(!r&&i){const r=new Set;for(let i=0;i<e;++i){const e=new Set(this.#vs);for(const e of r)this.#vs.add(e);const i=this.drawOne({previousDraws:n,metadata:t.metadata});if(this.#vs=e,!i)break;s.push(i),r.add(i.id),n.push(i)}return s}for(let i=0;i<e;++i){const e=this.drawOne({previousDraws:n,metadata:t.metadata});if(!e)break;s.push(e),n.push(e),r||this.excludeItem(e.id)}if(!r)for(const e of s)this.includeItem(e.id);return s}exportToJson(){return Xr(this.#hr),{items:Array.from(this.#Ss.values()).map(e=>({id:e.id,label:e.label,baseWeight:e.baseWeight,meta:e.meta,groups:Array.from(e.groups),locked:!1})),pity:Array.from(this.#bs.entries()),exclusions:Array.from(this.#vs),normalization:this.#ms,seed:this.#fs}}loadFromJson(e){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("data must be a non-null object");if(!Array.isArray(e.items)||!Array.isArray(e.pity)||!Array.isArray(e.exclusions))throw new TypeError("data must have items, pity, and exclusions arrays");if("string"!=typeof e.normalization)throw new TypeError("data.normalization must be a string");if(void 0!==e.seed&&null!==e.seed&&"number"!=typeof e.seed)throw new TypeError("data.seed must be a number, null, or undefined");this.clearList();for(const t of e.items){if("object"!=typeof t||null===t)throw new TypeError("Each item must be a non-null object");if("string"!=typeof t.id||!t.id.trim())throw new TypeError("Each item.id must be a non-empty string");if("string"!=typeof t.label)throw new TypeError(`Item with id "${t.id}" has invalid label; must be string`);if("number"!=typeof t.baseWeight||!Number.isFinite(t.baseWeight)||t.baseWeight<0)throw new TypeError(`Item with id "${t.id}" has invalid baseWeight; must be a finite non-negative number`);if(void 0!==t.groups&&!Array.isArray(t.groups))throw new TypeError(`Item with id "${t.id}" has invalid groups; must be an array of strings`);if(t.groups&&!t.groups.every(e=>"string"==typeof e))throw new TypeError(`Item with id "${t.id}" has groups containing non-string values`);if(void 0!==t.meta&&("object"!=typeof t.meta||null===t.meta))throw new TypeError(`Item with id "${t.id}" has invalid meta; must be an object`);this.#Ss.set(t.id,{id:t.id,label:t.label,baseWeight:t.baseWeight,meta:t.meta||{},groups:new Set(t.groups||[]),locked:!1});for(const e of t.groups||[])this._ensureGroup(e).add(t.id)}this.pitySystems=new Map(e.pity||[]),this.exclusions=new Set(e.exclusions||[]),this.normalization=e.normalization,void 0!==e.seed&&(this.seed=e.seed)}clone(){Xr(this.#hr);const e=new Zr;return e.#ms=this.#ms,e.#fs=this.#fs,e.#ys=[...this.#ys],e.#gs=this.#gs.map(e=>({fn:e.fn,uses:e.uses})),e.#ws=[...this.#ws],e.#bs=new Map([...this.#bs.entries()].map(([e,t])=>[e,{...t}])),e.#vs=new Set(this.#vs),e.#Es=new Map([...this.#Es.entries()].map(([e,t])=>[e,new Set(t)])),e.#Ts=this.#Ts,e.#Ss=new Map([...this.#Ss.entries()].map(([e,t])=>[e,{...t,groups:new Set(t.groups),meta:{...t.meta}}])),e.#xs=new Map(this.#xs),e}_makeSeededRng(e){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("seed must be a finite number");let t=e>>>0;return function(){t+=1831565813;let e=Math.imul(t^t>>>15,1|t);return e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}destroy(){this.#hr||(this.#bs.clear(),this.#vs.clear(),this.#Es.clear(),this.#Ss.clear(),this.#xs.clear(),this.#ys=[],this.#gs=[],this.#ws=[],this.#fs=null,this.#hr=!0)}}const ei=Zr,ti=class{#ie;get data(){return this.#ie}set data(e){if(!(Array.isArray(e)||e instanceof Set))throw new TypeError("Paginator expects an array or Set as data source.");this.#ie=e}get size(){return Array.isArray(this.#ie)?this.#ie.length:this.#ie.size}constructor(e){if(!(Array.isArray(e)||e instanceof Set))throw new TypeError("Paginator expects an array or Set as data source.");this.#ie=e}get({page:e,perPage:t,filter:r}){if(!Number.isInteger(e)||e<1)throw new RangeError("Page number must be a positive integer.");if(!Number.isInteger(t)||t<1)throw new RangeError("Items per page must be a positive integer.");const i=Array.isArray(this.#ie)?this.#ie:Array.from(this.#ie);let s=i;if(r)if("function"==typeof r)s=i.filter((e,t,i)=>r(e,t,i));else{if("object"!=typeof r)throw new TypeError("Filter must be an object or a function");s=i.filter(e=>Object.entries(r).every(([t,r])=>{const i=e[t];return r instanceof RegExp?r.test(i):i===r}))}else s=i;const n=s.length,o=Math.max(1,Math.ceil(n/t)),a=Math.min(e,o),l=(a-1)*t,h=l+t,u=a>1,c=a<o;return{items:s.slice(l,h),page:a,perPage:t,totalItems:n,totalPages:o,hasPrev:u,hasNext:c}}};class ri{static#As=new Map;static get itemRegistry(){const e={},t=Object.fromEntries(ri.#As);for(const r in t)e[r]={...t[r],metadata:{...t[r].metadata}};return e}static defineItem(e){if(!e||"object"!=typeof e)throw new TypeError("Config must be a valid object.");if(!e.id||"string"!=typeof e.id)throw new TypeError("Item must have a valid string 'id'.");if(void 0!==e.weight&&("number"!=typeof e.weight||e.weight<0))throw new TypeError(`weight must be a number >= 0. Received: ${e.weight}`);if(void 0!==e.maxStack&&(!Number.isInteger(e.maxStack)||e.maxStack<=0))throw new TypeError(`maxStack must be a positive integer. Received: ${e.maxStack}`);if(void 0!==e.metadata&&"object"!=typeof e.metadata)throw new TypeError("metadata must be an object.");if(void 0!==e.onUse&&null!==e.onUse&&"function"!=typeof e.onUse)throw new TypeError("onUse must be a function or null.");if(void 0!==e.type&&null!==e.type&&"string"!=typeof e.type)throw new TypeError("type must be a string or null.");ri.#As.set(e.id,{id:e.id,weight:e.weight||0,maxStack:e.maxStack||1,metadata:e.metadata||{},type:e.type??null,onUse:"function"==typeof e.onUse?e.onUse:null})}static removeItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");return ri.#As.delete(e)}static hasItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");return ri.#As.has(e)}static getItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");const t=ri.#As.get(e);if(!t)throw new Error(`Item '${e}' not defined in registry.`);return t}#Cs=new Map;#Is={add:[],remove:[],use:[],set:[]};#Ss=[];#Ds;#ks;#Ms;#Ls;get maxStack(){return this.#Ds}set maxStack(e){if(!Number.isInteger(e)||Number.isFinite(e)&&e<=0)throw new TypeError(`maxStack must be a positive integer. Received: ${e}`);this.#Ds=e}get maxSize(){return this.#ks}set maxSize(e){if(null!==e&&(!Number.isInteger(e)||e<=0))throw new TypeError(`maxSize must be null or a positive integer. Received: ${e}`);this.#ks=e}get maxSlots(){return this.#Ms}set maxSlots(e){if(null!==e&&(!Number.isInteger(e)||e<=0))throw new TypeError(`maxSlots must be null or a positive integer. Received: ${e}`);this.#Ms=e}get maxWeight(){return this.#Ls}set maxWeight(e){if(null!==e&&("number"!=typeof e||e<=0))throw new TypeError(`maxWeight must be null or a positive number. Received: ${e}`);this.#Ls=e}get events(){return{add:[...this.#Is.add],remove:[...this.#Is.remove],use:[...this.#Is.use],set:[...this.#Is.set]}}get items(){return[...this.#Ss].map(e=>e?this.#Ns(e):null)}get specialSlots(){return new Map([...this.#Cs.entries()].map(([e,t])=>[e,{type:t.type,item:t.item?this.#Ns(t.item):null}]))}get size(){const e=this.getAllItems();let t=0;for(const r of e)t+=r.quantity;return t}get slotsSize(){return this.getAllItems().length}get weight(){return this.getAllItems().reduce((e,t)=>{const r=ri.getItem(t.id);return e+(r?.weight||0)*t.quantity},0)}_cleanNulls(){let e=this.#Ss.length-1;for(;e>=0&&null===this.#Ss[e];)e--;this.#Ss=this.#Ss.slice(0,e+1)}constructor(e={}){if("object"!=typeof e||null===e)throw new TypeError("`options` must be an object.");if(void 0!==e.maxWeight&&null!==e.maxWeight&&"number"!=typeof e.maxWeight)throw new TypeError("`maxWeight` must be a number or null.");if(void 0!==e.maxSlots&&null!==e.maxSlots&&"number"!=typeof e.maxSlots)throw new TypeError("`maxSlots` must be a number or null.");if(void 0!==e.maxSize&&null!==e.maxSize&&"number"!=typeof e.maxSize)throw new TypeError("`maxSize` must be a number or null.");if(void 0!==e.maxStack&&"number"!=typeof e.maxStack)throw new TypeError("`maxStack` must be a number.");if(void 0!==e.specialSlots&&"object"!=typeof e.specialSlots)throw new TypeError("`specialSlots` must be an object if defined.");if(this.#Ls=e.maxWeight??null,this.#Ms=e.maxSlots??null,this.#ks=e.maxSize??null,this.#Ds=e.maxStack??1/0,e.specialSlots)for(const t in e.specialSlots){const r=e.specialSlots[t];if("object"!=typeof r||null===r)throw new TypeError("Each `specialSlot` entry must be an object.");if(void 0!==r.type&&null!==r.type&&"string"!=typeof r.type)throw new TypeError("`specialSlot.type` must be a string or null.");this.#Cs.set(t,{type:r.type??null,item:null})}}hasSpace({weight:e=0,sizeLength:t=0,slotsLength:r=0}={}){if("number"!=typeof e)throw new TypeError("`weight` must be a number.");if("number"!=typeof t)throw new TypeError("`sizeLength` must be a number.");if("number"!=typeof r)throw new TypeError("`slotsLength` must be a number.");return!(this.areFull(t)||this.areFullSlots(r)||this.isHeavy(e))}isHeavy(e=0){if("number"!=typeof e)throw new TypeError("`extraWeight` must be a number.");return null!==this.#Ls&&this.weight+e>this.#Ls}areFull(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#ks&&this.size+e>this.#ks}isFull(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#ks&&this.size+e>=this.#ks}areFullSlots(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ms&&this.slotsSize+e>this.#Ms}isFullSlots(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ms&&this.slotsSize+e>=this.#Ms}#_s(e,t){if("string"!=typeof e)throw new TypeError("`type` must be a string.");if("object"!=typeof t||null===t)throw new TypeError("`payload` must be an object.");if(this.#Is[e])for(const r of this.#Is[e])r(t)}off(e,t){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");if("function"!=typeof t)throw new TypeError("`callback` must be a function.");if(!this.#Is[e])return;const r=this.#Is[e],i=r.indexOf(t);-1!==i&&r.splice(i,1)}offAll(e){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");this.#Is[e]&&(this.#Is[e]=[])}cloneEventCallbacks(e){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");return this.#Is[e]?[...this.#Is[e]]:[]}onAddItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.add.push(e)}onSetItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.set.push(e)}onRemoveItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.remove.push(e)}onUseItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.use.push(e)}compactInventory(){this.#Ss=this.#Ss.filter((e,t)=>{const r=null!==e;return r||this.#_s("remove",{index:t,item:null,isCollection:!0,specialSlot:null,remove:()=>{}}),r})}addItem({itemId:e,quantity:t=1,metadata:r={},forceSpace:i=!1}){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw new TypeError("`quantity` must be a positive number.");if("object"!=typeof r||null===r)throw new TypeError("`metadata` must be an object.");if("boolean"!=typeof i)throw new TypeError("`forceSpace` must be a boolean.");const s=ri.getItem(e);let n=t;const o=s.maxStack<=this.#Ds?s.maxStack:this.#Ds,a=[],l=(e,t)=>JSON.stringify(e)===JSON.stringify(t);let h=!0;for(;n>0&&h;){h=!1;for(const t in this.#Ss){const u=this.#Ss[t];if(u&&u.id===e&&u.quantity<o&&l(u.metadata,r)){const e=Math.min(o-u.quantity,n);if(!i&&!this.hasSpace({weight:s.weight*e,sizeLength:e}))continue;u.quantity+=e,n-=e,h=!0;const r=Number(t),l=a.findIndex(e=>e.index===r);if(l<0?a.push({index:r,quantity:e}):a[l].quantity+=e,this.#_s("add",{item:this.#Ns(u),index:r,isCollection:!0,specialSlot:null,remove:this.#Ps({locationType:"normal",slotIndex:r,forceSpace:i,item:u})}),n<=0)break}}}if(n>0)for(const t in this.#Ss)if(null===this.#Ss[t]){const l=Math.min(o,n);if(!i&&!this.hasSpace({weight:s.weight*l,sizeLength:l}))continue;const h={id:e,quantity:l,metadata:r};this.#Ss[t]=h,n-=l;const u=Number(t),c=a.findIndex(e=>e.index===u);if(c<0?a.push({index:u,quantity:l}):a[c].quantity+=l,this.#_s("add",{item:this.#Ns(h),index:u,isCollection:!0,specialSlot:null,remove:this.#Ps({locationType:"normal",slotIndex:u,forceSpace:i,item:h})}),n<=0)break}for(;n>0;){const t=Math.min(o,n);if(!i&&!this.hasSpace({weight:s.weight*t,sizeLength:t,slotsLength:1}))break;const l={id:e,quantity:t,metadata:r};this.#Ss.push(l);const h=this.#Ss.length-1,u=a.findIndex(e=>e.index===h);u<0?a.push({index:h,quantity:t}):a[u].quantity+=t,this.#_s("add",{item:this.#Ns(l),index:h,isCollection:!0,specialSlot:null,remove:this.#Ps({locationType:"normal",slotIndex:h,forceSpace:i,item:l})}),n-=t}return{remaining:n,placesAdded:a}}getItemFrom(e){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if(e<0||e>=this.#Ss.length)throw new Error(`Slot index '${e}' out of bounds .`);return this.#Ss[e]?this.#Ns(this.#Ss[e]):null}setItem({slotIndex:e,item:t,forceSpace:r=!1}){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be a boolean.");const i=t&&"object"==typeof t&&"string"==typeof t.id&&"number"==typeof t.quantity&&!Number.isNaN(t.quantity)&&Number.isFinite(t.quantity)&&t.quantity>-1&&"object"==typeof t.metadata;if(null!==t&&!i)throw new Error("Invalid item type: must be null or a valid InventoryItem.");const s=t?ri.#As.get(t.id):null;if(null!==t&&!s)throw new Error(`Item '${t?.id??"unknown"}' not defined in registry.`);if(s&&t){const e=s.maxStack<=this.#Ds?s.maxStack:this.#Ds;if(t.quantity>e)throw new Error(`Item '${t.id}' exceeds max stack size. Allowed: ${e}, got: ${t.quantity}.`)}if(null!==this.#Ms&&(e<0||e>=this.#Ms))throw new Error(`Slot index ${e} out of range.`);const n=this.#Ss[e]??null,o=n?ri.#As.get(n.id)??null:null,a=(e,t)=>t?t.weight*(e?e.quantity:0):0,l=e=>e?e.quantity:0;if(!r&&!this.hasSpace({weight:a(t,s)-a(n,o),sizeLength:l(t)-l(n)}))throw new Error("Inventory is full or overweight.");for(;this.#Ss.length<=e;)this.#Ss.push(null);this.#Ss[e]=t,this._cleanNulls(),this.#_s("set",{index:e,isCollection:!0,item:t?this.#Ns(t):null,specialSlot:null,remove:t?this.#Ps({locationType:"normal",slotIndex:e,forceSpace:r,item:t}):()=>{}})}deleteItem(e,t=!1){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if("boolean"!=typeof t)throw new TypeError("`forceSpace` must be a boolean.");this.setItem({slotIndex:e,item:null,forceSpace:t})}moveItem(e,t,r=!1){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`fromIndex` must be an integer.");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError("`toIndex` must be an integer.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be a boolean.");const i=this.#Ss[e];if(!i)throw new Error(`No item found in slot ${e}.`);this.setItem({slotIndex:t,item:i,forceSpace:r}),this.setItem({slotIndex:e,item:null,forceSpace:r})}removeItem({itemId:e,metadata:t=null,quantity:r=1}){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if(null!==t&&"object"!=typeof t)throw new TypeError("`metadata` must be an object or null.");if("number"!=typeof r||!Number.isFinite(r)||r<=0)throw new TypeError("`quantity` must be a positive number.");let i=r;const s=(e,t)=>JSON.stringify(e)===JSON.stringify(t);for(let r=0;r<this.#Ss.length;r++){const n=this.#Ss[r];if(n&&n.id===e&&(null===t||s(n.metadata,t))){const e=Math.min(n.quantity,i);n.quantity-=e,i-=e;const t=Number(r);if(n.quantity<=0&&(this.#Ss[r]=null),i<=0)return this._cleanNulls(),this.#_s("remove",{index:t,item:this.#Ns(n),isCollection:!0,specialSlot:null,remove:this.#Ps({locationType:"normal",slotIndex:t,item:n})}),!0}}return this._cleanNulls(),this.#Cs.forEach((r,n)=>{if(i>0&&r.item&&r.item.id===e&&(null===t||s(r.item.metadata,t))){const e=Math.min(r.item.quantity,i);r.item.quantity-=e,r.item.quantity<0&&(r.item.quantity=0),i-=e,r.item.quantity<=0&&(r.item=null),this.#Cs.set(n,r),this.#_s("remove",{index:null,item:r.item?this.#Ns(r.item):null,isCollection:!1,specialSlot:n,remove:r.item?this.#Ps({locationType:"special",specialSlot:n,item:r.item}):()=>{}})}}),i<=0}#Ps({locationType:e,specialSlot:t,slotIndex:r,item:i,forceSpace:s=!1}){if("normal"!==e&&"special"!==e)throw new TypeError("`locationType` must be 'normal' or 'special'.");if("boolean"!=typeof s)throw new TypeError("`forceSpace` must be boolean.");if(!i||"object"!=typeof i)throw new TypeError("`item` must be an InventoryItem object.");if("special"===e&&t&&"string"!=typeof t)throw new TypeError("`specialSlot` must be a string when locationType is 'special'.");if("normal"===e&&"number"!=typeof r)throw new TypeError("`slotIndex` must be a number when locationType is 'normal'.");return(n=s)=>{if("special"===e&&t){const e=this.#Cs.get(t);if(!e?.item)throw new Error(`Special slot '${t}' is empty.`);e.item.quantity>1?(e.item.quantity-=1,this.#Cs.set(t,e)):this.setSpecialSlot({slotId:t,item:null,forceSpace:n})}else{if("number"!=typeof r)throw new Error("Invalid remove operation: no valid slotIndex or specialSlot provided.");i.quantity>1?this.setItem({slotIndex:r,item:{...i,quantity:i.quantity-1},forceSpace:n}):this.setItem({slotIndex:r,item:null,forceSpace:n})}}}useItem({slotIndex:e,specialSlot:t,forceSpace:r=!1},...i){if(void 0!==e&&("number"!=typeof e||!Number.isInteger(e)))throw new TypeError("`slotIndex` must be an integer if provided.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("`specialSlot` must be a string if provided.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");let s=null,n="normal",o=null;if(t){if(!this.#Cs.has(t))throw new Error(`Special slot '${t}' not found.`);s=this.#Cs.get(t).item,n="special"}else o=this.#Ss,s=o[e??-1]??null,n="normal";if(!s)throw new Error("special"===n?`No item found in special slot '${t}'.`:`No item found in slot ${e} of inventory.`);const a=ri.getItem(s.id);if(a.onUse){const l={inventory:this,item:this.#Ns(s),index:e??null,specialSlot:t??null,isCollection:!!o,itemDef:a,remove:this.#Ps({locationType:n,specialSlot:t,slotIndex:e,forceSpace:r,item:s}),...i},h=a.onUse(l);return this.#_s("use",l),h}return null}hasSpecialSlot(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");return this.#Cs.has(e)}getSpecialItem(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const t=this.#Cs.get(e);return t?.item?this.#Ns(t.item):null}getSpecialSlotType(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const t=this.#Cs.get(e);return t?.type??null}setSpecialSlot({slotId:e,item:t,forceSpace:r=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' not found.`);const i=t&&"object"==typeof t&&"string"==typeof t.id&&"number"==typeof t.quantity&&!Number.isNaN(t.quantity)&&Number.isFinite(t.quantity)&&t.quantity>-1&&"object"==typeof t.metadata;if(null!==t&&!i)throw new Error("Invalid item type: must be null or a valid InventoryItem.");const s=t?ri.#As.get(t.id):null;if(null!==t&&!s)throw new Error(`Item '${t?.id??"unknown"}' not defined in registry.`);const n=this.#Cs.get(e);if(!n)throw new Error(`Special slot ${e} out of range for slot '${e}'.`);const o=n.item?ri.#As.get(n.item.id):null,a=(e,t)=>t?t.weight*(e?1:0):0,l=e=>e?1:0;if(!r&&!this.hasSpace({weight:a(t,s)-a(n.item,o),sizeLength:l(t)-l(n.item)}))throw new Error("Inventory is full or overweight.");n.item=t,this.#_s("set",{index:null,item:t?this.#Ns(t):null,isCollection:!1,specialSlot:e,remove:t?this.#Ps({locationType:"special",specialSlot:e,forceSpace:r,item:t}):()=>{}})}deleteSpecialItem(e,t=!1){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("boolean"!=typeof t)throw new TypeError("`forceSpace` must be boolean.");this.setSpecialSlot({slotId:e,item:null,forceSpace:t})}equipItem({slotId:e,slotIndex:t,quantity:r=1,forceSpace:i=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError("`slotIndex` must be an integer.");if("number"!=typeof r||!Number.isFinite(r)||r<=0)throw new TypeError("`quantity` must be a positive number.");if("boolean"!=typeof i)throw new TypeError("`forceSpace` must be boolean.");if(r<=0||!Number.isFinite(r))throw new Error(`Invalid quantity '${r}'.`);if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const s=this.getItemFrom(t);if(!s)throw new Error(`No item found in inventory slot ${t}.`);if(s.quantity<r)throw new Error(`Not enough quantity of item '${s.id}' in inventory slot.`);const n=ri.getItem(s.id),o=this.#Cs.get(e);if(!o)throw new Error(`Slot '${e}' not defined in registry.`);const a=o.type??null;if(null!==a&&n.type!==a)throw new Error(`Item '${s.id}' cannot be equipped in slot '${e}'.`);const l=Math.min(n.maxStack,this.#Ds);if(o.item&&o.item.id===s.id){const t=Math.max(0,l-o.item.quantity);if(t<=0)return r;const i=Math.min(r,t);return this.removeItem({itemId:s.id,quantity:i,metadata:null}),o.item.quantity+=i,this.#Cs.set(e,o),r-i}o.item&&this.unequipItem({slotId:e,forceSpace:i});const h=Math.min(r,l);return this.removeItem({itemId:s.id,quantity:h,metadata:null}),o.item={id:s.id,quantity:h,metadata:s.metadata},this.#Cs.set(e,o),r-h}unequipItem({slotId:e,quantity:t=null,forceSpace:r=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(null!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new TypeError("`quantity` must be a positive number or null.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const i=this.#Cs.get(e);if(!i)throw new Error(`Slot '${e}' not defined in registry.`);if(!i.item)return!1;const s=i.item,n=null===t?s.quantity:t;if(n<=0)throw new Error(`Invalid unequip quantity: ${n}`);if(n>s.quantity)throw new Error(`Not enough items in slot '${e}' to unequip.`);return this.addItem({itemId:s.id,quantity:n,metadata:s.metadata,forceSpace:r}),n===s.quantity?i.item=null:(s.quantity-=n,i.item=s),this.#Cs.set(e,i),!0}#Ns(e){if(!e||"object"!=typeof e)throw new TypeError("`item` must be an InventoryItem object.");if("string"!=typeof e.id)throw new TypeError("`item.id` must be a string.");if("number"!=typeof e.quantity||!Number.isFinite(e.quantity))throw new TypeError("`item.quantity` must be a finite number.");if(!e.metadata||"object"!=typeof e.metadata)throw new TypeError("`item.metadata` must be an object.");return{id:e.id,quantity:e.quantity,metadata:{...e.metadata}}}getItemList(){return[...this.#Ss].map((e,t)=>[e?this.#Ns(e):null,t]).filter(e=>null!==e[0])}getAllItems(){const e=[...this.#Ss].filter(e=>null!==e).map(this.#Ns);return this.#Cs.forEach(t=>{const r=t.item;r&&e.push(r)}),e}getItemsByMetadata(e){if("function"!=typeof e)throw new TypeError("`filterFn` must be a function.");return this.getAllItems().filter(t=>{const r=ri.getItem(t.id);return e(r.metadata,t)})}findItem(e){if("function"!=typeof e)throw new TypeError("`predicate` must be a function.");return this.getAllItems().find(e)}findItems(e){if("function"!=typeof e)throw new TypeError("`predicate` must be a function.");return this.getAllItems().filter(e)}getItemCount(e){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");return this.getAllItems().filter(t=>t.id===e).reduce((e,t)=>e+t.quantity,0)}hasItem(e,t=1){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if("number"!=typeof t||!Number.isFinite(t)||t<0)throw new TypeError("`quantity` must be a non-negative number.");return this.getItemCount(e)>=t}existsItemAt(e){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");return!!this.#Ss[e]}clear(){this.clearAllItems(),this.clearAllEvents()}clearAllEvents(){this.#Is={add:[],remove:[],use:[],set:[]}}clearAllItems(){this.clearItems(),this.clearSpecialItems()}clearItems(){for(let e=this.#Ss.length-1;e>=0;e--)this.#Ss[e]&&this.deleteItem(e,!0)}clearSpecialItems(){for(const e of this.#Cs.keys()){const t=this.#Cs.get(e);t?.item&&this.deleteSpecialItem(e,!0)}}clone(){const e=this.toObject();return ri.fromObject(e)}toObject(){const e={};for(const[t,r]of this.#Cs.entries())e[t]={type:r?.type??null,item:r?.item?this.#Ns(r.item):null};return{__schema:"TinyInventory",version:1,maxWeight:this.#Ls,maxSlots:this.#Ms,maxSize:this.#ks,maxStack:this.#Ds,items:this.#Ss.map(e=>e?this.#Ns(e):null),specialSlots:e}}toJSON(e=0){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new TypeError("`space` must be a non-negative number.");return JSON.stringify(this.toObject(),null,e)}static fromObject(e){if(!e||"object"!=typeof e)throw new TypeError("Invalid state: expected object.");if("TinyInventory"!==e.__schema||"number"!=typeof e.version)throw new TypeError("Invalid or missing schema header.");if(1!==e.version)throw new TypeError(`Unsupported TinyInventory state version: ${e.version}`);const t={};if(e.specialSlots&&"object"==typeof e.specialSlots)for(const r of Object.keys(e.specialSlots))t[r]={type:e.specialSlots[r]?.type??null};const r=new ri({maxWeight:e.maxWeight??null,maxSlots:e.maxSlots??null,maxSize:e.maxSize??null,maxStack:e.maxStack??null,specialSlots:t});if(Array.isArray(e.items))for(const t in e.items){const i=e.items[t];if(null!==i){const e={id:String(i.id),quantity:Math.max(1,Number(i.quantity)||1),metadata:i.metadata&&"object"==typeof i.metadata?i.metadata:{}};r.setItem({slotIndex:Number(t),item:e,forceSpace:!0})}else r.setItem({slotIndex:Number(t),item:null,forceSpace:!0})}if(e.specialSlots&&"object"==typeof e.specialSlots)for(const[t,i]of Object.entries(e.specialSlots)){if(!r.hasSpecialSlot(t))continue;const e=i?.item;if(e&&e.id){const i={id:String(e.id),quantity:Math.max(1,Number(e.quantity)||1),metadata:e.metadata&&"object"==typeof e.metadata?e.metadata:{}};r.setSpecialSlot({slotId:t,item:i,forceSpace:!0})}}return r}static fromJSON(e){if("string"!=typeof e)throw new TypeError("`json` must be a string.");const t=JSON.parse(e);return ri.fromObject(t)}}const ii=ri,si=class{#Rs=null;#js=null;get sender(){return this.#Rs}get receiver(){return this.#js}set sender(e){if(!(e instanceof ii&&this.receiver instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#Rs=e}set receiver(e){if(!(this.sender instanceof ii&&e instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#js=e}constructor(e,t){if(e||t){if(!(e instanceof ii&&t instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.connect(e,t)}}connect(e,t){if(!(e instanceof ii&&t instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#Rs=e,this.#js=t}disconnect(){this.#Rs=null,this.#js=null}invert(){const e=this.#Rs,t=this.#js;this.#Rs=t,this.#js=e}transferItem({slotIndex:e,specialSlot:t,quantity:r=1,receiverSlotIndex:i,forceSpace:s=!1,strict:n=!1}){if(!this.#Rs||!this.#js)throw new Error("Sender and receiver inventories must be connected.");let o;if(t){if(o=this.#Rs.getSpecialItem(t),!o)throw new Error(`No item found in sender special slot '${t}'.`)}else{if("number"!=typeof e)throw new Error("Must provide either slotIndex or specialSlot.");if(o=this.#Rs.getItemFrom(e),!o)throw new Error(`No item found in sender slot ${e}.`)}if(o.quantity<r)throw new Error(`Sender does not have enough quantity of '${o.id}' to transfer.`);const a={id:o.id,quantity:r,metadata:o.metadata};let l;if(n)if("number"==typeof i){const e=this.#js.existsItemAt(i)?this.#js.getItemFrom(i):null;if(e){if(e.id!==a.id)throw new Error(`Receiver slot ${i} contains a different item.`);const t=ii.getItem(e.id).maxStack-e.quantity;if(a.quantity>t)throw new Error(`Strict mode: not enough space in receiver slot ${i}.`)}}else if(this.#js.clone().addItem({itemId:a.id,quantity:a.quantity,metadata:a.metadata,forceSpace:s}).remaining>0)throw new Error("Strict mode: not enough space in receiver inventory.");if("number"==typeof i){const e=this.#js.existsItemAt(i)?this.#js.getItemFrom(i):null;let t=a.quantity;if(e){if(e.id!==a.id)throw new Error(`Receiver slot ${i} contains a different item.`);const r=ii.getItem(e.id).maxStack-e.quantity;t=Math.min(r,a.quantity),t>0&&this.#js.setItem({slotIndex:i,item:{...e,quantity:e.quantity+t},forceSpace:s})}else this.#js.setItem({slotIndex:i,item:a,forceSpace:s});l={remaining:a.quantity-t}}else l=this.#js.addItem({itemId:a.id,quantity:a.quantity,metadata:a.metadata,forceSpace:s});const h=a.quantity-l.remaining;if(h>0)if(t)this.#Rs.unequipItem({slotId:t,quantity:h,forceSpace:s});else if("number"==typeof e){const t=o.quantity-h;this.#Rs.setItem({slotIndex:e,item:t>0?{...o,quantity:t}:null,forceSpace:s})}return l}transferMultiple(e){return e.map(e=>this.transferItem(e))}},ni=class{#Os;#vt={message:"We use cookies to improve your experience.",acceptText:"Accept All",rejectText:"Reject All",settingsText:"Manage Settings",categories:[],storageKey:"cookie-consent-preferences",onSave:e=>console.log("Preferences saved:",e),animationDuration:400,renderBar:null,renderModal:null};get preferences(){const e=localStorage.getItem(this.#vt.storageKey);return e?JSON.parse(e):{}}get config(){return{...this.#vt,categories:[...this.#vt.categories]}}set config(e){this.validateConfig(e),this.#vt=Object.assign(this.#vt,e)}constructor(e){if(!e||"object"!=typeof e)throw new TypeError("Config must be an object.");this.config=e;const t=this.loadPreferences();this.#Os=t??{},t||this.showConsentBar()}validateConfig(e){if(void 0!==e.message&&"string"!=typeof e.message)throw new TypeError("Config.message must be a string.");if(["acceptText","rejectText","settingsText","storageKey"].forEach(t=>{if(void 0!==e[t]&&"string"!=typeof e[t])throw new TypeError(`Config.${t} must be a string.`)}),void 0!==e.categories){if(!Array.isArray(e.categories))throw new TypeError("Config.categories must be an array of Category objects.");e.categories.forEach((e,t)=>this.validateCategory(e,t))}if(void 0!==e.onSave&&"function"!=typeof e.onSave)throw new TypeError("Config.onSave must be a function.");if(void 0!==e.animationDuration&&("number"!=typeof e.animationDuration||e.animationDuration<0))throw new TypeError("Config.animationDuration must be a positive number.");if(void 0!==e.renderBar&&null!==e.renderBar&&"function"!=typeof e.renderBar)throw new TypeError("Config.renderBar must be a function or null.");if(void 0!==e.renderModal&&null!==e.renderModal&&"function"!=typeof e.renderModal)throw new TypeError("Config.renderModal must be a function or null.")}validateCategory(e,t){if(!e||"object"!=typeof e)throw new TypeError(`Category at index ${t} must be an object.`);if("string"!=typeof e.label)throw new TypeError(`Category.label at index ${t} must be a string.`);if("boolean"!=typeof e.required)throw new TypeError(`Category.required at index ${t} must be a boolean.`);if("boolean"!=typeof e.default)throw new TypeError(`Category.default at index ${t} must be a boolean.`)}loadPreferences(){const e=localStorage.getItem(this.#vt.storageKey);return e?JSON.parse(e):null}removeWithAnimation(e){if(!(e instanceof HTMLElement))throw new TypeError("removeWithAnimation expects an HTMLElement.");e.classList.add("closing"),setTimeout(()=>e.remove(),this.#vt.animationDuration)}savePreferences(e){if(!e||"object"!=typeof e)throw new TypeError("Preferences must be an object.");localStorage.setItem(this.#vt.storageKey,JSON.stringify(e)),this.#vt.onSave(e)}showConsentBar(){const e=document.createElement("div");e.className="cookie-consent-bar",e.innerHTML=this.#vt.renderBar?this.#vt.renderBar(this.#vt):`\n <div><p>${this.#vt.message}</p></div>\n <div><button class="accept">${this.#vt.acceptText}</button></div>\n <div><button class="reject">${this.#vt.rejectText}</button></div>\n <div><button class="settings">${this.#vt.settingsText}</button></div>\n `,document.body.appendChild(e);const t=e.querySelector(".accept");t instanceof HTMLElement&&(t.onclick=()=>{const t={};this.#vt.categories.forEach(e=>t[e.label]=!0),this.savePreferences(t),this.removeWithAnimation(e)});const r=e.querySelector(".reject");r instanceof HTMLElement&&(r.onclick=()=>{const t={};this.#vt.categories.forEach(e=>t[e.label]=e.required),this.savePreferences(t),this.removeWithAnimation(e)});const i=e.querySelector(".settings");i instanceof HTMLElement&&(i.onclick=()=>this.showSettingsModal(e))}showSettingsModal(e){const t=document.createElement("div");t.className="cookie-consent-modal",t.innerHTML=this.#vt.renderModal?this.#vt.renderModal(this.#vt):`\n <div class="modal-content">\n <h2>Cookie Settings</h2>\n <form class="settings-form">\n ${this.#vt.categories.map(e=>`\n <label>\n <input type="checkbox" name="${e.label}" \n ${e.default?"checked":""} \n ${e.required?"disabled":""}>\n ${e.label}\n </label>\n `).join("")}\n </form>\n <button class="save">Save Preferences</button>\n </div>\n `,document.body.appendChild(t);const r=t.querySelector(".save");r instanceof HTMLElement&&(r.onclick=()=>{const r={};t.querySelectorAll("input[type=checkbox]").forEach(e=>{e instanceof HTMLInputElement&&(r[e.name]=e.checked)}),this.savePreferences(r),this.removeWithAnimation(t),e&&this.removeWithAnimation(e)})}isAllowed(e){if("string"!=typeof e)throw new TypeError("isAllowed expects a string as category.");return!!this.#Os&&!!this.#Os[e]}};var oi=r(942),ai=r(913);const li=le("TinyI18");class hi{static#$s=null;static#Hs=null;static#Fs=null;static#zs=null;static set _join(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_join" must be a function');if(null!==hi.#$s)throw new Error('TinyI18: "_join" has already been set');hi.#$s=e}static set _existsSync(e){if("function"!=typeof e&&!1!==e)throw new TypeError('TinyI18: "_existsSync" must be a function or false');if(null!==hi.#Hs)throw new Error('TinyI18: "_existsSync" has already been set');hi.#Hs=e}static set _readFile(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_readFile" must be a function');if(null!==hi.#Fs)throw new Error('TinyI18: "_readFile" has already been set');hi.#Fs=e}static set _writeFile(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_writeFile" must be a function');if(null!==hi.#zs)throw new Error('TinyI18: "_writeFile" has already been set');hi.#zs=e}static async mergeLocaleFiles({files:e,output:t,spaces:r=0}){if(null===hi.#Hs||null===hi.#Fs||null===hi.#zs)throw new Error('TinyI18: "mergeLocaleFiles" requires "_existsSync", "_readFile", and "_writeFile" to be set');if("number"!=typeof r||Number.isNaN(r)||r<0)throw new TypeError('mergeLocaleFiles: "spaces" must be a non-negative number');if(!Array.isArray(e)||0===e.length)throw new TypeError('mergeLocaleFiles: "files" must be a non-empty array of file paths');if("string"!=typeof t||!t)throw new TypeError('mergeLocaleFiles: "output" must be a non-empty string path');const i={};for(const t of e){if("string"!=typeof t||!t)throw new TypeError("mergeLocaleFiles: each file path must be a non-empty string");if(!1!==hi.#Hs&&!hi.#Hs(t))throw new Error(`mergeLocaleFiles: file "${t}" does not exist`);const e=await hi.#Fs(t,"utf-8");let r;try{r=JSON.parse(e)}catch(e){throw new Error(`mergeLocaleFiles: file "${t}" is not valid JSON`)}Object.assign(i,r)}await hi.#zs(t,JSON.stringify(i,null,r),"utf-8")}#u=!1;get destroyed(){return this.#u}#Bs;#Ws;#qs=null;#Vs;#Us=!1;#Ks=null;#Js=new Map;#Gs=new Map;#Ys=new Map;#Xs=new Map;get currentLocale(){return li(this.#u),this.#qs}get defaultLocale(){return li(this.#u),this.#Ws}get mode(){return li(this.#u),this.#Bs}get strict(){return li(this.#u),this.#Vs}get acceptNullResults(){return li(this.#u),this.#Us}get basePath(){return li(this.#u),this.#Ks}get stats(){li(this.#u);const e=[];for(const t of this.#Js.keys())e.push(this.getStatsForLocale(t));return e}get stringTables(){li(this.#u);const e={};for(const[t,r]of this.#Js.entries())e[t]=this.#Qs(r);return e}get patternTables(){li(this.#u);const e={};for(const[t,r]of this.#Gs.entries())e[t]=r.map(e=>({$pattern:new RegExp(e.$pattern.source,e.$pattern.flags),value:this.#Qs(e.value),elseValue:this.#Qs(e.elseValue)}));return e}get helpers(){li(this.#u);const e={};for(const[t,r]of this.#Ys.entries())e[t]=r;return e}get regexCache(){li(this.#u);const e={};for(const[t,r]of this.#Xs.entries())e[t]=new RegExp(r.source,r.flags);return e}#Qs(e){if(null==e||"string"==typeof e||"function"==typeof e||"number"==typeof e)return e;if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e))return e.map(e=>this.#Qs(e));if("object"==typeof e){const t={};for(const[r,i]of Object.entries(e))t[r]=this.#Qs(i);return t}return e}#Zs(e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('#resolveOrder: "forceLocale" must be a string if provided');const t=[];return e&&"string"==typeof e&&this.#Js.has(e)?t.push(e):this.#qs&&t.push(this.#qs),t.push(this.#Ws),t}#en(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError('#resolveExact: "order" must be an array of strings');if("string"!=typeof t||!t)throw new TypeError('#resolveExact: "key" must be a non-empty string');for(const r of e){const e=this.#Js.get(r);if(e&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}}#tn(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError('#resolveByPattern: "order" must be an array of strings');if("string"!=typeof t||!t)throw new TypeError('#resolveByPattern: "key" must be a non-empty string');for(const r of e){const e=this.#Gs.get(r)||[];for(const r of e)return r.$pattern.test(t)?r.value:r.elseValue??void 0}}#rn(e,t){if(null==e){if(this.#Vs)throw new TypeError('#materialize: "value" cannot be null or undefined');return""}if("string"==typeof e)return this.#in(e,t);if("function"==typeof e)return e(t??{},this.#sn());if(e&&"object"==typeof e&&"string"==typeof e.$fn){const r=this.#Ys.get(e.$fn);if("function"!=typeof r){if(this.#Vs)throw new Error(`TinyI18: helper "${e.$fn}" is not registered`);return""}return r({...t??{},args:void 0!==e.args?e.args:void 0},this.#sn())}if(this.#Vs)throw new Error("TinyI18: unsupported entry type");return""}#in(e,t){if("string"!=typeof e)throw new TypeError('#interpolate: "template" must be a string');if(void 0!==t&&(null===t||"object"!=typeof t))throw new TypeError('#interpolate: "params" must be an object if provided');return t&&"object"==typeof t?e.replace(/\{([a-zA-Z0-9_.$-]+)\}/g,(e,r)=>{const i=this.#nn(t,r);return null==i?"":String(i)}):e}#nn(e,t){if(!e||"object"!=typeof e)throw new TypeError('#dotGet: "obj" must be an object');if("string"!=typeof t||!t)throw new TypeError('#dotGet: "path" must be a non-empty string');const r=t.split(".");let i=e;for(const e of r){if(null==i)return;i=i[e]}return i}#sn(){return{has:e=>this.#Ys.has(e),call:(e,t,r)=>{const i=this.#Ys.get(e);if("function"!=typeof i)throw new Error(`Helper "${e}" not found`);return i(t,r??{})}}}#on(e,t){if("string"!=typeof e||!e)throw new TypeError('#ingestLocale: "locale" must be a non-empty string');if(!t||"object"!=typeof t)throw new TypeError('#ingestLocale: "raw" must be an object');if("string"!=typeof e||!e)throw new TypeError("#ingestLocale: invalid locale");if(!t||"object"!=typeof t)throw new TypeError('#ingestLocale: "raw" must be an object');const r={...this.#Js.get(e)??{}},i=[...this.#Gs.get(e)??[]],s=(e,t)=>{if(null!=t)if("string"==typeof t||"function"==typeof t||t&&"object"==typeof t&&"string"==typeof t.$fn){if(!e)throw new TypeError("Leaf value requires a key path");r[e]=t}else if(t&&"object"==typeof t){if(t.$pattern instanceof RegExp&&Object.prototype.hasOwnProperty.call(t,"value"))return void i.push({$pattern:t.$pattern,value:t.value,elseValue:t.elseValue});for(const[r,i]of Object.entries(t))s(e?`${e}.${r}`:r,i)}};s("",t),this.#Js.set(e,r),this.#Gs.set(e,i),this.#Js.has(this.#Ws)||(this.#Js.set(this.#Ws,{}),this.#Gs.set(this.#Ws,[]))}#an(e){if("string"!=typeof e||!e)throw new TypeError('#unloadLocale: "locale" must be a non-empty string');e!==this.#Ws&&(this.#Js.delete(e),this.#Gs.delete(e))}async#ln(e){if(null===hi.#$s||null===hi.#Fs)throw new Error('TinyI18: "file" mode requires "_join" and "_readFile" to be set');if("string"!=typeof e||!e)throw new TypeError('#loadLocaleFromFile: "locale" must be a non-empty string');if("string"!=typeof this.#Ks||!this.#Ks)throw new TypeError('#loadLocaleFromFile: "this.#basePath" must be a non-empty string');const t=hi.#$s(this.#Ks,`${e}.json`);let r;try{const e=await hi.#Fs(t,"utf8");r=JSON.parse(e)}catch(r){if(!(r instanceof Error))return;if(this.#Vs)throw new Error(`TinyI18: failed to load or parse ${t}: ${r.message}`);return this.#Js.set(e,{}),void this.#Gs.set(e,[])}const i={...this.#Js.get(e)??{}},s=[...this.#Gs.get(e)??[]],n=(e,t)=>{if(null!=t){if(t&&"object"==typeof t&&"string"==typeof t.$pattern&&Object.prototype.hasOwnProperty.call(t,"value")){const e=this.#hn(t.$pattern);return void s.push({$pattern:e,value:this.#un(t.value),elseValue:this.#un(t.elseValue)})}if("string"==typeof t||t&&"object"==typeof t&&"string"==typeof t.$fn){if(!e)throw new TypeError("Leaf value requires a key path");i[e]=this.#un(t)}else if(t&&"object"==typeof t)for(const[r,i]of Object.entries(t))n(e?`${e}.${r}`:r,i)}};n("",r),this.#Js.set(e,i),this.#Gs.set(e,s)}#hn(e){if("string"!=typeof e||!e)throw new TypeError('#safeRegExp: "src" must be a non-empty string');const t=this.#Xs.get(e);if(t)return t;try{const t=new RegExp(e);return this.#Xs.set(e,t),t}catch{if(this.#Vs)throw new Error(`TinyI18: invalid regex "${e}" in file`);return/^$/}}#un(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"string"==typeof e.$fn)return{$fn:String(e.$fn),args:e.args};if(this.#Vs)throw new Error("TinyI18: unsupported value in file JSON");return""}constructor(e){if(!e||"object"!=typeof e)throw new TypeError("TinyI18: options must be an object");const{mode:t,defaultLocale:r,basePath:i,localResources:s,strict:n=!0,acceptNullResults:o=!1}=e;if("local"!==t&&"file"!==t)throw new TypeError('TinyI18: "mode" must be "local" or "file"');if("string"!=typeof r||!r)throw new TypeError('TinyI18: "defaultLocale" must be a non-empty string');if("boolean"!=typeof n)throw new TypeError('TinyI18: "strict" must be a boolean');if("boolean"!=typeof o)throw new TypeError('TinyI18: "acceptNullResults" must be a boolean');if("file"===t){if("string"!=typeof i||!i)throw new TypeError('TinyI18: "basePath" is required in file mode');this.#Ks=i}if(this.#Bs=t,this.#Ws=r,this.#Vs=n,this.#Us=o,"local"===t&&s&&"object"==typeof s)for(const[e,t]of Object.entries(s))this.#on(e,t);this.#Js.has(this.#Ws)||(this.#Js.set(this.#Ws,{}),this.#Gs.set(this.#Ws,[]))}clearRegexCache(){li(this.#u),this.#Xs.clear()}registerHelper(e,t){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('registerHelper: "name" must be non-empty string');if("function"!=typeof t)throw new TypeError('registerHelper: "fn" must be a function');this.#Ys.set(e,t)}unregisterHelper(e){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('unregisterHelper: "name" must be a non-empty string');return this.#Ys.delete(e)}loadLocaleLocal(e,t){if(li(this.#u),"local"!==this.#Bs)throw new TypeError('loadLocaleLocal is only available in "local" mode');this.#on(e,t)}async setLocale(e){if(li(this.#u),null!==e&&("string"!=typeof e||!e))throw new TypeError('setLocale: "locale" must be string or null');const t=this.#qs;null!==e&&("file"===this.#Bs?await this.#ln(e):this.#Js.has(e)||(this.#Js.set(e,{}),this.#Gs.set(e,[]))),"file"===this.#Bs&&t&&t!==this.#Ws&&t!==e&&this.#an(t),this.#qs=e}t(e,t=void 0,r=void 0){return this.get(e,t,r)}get(e,t=void 0,r=void 0){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('get: "key" must be a non-empty string');const{locale:i}=r||{},s=this.#Zs(i);let n=this.#en(s,e);if(void 0===n){if(this.#Vs)throw new Error(`TinyI18: missing translation for key "${e}"`);return this.#Us?null:e}return this.#rn(n,t)}p(e,t){return this.resolveByPattern(e,t)}resolveByPattern(e,t){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('get: "key" must be a non-empty string');const{locale:r}=t||{},i=this.#Zs(r);let s=this.#tn(i,e);if(void 0===s){if(this.#Vs)throw new Error(`TinyI18: missing translation for key "${e}"`);return this.#Us?null:e}return s}resetToDefaultOnly(){if(li(this.#u),"file"===this.#Bs)for(const e of Array.from(this.#Js.keys()))e!==this.#Ws&&this.#an(e);this.#qs=null}getStatsForLocale(e){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('getStatsForLocale: "locale" must be a non-empty string');if(!this.#Js.has(e))throw new Error(`getStatsForLocale: locale "${e}" is not registered`);return{locale:e,strings:Object.keys(this.#Js.get(e)??{}).length,patterns:this.#Gs.get(e)?.length??0,isDefault:e===this.#Ws,isCurrent:e===this.#qs}}destroy(){this.#u||(this.#Js.clear(),this.#Gs.clear(),this.#Ys.clear(),this.#Xs.clear(),this.#qs=null,this.#Ks=null,this.#u=!0)}}const ui=hi;class ci extends ui{constructor(e){super(e)}}ci._join=(...e)=>(0,t().join)(...e),ci._existsSync=(...e)=>(0,ai.existsSync)(...e),ci._readFile=(...e)=>(0,oi.readFile)(...e),ci._writeFile=(...e)=>(0,oi.writeFile)(...e);const di=ci;class pi{#cn=new Map;#dn;#pn;#mn;get factors(){const e={};for(let[t,r]of this.#cn.entries())e[t]={...r};return e}get currentPercent(){return this.#pn/this.#dn*100}set maxValue(e){if("number"!=typeof e||Number.isNaN(e)||e<=0)throw new TypeError("maxValue must be a positive number.");this.#dn=e,this.#pn=Math.min(this.#pn,e)}get maxValue(){return this.#dn}get currentValue(){return this.#pn}set infiniteValue(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("infiniteValue must be a number.");this.#mn=e,this.#pn=Math.max(0,e),this.#pn=Math.min(this.#pn,this.#dn)}get infiniteValue(){return this.#mn}constructor(e=100,t=1,r=1){if("number"!=typeof e||Number.isNaN(e)||e<=0)throw new TypeError("maxValue must be a positive number.");this.#dn=e,this.setFactor("main",t,r),this.#pn=e,this.#mn=e}getFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");const t=this.#cn.get(e);if(!t)throw new Error(`Factor with key "${e}" not found.`);return{...t}}hasFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");return this.#cn.has(e)}setFactor(e,t,r=1){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");if("number"!=typeof t||Number.isNaN(t))throw new TypeError("Amount must be a valid number.");if("number"!=typeof r||Number.isNaN(r))throw new TypeError("Multiplier must be a valid number.");this.#cn.set(e,{amount:t,multiplier:r})}removeFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");return this.#cn.delete(e)}#fn(e){const t=this.#mn;return this.#mn-=e,this.#pn=Math.max(0,this.#pn-e),{prevValue:t,removedTotal:e,removedPercent:e/this.#dn*100,currentPercent:this.currentPercent,remainingValue:this.#pn,infiniteRemaining:this.#mn}}tick(){let e=0;for(let[t,r]of this.#cn.entries())e+=r.amount*r.multiplier;return this.#fn(e)}tickWithTempFactor(e){if("object"!=typeof e||null===e)throw new TypeError("You must provide a valid factor object.");if("number"!=typeof e.amount||Number.isNaN(e.amount))throw new TypeError('Temp factor "amount" must be a valid number.');if("multiplier"in e&&("number"!=typeof e.multiplier||Number.isNaN(e.multiplier)))throw new TypeError('Temp factor "multiplier" must be a valid number if provided.');let t=0;for(let[e,r]of this.#cn.entries())t+=r.amount*r.multiplier;return e&&(t+=e.amount*(e.multiplier??1)),this.#fn(t)}tickSingleFactor(e){if("object"!=typeof e||null===e)throw new TypeError("You must provide a valid factor object.");if("number"!=typeof e.amount||Number.isNaN(e.amount))throw new TypeError('Temp factor "amount" must be a valid number.');if("multiplier"in e&&("number"!=typeof e.multiplier||Number.isNaN(e.multiplier)))throw new TypeError('Temp factor "multiplier" must be a valid number if provided.');if(!e)throw new Error("You must provide a factor to apply.");const t=e.amount*(e.multiplier??1);return this.#fn(t)}toJSON(){return{maxValue:this.#dn,currentValue:this.#pn,infiniteValue:this.#mn,factors:this.factors}}static fromJSON(e){const t=new pi(e.maxValue,0,0);t.infiniteValue=e.infiniteValue,t.#cn.clear();for(const[r,i]of Object.entries(e.factors))t.setFactor(r,i.amount,i.multiplier);return t}clone(){return pi.fromJSON(this.toJSON())}clearFactors(){this.#cn.clear()}}const mi=pi;class fi{static _safeEvaluate(e){if(!/^[\d+\-*/%.()\s^]+$/.test(e))throw new Error(`Invalid characters in expression: "${e}"`);const t=e.replace(/\^/g,"**");try{return Function(`"use strict"; return (${t})`)()}catch(t){if(!(t instanceof Error))throw new Error("Unknown Error");throw new Error(`Invalid expression "${e}": ${t.message}`)}}static replaceValues(e,t){let r=0;return e.replace(/(\d*)d(\d+)/g,(e,i)=>{const s=i?Number(i):1;let n=0;for(let e=0;e<s;e++){const e=t[r++];n+=void 0!==e?e:0}return String(n)})}static tokenizeValues(e,t){const r=fi.replaceValues(e,t),i=[],s=/\d+|[()+\-*/]/g;let n;for(;null!==(n=s.exec(r));)/^\d+$/.test(n[0])?i.push(Number(n[0])):i.push(n[0]);return{tokens:i,text:r}}static parseString(e){if("string"!=typeof e)throw new TypeError("Input must be a string.");const t=e.split(",").map(e=>e.trim()).filter(Boolean),r=[],i=[];if(t.forEach((e,t)=>{const s=/\b(?:(\d+)?d(\d+))\b/g;let n;const o=[],a=e.replace(/\(([^()]+?\|[^()]+?)\)/g,(e,t)=>{const r="string"==typeof t?t.split("|").map(e=>e.trim()).filter(Boolean):[];if(0===r.length)throw new Error(`Invalid random-choice group: "${e}"`);return r[Math.floor(Math.random()*r.length)]});for(;null!==(n=s.exec(a));){const e=parseInt(n[1]||"1",10),r=parseInt(n[2],10);if(isNaN(r))throw new Error(`Invalid dice sides in expression "${n[0]}" at position ${t+1}.`);o.push({count:e,sides:r})}if(0===o.length&&Number.isNaN(parseFloat(a)))throw new Error(`Invalid dice expression at position ${t+1}: "${e}"`);r.push(...o),i.push({index:t,original:e,expression:a})}),0===r.length)throw new Error("Invalid dice amount.");return{sides:r,modifiers:i}}static applyModifiers(e,t){if(!Array.isArray(e)||!e.every(e=>"number"==typeof e&&!Number.isNaN(e)||v(e)&&"number"==typeof e.value&&!Number.isNaN(e.value)&&"number"==typeof e.sides&&!Number.isNaN(e.sides)))throw new TypeError("Bases must be a valid numbers.");if(!Array.isArray(t))throw new TypeError("Modifiers must be an array of modifier objects.");let r=0;const i=[],s=[...e];for(const e in t){const n=t[e];if("string"!=typeof n.expression)throw new Error("Each modifier must include an expression string.");const o=n.original,a=n.expression,l=[],h=[],u=[],c=e=>e.match(/\(\s*[^()]+\|\s*[^()]+\s*\)|\b\d*d\d+\b|[-+]?\d+(?:\.\d+)?|[+\-*/%^()]/g)||[],d=c(a),p=c(o),m=[...d],f=[],y=a.replace(/\b\d*d\d+\b/g,e=>{const t=e.split("d"),r=()=>{for(const t in d)if(d[t]===e&&f.indexOf(t)<0){f.push(t),u.push(Number(t));break}},i=e=>{if(e.value>e.sides)throw new Error(`Invalid dice roll: value (${e.value}) must be between 1 and ${e.sides}.`)};if(0===t[0].trim().length){const t=s.shift(),n="number"==typeof t?t:v(t)?t.value:0;v(t)&&i(t),l.push([n]);for(const t in m)if(m[t]===e){m[t]=String(n),h.push(Number(t));break}return r(),n}const n=[],o=Number(t[0]),a=["("];let c="(";for(let e=0;e<o;e++){const t=s.shift(),r="number"==typeof t?t:v(t)?t.value:0;v(t)&&i(t),a.push(String(r));const l=e<o-1?" + ":")";a.push(l),c+=`${r}${l}`,n.push(r)}for(const t in m){const r=Number(t);if(m[r]===e){m.splice(r,1,...a);let e=1;for(let t=0;t<o;t++)h.push(r+t+e),e++;break}}return l.push(n),r(),c});let g;try{g=fi._safeEvaluate(y)}catch(e){if(!(e instanceof Error))throw new Error("Unknown Error");throw new Error(`Error evaluating expression "${y}" (from "${a}"): ${e.message}`)}i.push({rawTokensP:d,rawTokens:p,tokens:m,rawDiceTokenSlots:u,diceTokenSlots:h,dicesResult:l,total:g}),r+=g}return{final:r,steps:i}}static rollArrayIndex(e){const t=Array.isArray(e),r=e instanceof Set;if(!t&&!r)throw new TypeError("rollArrayIndex expects an array or Set.");return Math.floor(Math.random()*(t?e.length:e.size))}#dn;#yn;get maxValue(){return this.#dn}set maxValue(e){if(!Number.isInteger(e)||e<0)throw new TypeError("maxValue must be an integer greater than -1.");this.#dn=e}get allowZero(){return this.#yn}set allowZero(e){if("boolean"!=typeof e)throw new TypeError("allowZero must be a boolean.");this.#yn=e}constructor({maxValue:e,allowZero:t=!0}){if("boolean"!=typeof t)throw new TypeError("allowZero must be an boolean.");if(!Number.isInteger(e)||e<0)throw new TypeError("maxValue must be an integer greater than -1.");this.#dn=e,this.#yn=t}roll(){const e=this.#yn?0:1;return Math.floor(Math.random()*(this.#dn-e+1))+e}}const yi=fi,gi=class{#S=null;get overlay(){return this.#S}#gn=null;get messageElement(){return this.#gn}#j;get container(){return this.#j}#wn={fadeIn:null,fadeOut:null,zIndex:9999};get options(){return{...this.#wn}}set options(e){if("object"!=typeof e||null===e)throw new TypeError("options must be an object");if(void 0!==e.fadeIn&&null!==e.fadeIn&&("number"!=typeof e.fadeIn||e.fadeIn<0))throw new TypeError("fadeIn must be a non-negative number or null");if(void 0!==e.fadeOut&&null!==e.fadeOut&&("number"!=typeof e.fadeOut||e.fadeOut<0))throw new TypeError("fadeOut must be a non-negative number or null");if(void 0!==e.zIndex&&("number"!=typeof e.zIndex||!Number.isInteger(e.zIndex)))throw new TypeError("zIndex must be an integer number");this.#wn={fadeIn:e.fadeIn??null,fadeOut:e.fadeOut??null,zIndex:e.zIndex??9999}}#bn="none";get status(){return this.#bn}#vn="";get defaultMessage(){return this.#vn}set defaultMessage(e){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("defaultMessage must be a string or an HTMLElement");this.#vn=e}#En=null;get message(){return this.#En}#Tn=!1;get allowHtmlText(){return this.#Tn}set allowHtmlText(e){if("boolean"!=typeof e)throw new TypeError("allowHtmlText must be a boolean");this.#Tn=e}#Sn=null;get fadeInTimeout(){return null!==this.#Sn}#xn=null;get fadeOutTimeout(){return null!==this.#xn}get visible(){return!!this.#S}#An=null;get onChange(){return this.#An}set onChange(e){if(null!==e&&"function"!=typeof e)throw new TypeError("onChange must be a function or null");this.#An=e}_emitChange(){"function"==typeof this.#An&&this.#An(this.#bn)}constructor(e=document.body){if(!(e instanceof HTMLElement))throw new TypeError("container must be an HTMLElement");this.#j=e}_updateMessage(e=this.#vn){if(!this.#gn)throw new Error("messageElement is not initialized");if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");if(this.#En=e,"string"==typeof e)this.#Tn?this.#gn.innerHTML=e:this.#gn.textContent=e;else{if(!this.#Tn)throw new Error("HTMLElement messages require allowHtmlText = true");this.#gn.textContent="",this.#gn.appendChild(e)}}_removeOldClasses(){this.#S?.classList.remove("active"),this.#S?.classList.remove("fadeIn"),this.#S?.classList.remove("fadeOut")}start(e=this.#vn){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");if(!this.#S){this.#S=document.createElement("div"),this.#S.classList.add("loading-overlay"),this.#S.style.zIndex=String(this.#wn.zIndex);const t=document.createElement("div");t.classList.add("loading-container");const r=document.createElement("div");r.classList.add("loading-content");const i=document.createElement("div");i.classList.add("loading-spinner"),this.#gn=document.createElement("div"),this.#gn.classList.add("loading-message"),r.appendChild(i),r.appendChild(this.#gn),t.appendChild(r),this.#S.appendChild(t),this.#j.appendChild(this.#S),this._removeOldClasses(),this.#bn="fadeIn",this.#S.classList.add("fadeIn"),this._emitChange();const s=()=>{this._removeOldClasses(),this.#Sn=null,this.#bn="active",this.#S?.classList.add("active"),this._emitChange()};return"number"==typeof this.#wn.fadeIn?(this.#Sn&&clearTimeout(this.#Sn),this.#Sn=setTimeout(s,this.#wn.fadeIn)):s(),this._updateMessage(e),!0}return this.#gn&&this._updateMessage(e),!1}update(e=this.#vn){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");return!!this.#gn&&(this._updateMessage(e),!0)}stop(){if(this.#S){this._removeOldClasses(),this.#bn="fadeOut",this.#S.classList.add("fadeOut"),this._emitChange();const e=()=>{this._removeOldClasses(),this.#xn=null,this.#bn="none",this.#S?.remove(),this.#S=null,this.#gn=null,this.#En=null,this._emitChange()};return"number"==typeof this.#wn.fadeOut?(this.#xn&&clearTimeout(this.#xn),this.#xn=setTimeout(e,this.#wn.fadeOut)):e(),!0}return!1}};class wi{static#Cn=/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;static#In=/^#([A-Fa-f0-9]{8})$/;static#Dn="(0|1|0?\\.\\d+)";static#kn="(0|[1-9]\\d?|1\\d{2}|2[0-4]\\d|25[0-5])";static#Mn="(0|[1-9]\\d?|[1-2]\\d{2}|3[0-5]\\d|360)";static#Ln="(0|[1-9]?\\d|100)";static#Nn=new RegExp(`^rgb\\(\\s*${wi.#kn}\\s*,\\s*${wi.#kn}\\s*,\\s*${wi.#kn}\\s*\\)$`);static#_n=new RegExp(`^rgba\\(\\s*${wi.#kn}\\s*,\\s*${wi.#kn}\\s*,\\s*${wi.#kn}\\s*,\\s*${wi.#Dn}\\s*\\)$`);static#Pn=new RegExp(`^hsl\\(\\s*${wi.#Mn}\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#Ln}%\\s*\\)$`);static#Rn=new RegExp(`^hsla\\(\\s*${wi.#Mn}\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#Dn}\\s*\\)$`);static#jn=new RegExp(`^hwb\\(\\s*${wi.#Mn}(deg|grad|rad|turn)?\\s*${wi.#Ln}%\\s*${wi.#Ln}%\\s*\\)$`);static#On="(-?\\d+)";static#$n=new RegExp(`^lab\\(\\s*${wi.#Ln}%?\\s*${wi.#On}%?\\s*${wi.#On}%?\\s*\\)$`);static#Hn=new RegExp(`^lch\\(\\s*${wi.#Ln}%?\\s*${wi.#Ln}%?\\s*${wi.#Mn}(deg|grad|rad|turn)?\\s*\\)$`);static#Fn=new Set(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"]);static#zn=new Set(["transparent","currentColor"]);static getNames(){return Array.from(wi.#Fn)}static addName(e){const t=wi.#Fn.size;return wi.#Fn.add(e.toLowerCase()),wi.#Fn.size>t}static removeName(e){return wi.#Fn.delete(e.toLowerCase())}static hasName(e){return wi.#Fn.has(e.toLowerCase())}static getSpecialNames(){return Array.from(wi.#zn)}static addSpecialName(e){const t=wi.#zn.size;return wi.#zn.add(e),wi.#zn.size>t}static removeSpecialName(e){return wi.#zn.delete(e)}static hasSpecialName(e){return wi.#zn.has(e)}#Bn;get code(){return this.#Bn}#Wn;get type(){return this.#Wn}constructor(e){this.#Bn=e,this.#Wn=wi.isColor(this.#Bn)}static isHex(e){if("string"!=typeof e)throw new TypeError("isHex: input must be a string.");return wi.#Cn.test(e.trim())}isHex(){return wi.isHex(this.#Bn)}static isHexa(e){if("string"!=typeof e)throw new TypeError("isHexa: input must be a string.");return wi.#In.test(e.trim())}isHexa(){return wi.isHexa(this.#Bn)}static isRgb(e){if("string"!=typeof e)throw new TypeError("isRgb: input must be a string.");return wi.#Nn.test(e.trim())}isRgb(){return wi.isRgb(this.#Bn)}static isRgba(e){if("string"!=typeof e)throw new TypeError("isRgba: input must be a string.");return wi.#_n.test(e.trim())}isRgba(){return wi.isRgba(this.#Bn)}static isHsl(e){if("string"!=typeof e)throw new TypeError("isHsl: input must be a string.");return wi.#Pn.test(e.trim())}isHsl(){return wi.isHsl(this.#Bn)}static isHsla(e){if("string"!=typeof e)throw new TypeError("isHsla: input must be a string.");return wi.#Rn.test(e.trim())}isHsla(){return wi.isHsla(this.#Bn)}static isHwb(e){if("string"!=typeof e)throw new TypeError("isHwb: input must be a string.");return wi.#jn.test(e.trim())}isHwb(){return wi.isHwb(this.#Bn)}static isLab(e){if("string"!=typeof e)throw new TypeError("isLab: input must be a string.");return wi.#$n.test(e.trim())}isLab(){return wi.isLab(this.#Bn)}static isLch(e){if("string"!=typeof e)throw new TypeError("isLch: input must be a string.");return wi.#Hn.test(e.trim())}isLch(){return wi.isLch(this.#Bn)}static isName(e){if("string"!=typeof e)throw new TypeError("isName: input must be a string.");return wi.#Fn.has(e.trim().toLowerCase())}isName(){return wi.isName(this.#Bn)}static isSpecialName(e){if("string"!=typeof e)throw new TypeError("isSpecialName: input must be a string.");return wi.#zn.has(e.trim())}isSpecialName(){return wi.isSpecialName(this.#Bn)}static isColor(e){if("string"!=typeof e)throw new TypeError("isColor: input must be a string.");return wi.isHex(e)?"hex":wi.isHexa(e)?"hexa":wi.isRgb(e)?"rgb":wi.isRgba(e)?"rgba":wi.isHsl(e)?"hsl":wi.isHsla(e)?"hsla":wi.isHwb(e)?"hwb":wi.isLab(e)?"lab":wi.isLch(e)?"lch":wi.isName(e)?"name":wi.isSpecialName(e)?"specialName":null}parse(){switch(this.#Wn){case"hex":return wi.parseHex(this.code);case"hexa":return wi.parseHexa(this.code);case"rgb":return wi.parseRgb(this.code);case"rgba":return wi.parseRgba(this.code);case"hsl":return wi.parseHsl(this.code);case"hsla":return wi.parseHsla(this.code);case"hwb":return wi.parseHwb(this.code);case"lab":return wi.parseLab(this.code);case"lch":return wi.parseLch(this.code);case"name":case"specialName":return this.#Bn.trim().toLowerCase();default:return null}}static parseHex(e){if("string"!=typeof e)throw new TypeError("parseHex: input must be a string.");const t=new RegExp(wi.#Cn,"gm").exec(e.trim());return t?t[1]:null}parseHex(){return wi.parseHex(this.#Bn)}static parseHexa(e){if("string"!=typeof e)throw new TypeError("parseHexa: input must be a string.");const t=new RegExp(wi.#In,"gm").exec(e.trim());return t?t[1]:null}parseHexa(){return wi.parseHexa(this.#Bn)}static parseRgb(e){if("string"!=typeof e)throw new TypeError("parseRgb: input must be a string.");const t=new RegExp(wi.#Nn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseRgb(){return wi.parseRgb(this.#Bn)}static parseRgba(e){if("string"!=typeof e)throw new TypeError("parseRgba: input must be a string.");const t=new RegExp(wi.#_n,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])]:null}parseRgba(){return wi.parseRgba(this.#Bn)}static parseHsl(e){if("string"!=typeof e)throw new TypeError("parseHsl: input must be a string.");const t=new RegExp(wi.#Pn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseHsl(){return wi.parseHsl(this.#Bn)}static parseHsla(e){if("string"!=typeof e)throw new TypeError("parseHsla: input must be a string.");const t=new RegExp(wi.#Rn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])]:null}parseHsla(){return wi.parseHsla(this.#Bn)}static parseHwb(e){if("string"!=typeof e)throw new TypeError("parseHwb: input must be a string.");const t=new RegExp(wi.#jn,"gm").exec(e.trim());return t?[parseFloat(t[1]),t[2]??null,parseFloat(t[3]),parseFloat(t[4])]:null}parseHwb(){return wi.parseHwb(this.#Bn)}static parseLab(e){if("string"!=typeof e)throw new TypeError("parseLab: input must be a string.");const t=new RegExp(wi.#$n,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseLab(){return wi.parseLab(this.#Bn)}static parseLch(e){if("string"!=typeof e)throw new TypeError("parseLch: input must be a string.");const t=new RegExp(wi.#Hn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),t[4]??null]:null}parseLch(){return wi.parseLch(this.#Bn)}}const bi=wi,vi=le("TinyAnalogClock"),Ei=class{#qn;#Vn;#Un;#vt;#oi=null;#u=!1;get destroyed(){return this.#u}_getDate(){const e=new Date,t=e.getSeconds(),r=e.getMinutes(),i=e.getHours();return{now:e,s:t,m:r,h:i}}constructor(e={}){this.#vt={bgColor:"#f0f0f0",borderColor:"#333",borderWidth:8,markColor:"#333",hourHandColor:"#000",minuteHandColor:"#444",secondHandColor:"#d81c1c",textColor:"#000",skinUrl:null,showNumbers:!0,showSeconds:!0,size:800,sizeAdjust:.04,padding:45,angleDistance:.95,pwH:.008,phH:.08,pwM:.005,phM:.03,...e},this.#qn=document.createElement("div"),this.#qn.className="analog-clock-container",this.#qn.style.position="relative",this.#qn.style.borderRadius="50%",this.#qn.style.overflow="hidden",this.#qn.style.boxSizing="border-box",this.#Un=document.createElement("div"),this.#Un.style.position="absolute",this.#Un.style.inset="0",this.#Un.style.backgroundSize="cover",this.#Un.style.backgroundPosition="center",this.#Un.style.zIndex="0",this.#Vn=document.createElement("div"),this.#Vn.style.position="absolute",this.#Vn.style.inset="0",this.#Vn.style.zIndex="1",this.#Vn.style.pointerEvents="none";const t=document.createElement("div");t.style.position="absolute",t.style.inset="0",t.style.zIndex="2",t.style.pointerEvents="none",t.innerHTML='\n <div class="hand hour-hand"></div>\n <div class="hand minute-hand"></div>\n <div class="hand second-hand"></div>\n <div class="center-pin"></div>\n ',this.#qn.appendChild(this.#Un),this.#qn.appendChild(this.#Vn),this.#qn.appendChild(t);const r=document.createElement("style");r.textContent="\n .analog-clock-container .hand {\n position: absolute;\n bottom: 50%;\n left: 50%;\n transform-origin: bottom center;\n border-radius: 4px;\n transform: translateX(-50%) rotate(0deg);\n z-index: 5;\n }\n .analog-clock-container .center-pin {\n position: absolute;\n top: 50%; left: 50%;\n width: 12px; height: 12px;\n background: #333;\n border-radius: 50%;\n transform: translate(-50%, -50%);\n z-index: 10;\n }\n .analog-clock-container .clock-mark {\n position: absolute;\n top: 50%; left: 50%;\n background: currentColor;\n transform-origin: center center;\n }\n .analog-clock-container .clock-number {\n position: absolute;\n top: 50%; left: 50%;\n transform: translate(-50%, -50%);\n font-family: sans-serif;\n font-weight: bold;\n text-align: center;\n line-height: 1;\n }\n ",this.#qn.appendChild(r),this._applyConfig(),this._renderFace(),this._startTicker()}_applyConfig(){const e=this.#qn.style,t=this.#vt;e.width=`${t.size}px`,e.height=`${t.size}px`,e.border=`${t.borderWidth}px solid ${t.borderColor}`,e.backgroundColor=t.bgColor,t.skinUrl?(this.#Un.style.backgroundImage=`url(${t.skinUrl})`,this.#Un.style.display="block"):this.#Un.style.display="none";const r=e=>{const t=this.#qn.querySelector(e);if(!(t instanceof HTMLDivElement))throw new Error(`TinyAnalogClock: Element ${e} not found.`);return t},i=r(".hour-hand");i.style.backgroundColor=t.hourHandColor,i.style.width=.025*t.size+"px",i.style.height=.25*t.size+"px",i.style.marginLeft=.025*t.size/-2+"px",i.style.bottom="50%",i.style.left="50%",i.style.transformOrigin="bottom center";const s=r(".minute-hand");s.style.backgroundColor=t.minuteHandColor,s.style.width=.015*t.size+"px",s.style.height=.35*t.size+"px",s.style.marginLeft=.015*t.size/-2+"px";const n=r(".second-hand");t.showSeconds?(n.style.display="block",n.style.backgroundColor=t.secondHandColor,n.style.width=.005*t.size+"px",n.style.height=.4*t.size+"px",n.style.marginLeft=.005*t.size/-2+"px"):n.style.display="none",r(".center-pin").style.background=t.borderColor}_renderFace(){this.#Vn.innerHTML="";const e=this.#vt.size/2-this.#vt.borderWidth;for(let t=0;t<60;t++){const r=t%5==0,i=document.createElement("div");i.className="clock-mark";const s=r?this.#vt.size*this.#vt.pwH:this.#vt.size*this.#vt.pwM,n=r?this.#vt.size*this.#vt.phH:this.#vt.size*this.#vt.phM,o=this.#vt.markColor;i.style.width=`${s}px`,i.style.height=`${n}px`,i.style.color=o;const a=e-this.#vt.padding-n/2;i.style.transform=`translate(-50%, -50%) rotate(${6*t}deg) translate(0, -${a}px)`,this.#Vn.appendChild(i)}if(this.#vt.showNumbers)for(let t=1;t<=12;t++){const r=30*t*(Math.PI/180),i=e*this.#vt.angleDistance,s=e+Math.sin(r)*i,n=e-Math.cos(r)*i,o=document.createElement("div");o.className="clock-number",o.innerText=t.toString(),o.style.left=`${s}px`,o.style.top=`${n}px`,o.style.color=this.#vt.textColor,o.style.fontSize=this.#vt.size*this.#vt.sizeAdjust+"px",this.#Vn.appendChild(o)}}_startTicker(){if(this.#oi)return;const e=()=>{const{s:t,m:r,h:i}=this._getDate(),s=6*t,n=6*r+.1*t,o=i%12*30+.5*r,a=e=>{const t=this.#qn.querySelector(e);if(!(t instanceof HTMLDivElement))throw new Error(`${e} not found.`);return t};this.#qn.querySelector(".second-hand")&&(a(".second-hand").style.transform=`rotate(${s}deg)`),a(".minute-hand").style.transform=`rotate(${n}deg)`,a(".hour-hand").style.transform=`rotate(${o}deg)`,this.#oi=requestAnimationFrame(e)};e()}get element(){return vi(this.#u),this.#qn}set size(e){if(vi(this.#u),"number"!=typeof e||e<=0||isNaN(e))throw new Error(`TinyAnalogClock: 'size' must be a positive number. Received: ${e}`);this.#vt.size=e,this._applyConfig(),this._renderFace()}get size(){return vi(this.#u),this.#vt.size}set skinUrl(e){if(vi(this.#u),null!==e&&"string"!=typeof e)throw new Error("TinyAnalogClock: 'skin' must be a URL string or null. Received type: "+typeof e);this.#vt.skinUrl=e,this._applyConfig()}get skinUrl(){return vi(this.#u),this.#vt.skinUrl}set borderColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'borderColor' must be a non-empty string. Received: ${e}`);this.#vt.borderColor=e,this._applyConfig(),this._renderFace()}get borderColor(){return vi(this.#u),this.#vt.borderColor}set markColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'markColor' must be a non-empty string. Received: ${e}`);this.#vt.markColor=e,this._applyConfig(),this._renderFace()}get markColor(){return vi(this.#u),this.#vt.markColor}set textColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'textColor' must be a non-empty string. Received: ${e}`);this.#vt.textColor=e,this._applyConfig(),this._renderFace()}get textColor(){return vi(this.#u),this.#vt.textColor}set showNumbers(e){if(vi(this.#u),"boolean"!=typeof e)throw new Error("TinyAnalogClock: 'showNumbers' must be a boolean. Received type: "+typeof e);this.#vt.showNumbers=e,this._renderFace()}get showNumbers(){return vi(this.#u),this.#vt.showNumbers}set bgColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'bgColor' must be a non-empty string.");this.#vt.bgColor=e,this._applyConfig()}get bgColor(){return vi(this.#u),this.#vt.bgColor}set borderWidth(e){if(vi(this.#u),"number"!=typeof e||e<0)throw new Error("TinyAnalogClock: 'borderWidth' must be a non-negative number.");this.#vt.borderWidth=e,this._applyConfig(),this._renderFace()}get borderWidth(){return vi(this.#u),this.#vt.borderWidth}set hourHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'hourHandColor' must be a non-empty string.");this.#vt.hourHandColor=e,this._applyConfig()}get hourHandColor(){return vi(this.#u),this.#vt.hourHandColor}set minuteHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'minuteHandColor' must be a non-empty string.");this.#vt.minuteHandColor=e,this._applyConfig()}get minuteHandColor(){return vi(this.#u),this.#vt.minuteHandColor}set secondHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'secondHandColor' must be a non-empty string.");this.#vt.secondHandColor=e,this._applyConfig()}get secondHandColor(){return vi(this.#u),this.#vt.secondHandColor}set showSeconds(e){if(vi(this.#u),"boolean"!=typeof e)throw new Error("TinyAnalogClock: 'showSeconds' must be a boolean.");this.#vt.showSeconds=e,this._applyConfig()}get showSeconds(){return vi(this.#u),this.#vt.showSeconds}set sizeAdjust(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'sizeAdjust' must be a positive number.");this.#vt.sizeAdjust=e,this._renderFace()}get sizeAdjust(){return vi(this.#u),this.#vt.sizeAdjust}set padding(e){if(vi(this.#u),"number"!=typeof e||e<0)throw new Error("TinyAnalogClock: 'padding' must be a non-negative number.");this.#vt.padding=e,this._renderFace()}get padding(){return vi(this.#u),this.#vt.padding}set angleDistance(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'angleDistance' must be a positive number.");this.#vt.angleDistance=e,this._renderFace()}get angleDistance(){return vi(this.#u),this.#vt.angleDistance}set pwH(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'pwH' must be a positive number.");this.#vt.pwH=e,this._renderFace()}get pwH(){return vi(this.#u),this.#vt.pwH}set phH(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'phH' must be a positive number.");this.#vt.phH=e,this._renderFace()}get phH(){return vi(this.#u),this.#vt.phH}set pwM(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'pwM' must be a positive number.");this.#vt.pwM=e,this._renderFace()}get pwM(){return vi(this.#u),this.#vt.pwM}set phM(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'phM' must be a positive number.");this.#vt.phM=e,this._renderFace()}get phM(){return vi(this.#u),this.#vt.phM}destroy(){this.#u||(this.#oi&&(cancelAnimationFrame(this.#oi),this.#oi=null),this.#qn.remove(),this.#u=!0)}},Ti=le("TinyTextDiffer"),Si=class{#Kn=[];#u=!1;get destroyed(){return this.#u}get history(){return Ti(this.#u),[...this.#Kn]}set history(e){if(Ti(this.#u),!Array.isArray(e))throw new TypeError("History data must be provided as an array.");if(!e.every(e=>"string"==typeof e))throw new TypeError("All items in the history array must be strings.");this.#Kn=[...e]}get size(){return Ti(this.#u),this.#Kn.length}constructor(e=[]){this.history=e}#Jn(e){if("number"!=typeof e)throw new TypeError("The provided index must be a valid number.")}#Gn(e){if("string"!=typeof e)throw new TypeError("The provided text must be a valid string.")}get(e){if(Ti(this.#u),this.#Jn(e),void 0===this.#Kn[e])throw new Error(`No text version found at index ${e}.`);return this.#Kn[e]}has(e){return Ti(this.#u),this.#Jn(e),void 0!==this.#Kn[e]}add(e){Ti(this.#u),this.#Gn(e),this.#Kn.push(e)}remove(){return Ti(this.#u),this.#Kn.pop()}addAt(e,t){Ti(this.#u),this.#Jn(e),this.#Gn(t),this.#Kn.splice(e,0,t)}removeAt(e){Ti(this.#u),this.#Jn(e);const t=this.#Kn.length;return this.#Kn.splice(e,1),t!==this.#Kn.length}clear(){Ti(this.#u),this.#Kn=[]}compare(...e){Ti(this.#u);const t=e.length;if(0===t||t%2!=0)throw new Error("The compare method requires an even number of indices to form comparison pairs.");const r=[];for(let i=0;i<t;i+=2){const s=i+1;if(s>t-1)continue;this.#Jn(e[i]),this.#Jn(e[s]);const n=this.#Kn[e[i]],o=this.#Kn[e[s]];r.push(this._computeDiff(n,o))}return r}_computeDiff(e,t){const r=e.length,i=t.length,s=Array(r+1).fill(null).map(()=>Array(i+1).fill(0));let n=1,o=1;for(n=1;n<=r;n++)for(o=1;o<=i;o++)e[n-1]===t[o-1]?s[n][o]=s[n-1][o-1]+1:s[n][o]=Math.max(s[n-1][o],s[n][o-1]);n=r,o=i;const a=[];for(;n>0||o>0;)n>0&&o>0&&e[n-1]===t[o-1]?(a.unshift({value:e[n-1],type:"normal"}),n--,o--):o>0&&(0===n||s[n][o-1]>=s[n-1][o])?(a.unshift({value:t[o-1],type:"added"}),o--):n>0&&(0===o||s[n][o-1]<s[n-1][o])&&(a.unshift({value:e[n-1],type:"deleted"}),n--);return a.reduce((e,t)=>{const r=e.length-1;return e.length>0&&e[r].type===t.type?e[r].value+=t.value:e.push(t),e},[])}destroy(){this.#u||(this.#Kn=[],this.#u=!0)}};class xi{static generateHash(e){let t;try{t="object"==typeof e&&null!==e?JSON.stringify(e):String(e)}catch(e){throw new TypeError("Failed to stringify item for hashing. Ensure the object does not have circular references.")}let r=0;for(let e=0,i=t.length;e<i;e++)r=(r<<5)-r+t.charCodeAt(e),r|=0;return r.toString(36)}#Yn=[];#Xn=null;#Qn=!0;get idKey(){return this.#Xn}set idKey(e){if(null!==e&&"string"!=typeof e)throw new TypeError("The idKey must be a string or null.");this.#Xn=e}get deepComparison(){return this.#Qn}set deepComparison(e){if("boolean"!=typeof e)throw new TypeError("The deepComparison option must be a boolean.");this.#Qn=e}get oldArray(){return this.#Yn}set oldArray(e){if(!Array.isArray(e))throw new TypeError("The provided oldArray must be a valid Array.");this.#Yn=e}constructor(e,t={}){void 0!==e&&(this.oldArray=e),"string"==typeof t.idKey&&(this.idKey=t.idKey),"boolean"==typeof t.deepComparison&&(this.deepComparison=t.deepComparison)}_generateHash(e){return xi.generateHash(e)}#Zn(e,t){const r={added:{},deleted:{},modified:{},nested:{}},i=new Set([...Object.keys(e),...Object.keys(t)]);for(const s of i){const i=e[s],n=t[s];if(s in e)if(s in t)if("object"!=typeof i||null===i||"object"!=typeof n||null===n||Array.isArray(i)||Array.isArray(t))i!==n&&(r.modified[s]={oldValue:i,newValue:n});else{const e=this.#Zn(i,n);(Object.keys(e.added).length>0||Object.keys(e.deleted).length>0||Object.keys(e.modified).length>0||Object.keys(e.nested).length>0)&&(r.nested[s]=e)}else r.deleted[s]=i;else r.added[s]=n}return r}compare(e){if(!Array.isArray(e))throw new TypeError("The provided newArray must be a valid Array.");const t={oldItemsMap:new Map,affectedItems:[]};for(const e of this.#Yn){const r=this._generateHash(e),i=null!==this.#Xn&&null!==e&&"object"==typeof e&&this.#Xn in e?e[this.#Xn]:r;t.oldItemsMap.set(i,{item:e,hash:r})}for(const r of e){const e=this._generateHash(r),i=null!==this.#Xn&&null!==r&&"object"==typeof r&&this.#Xn in r?r[this.#Xn]:e,s=t.oldItemsMap.get(i);if(s)if(s.hash===e)t.oldItemsMap.delete(i);else{const e={item:r,oldItem:s.item,status:"edited"};this.#Qn&&"object"==typeof r&&null!==r&&"object"==typeof s.item&&null!==s.item&&(e.details=this.#Zn(s.item,r)),t.affectedItems.push(e),t.oldItemsMap.delete(i)}else t.affectedItems.push({item:r,status:"added"})}for(const e of t.oldItemsMap.values())t.affectedItems.push({item:e.item,status:"deleted"});return t.affectedItems}}const Ai=xi,Ci=e=>{if(!Array.isArray(e))throw new TypeError("Parameter 'sets' must be an array.");if(!e.every(e=>e instanceof Mi))throw new TypeError("All elements in the array must be instances of FuzzySet.")},Ii=(e,t,r=.5)=>{ki(e,"object","defuzzifyCentroid.fuzzyOutput");for(const t in e)ki(e[t],"number",`fuzzyOutput['${t}']`);Ci(t),ki(r,"number","defuzzifyCentroid.step");let i=0,s=0;for(let n=0;n<=100;n+=r){let r=0;t.forEach(t=>{const i=e[t.name]||0,s=Math.min(i,t.calculate(n));r=Math.max(r,s)}),i+=n*r,s+=r}return 0===s?0:i/s},Di=(e,t,r,i,s,n=!1)=>{if(n){if(e<=t||e>=s)return 0;if(e>=r&&e<=i)return 1}const o=t===r?1:(e-t)/(r-t),a=i===s?1:(s-e)/(s-i),l=Math.max(0,Math.min(o,1,a));return isNaN(l)?0:l},ki=(e,t,r)=>{if(typeof e!==t)throw new TypeError(`Parameter '${r}' must be a ${t}.`)};class Mi{static trapezoid(e,t,r,i,s,n=!1){return Di(e,t,r,i,s,n)}#eo="";#to=0;#ro=0;#io=0;#so=0;#no=!1;get name(){return this.#eo}set name(e){ki(e,"string","FuzzySet.name"),this.#eo=e}get a(){return this.#to}set a(e){ki(e,"number","FuzzySet.a"),this.#to=e}get b(){return this.#ro}set b(e){ki(e,"number","FuzzySet.b"),this.#ro=e}get c(){return this.#io}set c(e){ki(e,"number","FuzzySet.c"),this.#io=e}get d(){return this.#so}set d(e){ki(e,"number","FuzzySet.d"),this.#so=e}get optimize(){return this.#no}set optimize(e){ki(e,"boolean","FuzzySet.optimize"),this.#no=e}constructor(e,t,r,i,s,n=!1){this.name=e,this.a=t,this.b=r,this.c=i,this.d=s,this.optimize=n}calculate(e){return ki(e,"number","calculate.x"),Mi.trapezoid(e,this.#to,this.#ro,this.#io,this.#so,this.#no)}}class Li{#oo=new Map;addVariable(e,t){ki(e,"string","addVariable.name"),Ci(t),this.#oo.set(e,t)}removeVariable(e){return ki(e,"string","removeVariable.name"),this.#oo.delete(e)}getVariable(e){ki(e,"string","getVariable.name");const t=this.#oo.get(e);if(!t)throw new Error(`Linguistic variable '${e}' not found in the inference system.`);return[...t]}hasVariable(e){return ki(e,"string","hasVariable.name"),this.#oo.has(e)}fuzzify(e,t){ki(e,"string","fuzzify.varName"),ki(t,"number","fuzzify.value");const r=this.#oo.get(e)||[],i={};return r.forEach(e=>{i[e.name]=e.calculate(t)}),i}}class Ni{#ao=new Set;get appliedPlugins(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return[...this.#ao]}#ho=[];get appliedPluginClasses(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return[...this.#ho]}get size(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return this.#ho.length}#uo;get currentClass(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return this.#uo}#lo=!1;get used(){return this.#lo}constructor(e,t=[]){this.#uo=e,this.#ho=[...t,e]}#co(e,t,r){if(this.#lo)throw new Error("[TinyClassManager] Cannot reuse a consumed manager instance.");if(this.#ao.has(e))throw new Error(`[TinyClassManager] Plugin conflict: "${e}" is already installed.`);for(const r of t)if(!this.#ao.has(r))throw new Error(`[TinyClassManager] Missing Dependency: "${e}" requires "${r}" to be installed first.`);const i=new Ni(r,this.#ho);return this.#ao.forEach(e=>i.#ao.add(e)),i.#ao.add(e),this.#lo=!0,this.#ao.clear(),this.#ho=[],i}use(e){const t=e.dependencies||[],r=e.apply(this.#uo,this.appliedPluginClasses);return this.#co(e.name,t,r)}insert(e){const t=e(this.#uo,this.appliedPluginClasses),r=t._tinyDepName;if(!r)throw new Error("[TinyClassManager] Plugin class must define a static '_tinyDepName' property.");const i=t._tinyDeps??[];if(!Array.isArray(i)||!i.every(e=>"string"==typeof e))throw new Error("[TinyClassManager] Plugin class must define a static array of strings in '_tinyDepName' property.");return this.#co(r,i,t)}build(){if(this.#lo)throw new Error("[TinyClassManager] Cannot build from an already finalized manager.");return this.#lo=!0,this.#ao.clear(),this.#ho=[],this.#uo}}const _i=Ni,Pi=le("TinyRadioFm"),Ri=e().EventEmitter;class ji extends Ri{static async parseContent(e,t,r,i,s,n=!0){return or(e,t,r,i,s,n,ji.#do)}static#do="Unknown Artist";static get unknownArtist(){return ji.#do}static set unknownArtist(e){if("string"!=typeof e&&"function"!=typeof e)throw new TypeError("unknownArtist must have an string or function.");ji.#do=e}#u=!1;get destroyed(){return this.#u}get size(){return Pi(this.#u),this.#po.length+this.#mo.length}get musicSize(){return Pi(this.#u),this.#po.length}get voiceSize(){return Pi(this.#u),this.#mo.length}get customPosSize(){return Pi(this.#u),this.#fo.length}get tasksSize(){return Pi(this.#u),this.#yo.length}get cycleCacheSize(){return Pi(this.#u),this.#go.size}#po=[];get musicList(){return Pi(this.#u),structuredClone(this.#po)}#mo=[];get voiceList(){return Pi(this.#u),structuredClone(this.#mo)}#fo=[];get customPositions(){return Pi(this.#u),structuredClone(this.#fo)}#yo=[];get scheduledTasks(){return Pi(this.#u),structuredClone(this.#yo)}get allList(){return Pi(this.#u),[...this.musicList,...this.voiceList]}#fs=0;get seed(){return Pi(this.#u),this.#fs}set seed(e){if(Pi(this.#u),"number"!=typeof e)throw new TypeError("Seed must be a number.");this.#fs=e,this.#go.clear(),this.emit("seedChanged",{seed:e})}#wo=Date.now();get anchorDate(){return Pi(this.#u),this.#wo}#go=new Map;#vt={mode:"playlist",voiceMode:"playlist",silenceDuration:0,queryLimit:1e5,voiceAfterMusic:!0,voiceMin:0,voiceMax:1,voiceWeight:1,musicMaxConsecutive:0,musicMinConsecutive:0,voiceMaxConsecutive:0,voiceMinConsecutive:0};get config(){return Pi(this.#u),structuredClone(this.#vt)}set config(e){Pi(this.#u),this.#bo(e),this.#vt=structuredClone(e),this.#go.clear(),this.emit("configChanged",{config:this.config})}#bo(e){if("object"!=typeof e||null===e)throw new TypeError("Configuration must be a valid object.");const t=["playlist","random"];if(void 0!==e.mode&&!t.includes(e.mode))throw new TypeError(`Invalid mode: "${e.mode}". Must be one of: ${t.join(", ")}.`);if(void 0!==e.voiceMode&&!t.includes(e.voiceMode))throw new TypeError(`Invalid voiceMode: "${e.voiceMode}". Must be one of: ${t.join(", ")}.`);if(void 0!==e.silenceDuration&&("number"!=typeof e.silenceDuration||e.silenceDuration<0))throw new TypeError("silenceDuration must be a non-negative number.");if(void 0!==e.queryLimit&&("number"!=typeof e.queryLimit||e.queryLimit<=0))throw new TypeError("queryLimit must be a positive number.");if(void 0!==e.voiceAfterMusic&&"boolean"!=typeof e.voiceAfterMusic)throw new TypeError("voiceAfterMusic must be a boolean.");const r=(e,t)=>{if(void 0!==e&&("number"!=typeof e||e<0))throw new TypeError(`${t} must be a non-negative number.`)};r(e.voiceWeight,"voiceWeight"),r(e.voiceMin,"voiceMin"),r(e.voiceMax,"voiceMax"),r(e.musicMinConsecutive,"musicMinConsecutive"),r(e.musicMaxConsecutive,"musicMaxConsecutive"),r(e.voiceMinConsecutive,"voiceMinConsecutive"),r(e.voiceMaxConsecutive,"voiceMaxConsecutive");const i=e.voiceMin??this.#vt.voiceMin,s=e.voiceMax??this.#vt.voiceMax;if(s<i)throw new RangeError(`Logical error: voiceMax (${s}) cannot be less than voiceMin (${i}).`);const n=e.musicMinConsecutive??this.#vt.musicMinConsecutive,o=e.musicMaxConsecutive??this.#vt.musicMaxConsecutive;if(-1!==o&&n>o)throw new RangeError(`Logical error: musicMinConsecutive (${n}) cannot be greater than musicMaxConsecutive (${o}).`)}#vo=!0;get optimizeMediaMemory(){return Pi(this.#u),this.#vo}set optimizeMediaMemory(e){if(Pi(this.#u),"boolean"!=typeof e)throw new TypeError("optimizeMediaMemory must be a boolean.");this.#vo=e}#Eo=!0;get optimizePictureMemory(){return Pi(this.#u),this.#Eo}set optimizePictureMemory(e){if(Pi(this.#u),"boolean"!=typeof e)throw new TypeError("optimizePictureMemory must be a boolean.");this.#Eo=e}constructor(e=null,t=0){if(super(),null!==e&&"object"!=typeof e)throw new TypeError("initialData must be an object or null.");if("number"!=typeof t)throw new TypeError("seed must be a number.");this.#fs=t,e?this.#To(e):this.#wo=Date.now()}_ccBase64ToBlobUrl(e){this.#vo&&"string"==typeof e.url&&e.url.startsWith("data:")&&(e.url=er(e.url)),e.picture&&Array.isArray(e.picture)&&(e.picture=e.picture.map(e=>{if(this.#Eo){const t="string"==typeof e.data&&e.data.startsWith("data:"),r=e.data instanceof Uint8Array;if(t||r)return{...e,data:er(e.data,e.format)}}return e}))}async _rcblobUrlToBase64(e){this.#vo&&"string"==typeof e.url&&e.url.startsWith("blob:")&&(e.url=await tr(e.url)),this.#Eo&&e.picture&&Array.isArray(e.picture)&&(e.picture=await Promise.all(e.picture.map(async e=>"string"==typeof e.data&&e.data.startsWith("blob:")?{...e,data:await tr(e.data)}:e)))}add(e,t,r=!0){if(Pi(this.#u),!["music","voice","custom"].includes(e))throw new TypeError('Type must be "music", "voice", or "custom".');if(!t||"string"!=typeof t.id||"number"!=typeof t.duration)throw new TypeError("Content must have a string ID and a valid numerical duration in milliseconds.");if("boolean"!=typeof r)throw new TypeError("smartQueue must be a boolean.");sr(t);const i=structuredClone(t);this._ccBase64ToBlobUrl(i),"music"===e?(this.#po.push(i),this.#go.clear()):"voice"===e?(this.#mo.push(i),this.#go.clear()):"custom"===e&&this.#So(i,r),this.#xo(Date.now()),this.emit("contentAdded",{type:e,data:structuredClone(i)})}scheduleTask(e,t,r,i,s=!0){if(Pi(this.#u),"number"!=typeof e||isNaN(e))throw new TypeError("timestamp must be a valid number.");if(!["add","remove","move"].includes(t))throw new TypeError('action must be "add", "remove", or "move".');if(!["music","voice"].includes(r))throw new TypeError('type must be "music" or "voice".');if("boolean"!=typeof s)throw new TypeError("smartQueue must be a boolean.");if("add"===t){if("object"!=typeof i||null===i||"string"!=typeof i.id||"number"!=typeof i.duration)throw new TypeError('Payload for "add" must be a MediaContent object (id: string, duration: number).')}else if("remove"===t){if("string"!=typeof i)throw new TypeError('Payload for "remove" must be a string (the content ID).')}else if("move"===t&&("object"!=typeof i||null===i||"string"!=typeof i.id||"number"!=typeof i.newIndex))throw new TypeError('Payload for "move" must be a ScheduledMovePayload (id: string, newIndex: number).');let n=e;if(s){const t=this.#Ao(e,e);t&&(n=t.absoluteEnd)}v(i)&&"number"!=typeof i.newIndex&&sr(i);const o={timestamp:n,action:t,type:r,payload:i};this.#yo.push(o),this.#xo(Date.now()),this.emit("taskScheduled",structuredClone(o))}remove(e){if(Pi(this.#u),"string"!=typeof e)throw new TypeError("id must be a string.");this.#po.filter(t=>t.id===e).forEach(e=>rr(e)),this.#mo.filter(t=>t.id===e).forEach(e=>rr(e)),this.#fo.filter(t=>t.content?.id===e).forEach(e=>rr(e.content));const t=t=>t.id!==e&&t.content?.id!==e;this.#po=this.#po.filter(t),this.#mo=this.#mo.filter(t),this.#fo=this.#fo.filter(t),this.#yo=this.#yo.filter(t=>"add"===t.action&&"object"==typeof t.payload&&null!==t.payload&&"id"in t.payload?t.payload.id!==e||(rr(t.payload),!1):t.payload!==e),this.#go.clear(),this.emit("contentRemoved",{id:e})}setConfig(e){Pi(this.#u),this.#bo(e);const t={...this.#vt,...e};this.#bo(t),this.#vt=t,this.#go.clear(),this.emit("configChanged",{config:this.config})}getCurrentEvent(){Pi(this.#u);const e=Date.now();return this.#xo(e),this.#Ao(e,e)}queryTimeline(e,t=10){if(Pi(this.#u),"number"!=typeof t||isNaN(t))throw new TypeError("Invalid query limit value. Ensure it is a number.");if(t>this.#vt.queryLimit||t<=0)throw new RangeError(`Invalid query limit. Ensure it is > 0 and <= ${this.#vt.queryLimit}.`);const r=new ji(JSON.parse(this._exportState())),i=[];let s=e;for(let n=0;n<t;n++){r.#xo(s);const t=r.#Co(s,e);if(!t)break;i.push(t),s=t.absoluteEnd}return r.destroy(!1),this.emit("timelineQueried",{targetDate:e,limit:t,resultCount:i.length}),i}searchCustomPositions(){return Pi(this.#u),this.#xo(Date.now()),[...this.#fo]}async _processListForExport(e){return Promise.all(e.map(async e=>{sr(e);const t=structuredClone(e);return await this._rcblobUrlToBase64(t),t}))}_exportState(){return JSON.stringify({music:this.#po,voice:this.#mo,custom:this.#fo,tasks:this.#yo,seed:this.#fs,anchorDate:this.#wo,config:this.#vt})}async exportState(){Pi(this.#u);const e=await this._processListForExport(this.#po),t=await this._processListForExport(this.#mo),r=await Promise.all(this.#fo.map(async e=>{const t=await this._processListForExport([e.content]);return{...e,content:t[0]}})),i=await Promise.all(this.#yo.map(async e=>{if("add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload){const t=await this._processListForExport([e.payload]);return{...e,payload:t[0]}}return e}));return JSON.stringify({music:e,voice:t,custom:r,tasks:i,seed:this.#fs,anchorDate:this.#wo,config:this.#vt})}importState(e){let t;if(Pi(this.#u),"string"==typeof e)try{t=JSON.parse(e)}catch{throw new TypeError("Provided string is not valid JSON.")}else{if("object"!=typeof e||null===e)throw new TypeError("Import data must be a valid JSON string or an object.");t=e}this.#To(t),this.emit("stateImported",{data:structuredClone(t)})}_prng(e){return function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}#Io(e,t,r,i=0,s=0,n=null,o=0){if(0===e.length)return{items:[],lastId:n,consecutiveCount:o};if("random"!==r){const t=[...e],r=t[t.length-1];return{items:t,lastId:r.id,consecutiveCount:n===r.id?o+1:1}}const a=this._prng(t),l=[];let h=n,u=o;const c=new ei({rng:a,normalization:"relative"}),d=[...e];for(d.forEach(e=>{const t=e.weight??1,r=c.getItem(e.id);r?c.setBaseWeight(e.id,r.baseWeight+t):c.addItem(e.id,{weight:t})});d.length>0;){let e=null,t=-1;if(null!==h&&u<i&&(t=d.findIndex(e=>e.id===h),-1!==t?e=d[t]:l.length>0&&(e=l[l.length-1])),!e){let r=null;null!==h&&-1!==s&&u>=s&&d.some(e=>e.id!==h)&&(c.excludeItem(h),r=h);const i=c.drawOne();i&&(t=d.findIndex(e=>e.id===i.id),-1!==t&&(e=d[t])),r&&c.includeItem(r)}if(e||(e=d[0],t=0),l.push(e),-1!==t)if(d.splice(t,1),d.some(t=>t.id===e.id)){const t=c.getItem(e.id);if(t){const r=Math.max(0,t.baseWeight-(e.weight??1));r<=0?c.removeItem(e.id):c.setBaseWeight(e.id,r)}}else c.removeItem(e.id);e.id===h?u++:(h=e.id,u=1)}return c.destroy(),{items:l,lastId:h,consecutiveCount:u}}#Do(e){const t=this.#fs+e,r=this._prng(10*t);let i=null,s=0,n=null,o=0;if(e>0){const t=this.#go.get(e-1);t&&(i=t.lastMusicId??null,s=t.musicConsecutiveCount??0,n=t.lastVoiceId??null,o=t.voiceConsecutiveCount??0)}const a=this.#Io(this.#po,t+1,this.#vt.mode,this.#vt.musicMinConsecutive,this.#vt.musicMaxConsecutive,i,s),l=a.items,h=this.#Io(this.#mo,t+2,this.#vt.voiceMode,this.#vt.voiceMinConsecutive,this.#vt.voiceMaxConsecutive,n,o),u=h.items,c=[];let d=0,p=0;for(let e=0;e<l.length;e++){const t=l[e];if(c.push({...t,cycleStart:d,cycleEnd:d+t.duration}),d+=t.duration+this.#vt.silenceDuration,this.#vt.voiceAfterMusic&&u.length>0){const e=this.#vt.voiceWeight/(this.#vt.voiceWeight+1);if(r()<e){const e=this.#vt.voiceMax-this.#vt.voiceMin+1,t=Math.floor(r()*e)+this.#vt.voiceMin;for(let e=0;e<t;e++){const e=u[p%u.length];p++,c.push({...e,cycleStart:d,cycleEnd:d+e.duration}),d+=e.duration+this.#vt.silenceDuration}}}}return{items:c,duration:d,lastMusicId:a.lastId,musicConsecutiveCount:a.consecutiveCount,lastVoiceId:h.lastId,voiceConsecutiveCount:h.consecutiveCount}}#ko(e){if(0===this.#po.length)return null;let t=this.#wo,r=0;for(;;){if(r>this.#vt.queryLimit)throw new Error("Safety limit hit during cycle location.");let i=this.#go.get(r);if(i||(i=this.#Do(r),this.#go.set(r,i)),0===i.duration)return null;if(e>=t&&e<t+i.duration)return{block:i,startTimestamp:t,loopIndex:r};t+=i.duration,r++}}#Co(e,t){const r=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration>e).sort((e,t)=>e.intendedTimestamp-t.intendedTimestamp)[0];let i=null;if(r){const e=Math.max(t,r.intendedTimestamp);i=this.#Mo(r.content,r.intendedTimestamp,e,!0)}const s=this.#Lo(e,t);return s||i?s?i?i.absoluteStart<=s.absoluteStart?i:(i.absoluteStart<s.absoluteEnd&&(s.absoluteEnd=i.absoluteStart,s.duration=s.absoluteEnd-s.absoluteStart,s.remainingTime=Math.max(0,s.absoluteEnd-t),s.progress=Math.min(1,s.elapsedTime/s.duration)),s):s:i:null}#Lo(e,t){let r=this.#ko(e);if(!r)return null;const{block:i,startTimestamp:s}=r,n=e-s;let o,a=i.items.find(e=>e.cycleEnd>n);if(a)o=s+a.cycleStart;else{if(r=this.#ko(s+i.duration),!r||0===r.block.items.length)return null;a=r.block.items[0],o=r.startTimestamp+a.cycleStart}const l=Math.max(t,o);return this.#Mo(a,o,l,!1)}#Ao(e,t){const r=this.#fo.find(t=>e>=t.intendedTimestamp&&e<t.intendedTimestamp+t.content.duration);if(r)return this.#Mo(r.content,r.intendedTimestamp,t,!0);const i=this.#ko(e);if(!i)return null;const{block:s,startTimestamp:n}=i,o=e-n,a=s.items.find(e=>o>=e.cycleStart&&o<e.cycleEnd);return a?this.#Mo(a,n+a.cycleStart,t,!1):null}#Mo(e,t,r,i){const s=r-t;return{id:e.id,title:e.title,artist:e.artist,duration:e.duration,url:e.url,absoluteStart:t,absoluteEnd:t+e.duration,elapsedTime:s,remainingTime:e.duration-s,progress:Math.min(1,s/e.duration),isCustom:i}}#So(e,t){let r=e.timestamp||Date.now();const i=e.duration;if(t){const e=this.#Ao(r,r);e&&(r=e.absoluteEnd)}const s=[...this.#fo].sort((e,t)=>e.intendedTimestamp-t.intendedTimestamp);let n=r;if(s.some(e=>r<e.intendedTimestamp+e.content.duration&&r+i>e.intendedTimestamp)){const e=[];let t=Date.now();for(const r of s)r.intendedTimestamp>t&&e.push({start:t,end:r.intendedTimestamp}),t=Math.max(t,r.intendedTimestamp+r.content.duration+this.#vt.silenceDuration);e.push({start:t,end:1/0});let o=1/0;for(const t of e)if(t.end-t.start>=i){let e=null;if(r>=t.start&&r+i<=t.end?e=r:r<t.start?e=t.start:r>t.end&&(e=t.end-i),null!==e){const t=Math.abs(r-e);t<o&&(o=t,n=e)}}}this.#fo.push({content:e,intendedTimestamp:n,originalTimestamp:e.timestamp||Date.now()})}#xo(e){const t=this.#yo.filter(t=>t.timestamp<=e);this.#yo=this.#yo.filter(t=>t.timestamp>e);const r=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration<=e);this.#fo=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration>e);let i=!1;r.forEach(e=>{rr(e.content),this.#fs+=e.content.id.length,i=!0,this.emit("customPositionExpired",{contentId:e.content.id})}),t.length>0&&t.sort((e,t)=>e.timestamp-t.timestamp).forEach(e=>{const t="music"===e.type?this.#po:this.#mo;if("add"===e.action)t.push(e.payload);else if("remove"===e.action){const r=t.findIndex(t=>t.id===e.payload);if(-1!==r){const[e]=t.splice(r,1);rr(e)}}else if("move"===e.action){const r=e.payload,i=t.findIndex(e=>e.id===r.id);if(-1!==i){const[e]=t.splice(i,1);t.splice(r.newIndex,0,e)}}this.#wo=e.timestamp,this.#fs+=1,i=!0,this.emit("taskExecuted",structuredClone(e))}),i&&this.#go.clear()}#To(e){this.#po.forEach(e=>rr(e)),this.#mo.forEach(e=>rr(e)),this.#fo.forEach(e=>rr(e.content)),this.#yo.forEach(e=>{"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload&&rr(e.payload)});const t=e=>e.map(e=>{sr(e);const t=structuredClone(e);return this._ccBase64ToBlobUrl(t),t});this.#po=t(e.music),this.#mo=t(e.voice),this.#fs=e.seed||0,this.#wo=e.anchorDate||Date.now(),this.#vt={...this.#vt,...e.config||{}},this.#fo=e.custom.map(e=>({...e,content:t([e.content])[0]})),this.#yo=e.tasks.map(e=>"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload?{...e,payload:t([e.payload])[0]}:e)}destroy(e=!0){this.#u||(e&&(this.#po.forEach(e=>rr(e)),this.#mo.forEach(e=>rr(e)),this.#fo.forEach(e=>rr(e.content)),this.#yo.forEach(e=>{"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload&&rr(e.payload)})),this.#po=[],this.#mo=[],this.#fo=[],this.#yo=[],this.#go.clear(),this.emit("destroyed",{timestamp:Date.now()}),this.removeAllListeners(),this.#u=!0)}}const Oi=ji,$i=()=>"undefined"!=typeof window&&void 0!==window.document,Hi="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null,Fi="undefined"!=typeof document?document:null,zi=["chrome","firefox","ie","edge","safari","opera","yandex","other"];function Bi(){if("undefined"==typeof navigator)return"other";const e=navigator.userAgent;return-1!==e.indexOf("Chrome")?"chrome":-1!==e.indexOf("Firefox")?"firefox":-1!==e.indexOf("MSIE")?"ie":-1!==e.indexOf("Edge")?"edge":-1!==e.indexOf("Safari")?"safari":-1!==e.indexOf("Opera")?"opera":-1!==e.indexOf("YaBrowser")?"yandex":"other"}function Wi(){const e=Hi?.getComputedStyle?(Array.prototype.slice.call(Hi.getComputedStyle(document.documentElement,"")).join("").match(/-(moz|webkit|ms)-/)??["",""])[1]:"";return"moz"===e?"gecko":"webkit"===e?"webkit":"ms"===e?"trident":"other"}function qi(){const e=!!Hi?.opr&&!!opr.addons||!!Hi?.opera||navigator.userAgent.indexOf(" OPR/")>=0,t="undefined"!=typeof InstallTrigger,r=!!Hi?.HTMLElement&&/constructor/i.test(Hi.HTMLElement)||"[object SafariRemoteNotification]"===(!Hi.safari||"undefined"!=typeof safari&&safari.pushNotification).toString(),i=!!Fi?.documentMode,s=!i&&!!Hi?.StyleMedia,n=!!Hi?.chrome;return{isOpera:e,isFirefox:t,isSafari:r,isIE:i,isEdge:s,isChrome:n,isBlink:(n||e)&&!!Hi?.CSS}}function Vi(e=[]){if(!Array.isArray(e))throw new TypeError('The "disable" argument must be an array.');for(const t of e)if(!zi.includes(t))throw new TypeError(`Invalid browser name provided in disable array: ${t}`);const t={chrome:0,firefox:0,ie:0,edge:0,safari:0,opera:0,yandex:0,other:0};t[Bi()]++;const r=Wi();"gecko"===r?e.indexOf("firefox")<0&&t.firefox++:"webkit"===r?(e.indexOf("chrome")<0&&t.chrome++,e.indexOf("safari")<0&&t.safari++,e.indexOf("opera")<0&&t.opera++,e.indexOf("edge")<0&&t.edge++):"trident"===r?e.indexOf("ie")<0&&t.ie++:e.indexOf("other")<0&&t.other++;const i=qi();return i.isOpera&&e.indexOf("opera")<0&&t.opera++,i.isFirefox&&e.indexOf("firefox")<0&&t.firefox++,i.isSafari&&e.indexOf("safari")<0&&t.safari++,i.isIE&&e.indexOf("ie")<0&&t.ie++,i.isEdge&&e.indexOf("edge")<0&&t.edge++,i.isChrome&&e.indexOf("chrome")<0&&t.chrome++,t}function Ui(e=[]){const t=Vi(e);return Object.keys(t).reduce((e,r)=>t[r]>t[e]?r:e)}const Ki=e().EventEmitter,Ji=class extends Ki{#No;#_o;#Po=null;#Ro;#jo;#Oo;#$o;#Ho=new Map([["log",""],["info",""],["warn",""],["error",""],["debug",""],["main_class",""],["sub_class",""],["reset",""],["black",""],["red",""],["green",""],["yellow",""],["blue",""],["magenta",""],["cyan",""],["white",""],["gray",""]]);#Fo=new Map([["log","[_log_LOG_reset_]"],["info","[_info_INFO_reset_]"],["warn","[_warn_WARN_reset_]"],["error","[_error_ERROR_reset_]"],["debug","[_debug_DEBUG_reset_]"]]);constructor({logger:e,id:t,debugMode:r,canEmitLogs:i=!1,useLogColors:s=!1,autoHideId:n=!1}){if(super(),!E(e))throw new TypeError("Logger must be an object that implements the Console interface.");if("string"!=typeof t)throw new TypeError("Logger instance id must be a string.");if("boolean"!=typeof r)throw new TypeError("debugMode must be a boolean.");if("boolean"!=typeof i)throw new TypeError("canEmitLogs must be a boolean.");if("boolean"!=typeof s)throw new TypeError("useLogColors must be a boolean.");if("boolean"!=typeof n)throw new TypeError("autoHideId must be a boolean.");this.#_o=t,this.#No=e,this.#jo=r,this.#Ro=i,this.#$o=n,this.#Oo="firefox"!==Ui()&&s,this.log("info","Emit logs of debug mode set to: "+(this.#jo?"ON":"OFF")),this.log("info","Custom logger assigned.")}get logId(){return this.#_o}get logSubId(){if("string"!=typeof this.#Po)throw new Error('logSubId has not been set yet. Assign a string to "logSubId" before reading it.');return this.#Po}set logSubId(e){if("string"!=typeof e)throw new TypeError(`logSubId must be a string. Received: ${typeof e}.`);if(null!==this.#Po)throw new Error(`logSubId is already set to "${this.#Po}" and cannot be reassigned.`);this.#Po=e,this.emit("setLogSubId",e)}get canEmitLogs(){return this.#Ro}get useLogColors(){return this.#Oo}set useLogColors(e){if("boolean"!=typeof e)throw new TypeError("useLogColors must be a boolean.");this.#Oo=e,this.log("info","Log Colors usage mode set to: "+(this.#Oo?"ON":"OFF")),this.emit("setUseLogColors",e)}get debugMode(){return this.#jo}set debugMode(e){if("boolean"!=typeof e)throw new TypeError("debugMode must be a boolean.");this.#jo=e,this.log("info","Debug mode set to: "+(this.#jo?"ON":"OFF")),this.emit("setDebugMode",e)}_addLogColor(e,t){this.#Ho.set(e,t)}_removeLogColor(e){this.#Ho.delete(e)}_addLogPrefix(e,t){this.#Fo.set(e,t)}_removeLogPrefix(e){this.#Fo.delete(e)}#zo(e){if("string"!=typeof e)return e;let t=e;for(const[e,r]of this.#Fo){const i=new RegExp(`\\:${e}\\:`,"g");t=t.replace(i,r)}for(const[e,r]of this.#Ho){const i=new RegExp(`\\_${e}\\_`,"g");t=t.replace(i,this.#Oo?r:"")}return t}_applyLogFormatting(e){return this.#zo(e)}logClear(){if(this.#jo)return this.#Ro&&this.emit("debug:clear"),this.#No.clear?this.#No.clear():console.clear()}logGroupEnd(){if(this.#jo)return this.#Ro&&this.emit("debug:groupEnd"),this.#No.groupEnd?this.#No.groupEnd():console.groupEnd()}logLabel(e,t){if(!this.#jo)return;const r=["count","countReset","time","timeEnd","profile","profileEnd","timeStamp"];if(!r.includes(e))throw new TypeError(`Invalid logType. Expected one of: ${r.join(", ")}`);if(void 0!==t&&"string"!=typeof t)throw new TypeError("The label must be a string.");const i=this.#No[e]?this.#No[e]:console[e];if(!i)throw new TypeError(`The log type "${e}" is not supported by the provided logger or console.`);return this.#Ro&&this.emit("debug:logLabel",e,t),i(t)}logTimeLabel(e,...t){if(this.#jo)return this.#Ro&&this.emit("debug:timeLog",e,...t),this.#No.timeLog?this.#No.timeLog(e,...t):console.timeLog(e,...t)}logAssert(e,...t){if(this.#jo)return this.#Ro&&this.emit("debug:assert",e,...t),this.#No.assert?this.#No.assert(e,...t):console.assert(e,...t)}logDir(e,t){if(this.#jo)return this.#Ro&&this.emit("debug:dir",e,t),this.#No.dir?this.#No.dir(e,t):console.dir(e,t)}logTable(e,t){if(this.#jo){if(!(void 0===t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("Properties must be an array of strings.");return this.#Ro&&this.emit("debug:table",e,t),this.#No.table?this.#No.table(e,t):console.table(e,t)}}log(e,t,...r){if(!this.#jo)return;const i=["log","info","warn","error","debug","dirxml","group","groupCollapsed","trace"];if(!i.includes(e))throw new TypeError(`Invalid logType. Expected one of: ${i.join(", ")}`);if("string"!=typeof t)throw new TypeError("The message must be a string.");let s=this.#_o,n=this.#Po??"",o=t;const a=!this.#$o||"string"!=typeof this.#Po;s=a?this.#zo(s):"",n&&(n=this.#zo(n)),o=this.#zo(o);const l=`${s}${n?a?` ${n}`:n:""}`,h=this.#No[e]?this.#No[e]:console[e];return h?(this.#Ro&&this.emit("debug:log",l,o,...r),h(l,o,...r)):(this.#Ro&&this.emit("debug:log",l,o,...r),console.log(l,o,...r))}#Bo(e,t){const[r="",...i]=t;return"string"==typeof r?this.log(e,r,...i):this.log(e,"",r,...i)}toConsole(){return{log:(...e)=>this.#Bo("log",e),info:(...e)=>this.#Bo("info",e),warn:(...e)=>this.#Bo("warn",e),error:(...e)=>this.#Bo("error",e),debug:(...e)=>this.#Bo("debug",e),dirxml:(...e)=>this.#Bo("dirxml",e),group:(...e)=>this.#Bo("group",e),groupCollapsed:(...e)=>this.#Bo("groupCollapsed",e),trace:(...e)=>this.#Bo("trace",e),assert:(e,...t)=>this.logAssert(e,...t),dir:(e,t)=>this.logDir(e,t),table:(e,t)=>this.logTable(e,t),clear:()=>this.logClear(),groupEnd:()=>this.logGroupEnd(),count:e=>this.logLabel("count",e),countReset:e=>this.logLabel("countReset",e),time:e=>this.logLabel("time",e),timeEnd:e=>this.logLabel("timeEnd",e),timeLog:(e,...t)=>this.logTimeLabel(e,...t),timeStamp:e=>this.logLabel("timeStamp",e),profile:e=>this.logLabel("profile",e),profileEnd:e=>this.logLabel("profileEnd",e)}}},Gi=le("BaseMediaAdapter"),Yi=e().EventEmitter;class Xi extends Yi{constructor(){if(new.target===Xi)throw new Error("BaseMediaAdapter is an abstract class and cannot be instantiated directly.");super()}#u=!1;get destroyed(){return this.#u}static getThumbnailUrl(e){if("string"!=typeof e||""===e.trim())throw new TypeError('The "trackId" must be a non-empty string.');return""}static canHandle(e){throw new Error('Method "canHandle" must be implemented by the subclass.')}isReady(){throw Gi(this.#u),new Error('Method "isReady" must be implemented by the subclass.')}isPaused(){throw Gi(this.#u),new Error('Method "isPaused" must be implemented by the subclass.')}isEnded(){throw Gi(this.#u),new Error('Method "isEnded" must be implemented by the subclass.')}async waitIsReady(){throw Gi(this.#u),new Error('Method "waitIsReady" must be implemented by the subclass.')}canHandle(e){return Gi(this.#u),Xi.canHandle(e)}async play(e){throw Gi(this.#u),new Error('Method "play" must be implemented by the subclass.')}async pause(){throw Gi(this.#u),new Error('Method "pause" must be implemented by the subclass.')}async stop(){throw Gi(this.#u),new Error('Method "stop" must be implemented by the subclass.')}async seek(e){throw Gi(this.#u),new Error('Method "seek" must be implemented by the subclass.')}isMuted(){throw Gi(this.#u),new Error('Method "isMuted" must be implemented by the subclass.')}async mute(){throw Gi(this.#u),new Error('Method "mute" must be implemented by the subclass.')}async unMute(){throw Gi(this.#u),new Error('Method "unMute" must be implemented by the subclass.')}getCurrentTime(){throw Gi(this.#u),new Error('Method "getCurrentTime" must be implemented by the subclass.')}getTotalDuration(){throw Gi(this.#u),new Error('Method "getTotalDuration" must be implemented by the subclass.')}getRemainingTime(){throw Gi(this.#u),new Error('Method "getRemainingTime" must be implemented by the subclass.')}getPlaybackPercentage(){throw Gi(this.#u),new Error('Method "getPlaybackPercentage" must be implemented by the subclass.')}getTimeData(){throw Gi(this.#u),new Error('Method "getTimeData" must be implemented by the subclass.')}setVolume(e){throw Gi(this.#u),new Error('Method "setVolume" must be implemented by the subclass.')}getVolume(){throw Gi(this.#u),new Error('Method "getVolume" must be implemented by the subclass.')}async getContentData(){throw Gi(this.#u),new Error('Method "getContentData" must be implemented by the subclass.')}destroy(){this.#u||(this.removeAllListeners(),this.#u=!0,this.emit("destroyed"))}}const Qi=le("TinyMediaPlayer");class Zi extends Ji{static BaseMediaAdapter=Xi;static#do="Unknown Artist";static get unknownArtist(){return Zi.#do}static set unknownArtist(e){if("string"!=typeof e&&"function"!=typeof e)throw new TypeError("unknownArtist must be a string or a function.");Zi.#do=e}static async parseContent(e,t,r,i,s,n){return or(e,t,r,i,s,n,Zi.#do)}#u=!1;get destroyed(){return this.#u}#Wo=new Set;#qo=new WeakMap;#Vo=[];#Uo=-1;#Ko="NONE";#Jo=!1;#Go=!1;#Yo=!1;#Xo=1;#Qo;#Zo;#ea;#ta=!1;#ra;#ia;#sa=null;#na=null;#oa=300;get fadeVolumeSpeed(){return Qi(this.#u),this.#oa}set fadeVolumeSpeed(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("fadeVolumeSpeed must be a number.");if(e<0)throw new RangeError("fadeVolumeSpeed cannot be negative.");this.#oa=e,this.emit("fadeVolumeSpeedChange",this.#oa)}#aa=2e3;get prevClickTimeoutDuration(){return Qi(this.#u),this.#aa}set prevClickTimeoutDuration(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("prevClickTimeoutDuration must be a number.");if(e<0)throw new RangeError("prevClickTimeoutDuration cannot be negative.");this.#aa=e,this.emit("prevClickTimeoutDurationChange",this.#aa)}get repeatCurrentOnPrev(){return Qi(this.#u),this.#ea}set repeatCurrentOnPrev(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("repeatCurrentOnPrev must be a boolean.");this.#ea=e,this.emit("repeatCurrentOnPrevChange",this.#ea)}get smoothPlayPauseVolume(){return Qi(this.#u),this.#ra}set smoothPlayPauseVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("smoothPlayPauseVolume must be a boolean.");this.#ra=e,this.emit("smoothPlayPauseVolumeChange",this.#ra)}get smoothStopVolume(){return Qi(this.#u),this.#ia}set smoothStopVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("smoothStopVolume must be a boolean.");this.#ia=e,this.emit("smoothStopVolumeChange",this.#ia)}constructor(e={}){if(!E(e))throw new TypeError("Options must be a non-null object.");if(super({id:"[_main_class_TinyMediaPlayer_reset_]",logger:e.logger??console,debugMode:e.debugMode??!1,useLogColors:e.useLogColors??!1}),void 0!==e.persistVolume){if("boolean"!=typeof e.persistVolume)throw new TypeError("persistVolume must be a boolean.");this.#Qo=e.persistVolume}else this.#Qo=!1;if(void 0!==e.volumeStorageKey){if("string"!=typeof e.volumeStorageKey)throw new TypeError("volumeStorageKey must be a string.");this.#Zo=e.volumeStorageKey}else this.#Zo="tiny_media_player_volume";if(void 0!==e.repeatCurrentOnPrev){if("boolean"!=typeof e.repeatCurrentOnPrev)throw new TypeError("repeatCurrentOnPrev must be a boolean.");this.#ea=e.repeatCurrentOnPrev}else this.#ea=!1;if(void 0!==e.smoothPlayPauseVolume){if("boolean"!=typeof e.smoothPlayPauseVolume)throw new TypeError("smoothPlayPauseVolume must be a boolean.");this.#ra=e.smoothPlayPauseVolume}else this.#ra=!1;if(void 0!==e.smoothStopVolume){if("boolean"!=typeof e.smoothStopVolume)throw new TypeError("smoothStopVolume must be a boolean.");this.#ia=e.smoothStopVolume}else this.#ia=!1;this.#Qo&&this.#la(),this.log("info","Instance initialized.",{options:e})}#la(){try{if("undefined"!=typeof window&&window.localStorage){const e=window.localStorage.getItem(this.#Zo);if(null!==e){const t=parseFloat(e);!isNaN(t)&&t>=0&&t<=1&&(this.#Xo=t,this.log("info",`Volume loaded from storage: ${this.#Xo}`))}}}catch(e){console.warn("[TinyMediaPlayer] Failed to read volume from localStorage.",e)}}#ha(){try{this.#Qo&&"undefined"!=typeof window&&window.localStorage&&(window.localStorage.setItem(this.#Zo,this.#Xo.toString()),this.log("info",`Volume saved to storage: ${this.#Xo}`))}catch(e){console.warn("[TinyMediaPlayer] Failed to save volume to localStorage.",e)}}_getWeightedRandomIndex(){if(0===this.#Vo.length)return-1;if(1===this.#Vo.length)return 0;let e=0;for(let t=0;t<this.#Vo.length;t++){if(t===this.#Uo)continue;const r=this.#Vo[t];e+="number"==typeof r.weight&&r.weight>0?r.weight:1}let t=Math.random()*e;for(let e=0;e<this.#Vo.length;e++){if(e===this.#Uo)continue;const r=this.#Vo[e],i="number"==typeof r.weight&&r.weight>0?r.weight:1;if(t<i)return e;t-=i}return this.#Uo===this.#Vo.length-1?0:this.#Vo.length-1}async#ua(e){this.#sa&&this.#sa.abort(),this.#sa=new AbortController;const{signal:t}=this.#sa,r=this.#ca();if(!r)return;const i=r.getVolume(),s=performance.now(),n=this.#oa;return this.log("info",`Starting volume fade: ${i} -> ${e}`),new Promise(o=>{const a=l=>{if(t.aborted)return this.log("info","Volume fade aborted."),o();const h=l-s,u=Math.min(h/n,1),c=i+(e-i)*u,d=Math.max(0,Math.min(1,c));r.setVolume(d),u<1?requestAnimationFrame(a):(r.setVolume(e),this.log("info",`Volume fade completed: ${e}`),o())};requestAnimationFrame(a)})}get playlist(){return Qi(this.#u),[...this.#Vo]}set playlist(e){if(Qi(this.#u),!Array.isArray(e))throw new TypeError("Playlist must be an array of MediaContent objects.");e.forEach(e=>sr(e));const t=this.#Go;let r=null;if(-1!==this.#Uo&&this.#Vo.length>0)try{r=this.#ca()}catch(e){}this.#Vo=e,this.log("info",`Playlist updated. New size: ${this.#Vo.length}`),this.emit("playlistUpdate",this.playlist),0===this.#Vo.length?this.#Uo=-1:(this.#Uo>=this.#Vo.length||-1===this.#Uo)&&(this.#Uo=0),this.emit("trackChange",this.#Uo),t&&(async()=>{try{r&&await r.stop(),-1!==this.#Uo&&await this.play()}catch(e){this.log("error","Background transition error on playlist update:",e),console.warn("[TinyMediaPlayer] Background transition error on playlist update:",e)}})()}get currentIndex(){return Qi(this.#u),this.#Uo}set currentIndex(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Current index must be a number.");if(e<-1||e>=this.#Vo.length&&this.#Vo.length>0)throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);if(this.#Uo===e)return;this.log("info",`Index change requested: ${this.#Uo} -> ${e}`);const t=this.#Go;let r=null;if(-1!==this.#Uo&&this.#Vo.length>0)try{r=this.#ca()}catch(e){}this.#Uo=e,this.emit("trackChange",this.#Uo),t&&(async()=>{try{r&&await r.stop(),-1!==this.#Uo&&await this.play()}catch(e){this.log("error","Background transition error on index update:",e),console.warn("[TinyMediaPlayer] Background transition error on index update:",e)}})()}get loopMode(){return Qi(this.#u),this.#Ko}set loopMode(e){Qi(this.#u);const t=["NONE","TRACK","PLAYLIST"];if(!t.includes(e))throw new TypeError(`Loop mode must be one of: ${t.join(", ")}.`);this.#Ko=e,this.log("info",`Loop mode changed to: ${this.#Ko}`),this.emit("loopModeChange",this.#Ko)}get isRandom(){return Qi(this.#u),this.#Jo}set isRandom(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("Random mode state must be a boolean.");this.#Jo=e,this.log("info",`Random mode: ${this.#Jo}`),this.emit("randomModeChange",this.#Jo)}get isPlaying(){return Qi(this.#u),this.#Go}get volume(){return Qi(this.#u),this.#Xo}set volume(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Volume must be a number.");if(e<0||e>1)throw new RangeError("Volume must be tightly constrained between 0.0 and 1.0.");if(this.#sa&&this.#sa.abort(),this.log("info",`Volume changed: ${this.#Xo} -> ${e}`),this.#Xo=e,this.#ha(),this.emit("volumeChange",this.#Xo),-1!==this.#Uo&&this.#Vo.length>0)try{const e=this.#ca();e&&e.setVolume(this.#Xo)}catch(e){}}get persistVolume(){return Qi(this.#u),this.#Qo}set persistVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("Persist volume parameter must be a boolean.");this.#Qo=e,this.log("info",`Persist volume: ${this.#Qo}`),e&&this.#ha()}get volumeStorageKey(){return Qi(this.#u),this.#Zo}set volumeStorageKey(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Volume storage key must be a string.");if(""===e.trim())throw new TypeError("Volume storage key cannot be an empty string.");const t=this.#Zo;this.#Zo=e;try{this.#Qo&&"undefined"!=typeof window&&window.localStorage&&(window.localStorage.removeItem(t),this.#ha())}catch(e){console.warn("[TinyMediaPlayer] Failed to migrate volume storage key.",e)}}get isMuted(){return Qi(this.#u),this.#Yo}async mute(){Qi(this.#u);const e=this.#ca();e&&(await e.mute(),this.#Yo=!0,this.emit("muteChange",this.#Yo),this.log("info","Playback muted successfully."))}async unMute(){Qi(this.#u);const e=this.#ca();e&&(await e.unMute(),this.#Yo=!1,this.emit("muteChange",this.#Yo),this.log("info","Playback unmuted successfully."))}get adapters(){return Array.from(this.#Wo)}get adaptersSize(){return this.#Wo.size}static#da=["timeupdate","ended"];static get defaultAdapterEventNames(){return structuredClone(Zi.#da)}static set defaultAdapterEventNames(e){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError("TinyMediaPlayer.defaultAdapterEventNames must be an array of strings.");Zi.#da=[...e]}#pa=new Set(Zi.defaultAdapterEventNames);#ma(e){const t=this.#qo.get(e);t&&(this.#pa.forEach(r=>{const i=t.get(r);i&&e.off(r,i)}),t.clear(),this.#qo.delete(e))}registerAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");this.log("info","Registering new adapter:",e);const t=new Map;this.#qo.set(e,t),this.#pa.forEach(t=>{this.#fa(e,t)}),this.#Wo.add(e)}removeAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");return this.log("info","Removing adapter:",e),this.#ma(e),this.#Wo.delete(e)}destroyAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");this.log("info","Destroying adapter:",e),this.#ma(e);const t=this.#Wo.delete(e);return t&&e.destroy(),t}hasAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");return this.#Wo.has(e)}destroyAllAdapters(){Qi(this.#u),this.log("info","Destroying all adapters."),this.#Wo.forEach(e=>{this.#ma(e),e.destroy()}),this.#Wo.clear()}clearAdapters(){Qi(this.#u),this.log("info","Clearing all adapters."),this.#Wo.forEach(e=>this.#ma(e)),this.#Wo.clear()}getMediaAdapter(e){if(!E(e))throw new TypeError("Content must be a valid object.");for(const t of this.#Wo.values())if(t.canHandle(e))return t;return null}#ca(){if(-1===this.#Uo||0===this.#Vo.length)return null;const e=this.#Vo[this.#Uo],t=this.getMediaAdapter(e);if(t)return t;const r=`No compatible adapter found for content ID: ${e.id}.`;throw this.log("error",r),new Error(r)}addAdapterEvent(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");this.#pa.has(e)||(this.log("info",`Adding adapter event listener: ${e}`),this.#pa.add(e),this.#Wo.forEach(t=>{this.#fa(t,e)}))}removeAdapterEvent(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");this.#pa.has(e)&&(this.log("info",`Removing adapter event listener: ${e}`),this.#pa.delete(e),this.#Wo.forEach(t=>{this.#ya(t,e)}))}resetAdapterEvents(){Qi(this.#u);const e=Zi.defaultAdapterEventNames,t=Array.from(this.#pa);for(const r of t)e.includes(r)||this.removeAdapterEvent(r);for(const t of e)this.#pa.has(t)||this.addAdapterEvent(t)}#fa(e,t){const r=this.#qo.get(e);if(!r)return;const i=(...e)=>{this.#u||("timeupdate"!==t&&this.log("debug",`Adapter event triggered: ${t}`,...e),this.emit(t,...e))};e.on(t,i),r.set(t,i)}#ya(e,t){const r=this.#qo.get(e);if(!r)return;const i=r.get(t);i&&(e.off(t,i),r.delete(t))}addTrack(e){if(Qi(this.#u),!E(e)||"string"!=typeof e.url)throw new TypeError("Track content must be a valid MediaContent object containing a URL.");const t={id:"",title:"",artist:"",url:"",duration:0,weight:1,...e};sr(t);const r=this.#Vo.push(t);return this.log("info",`Track added. New length: ${r}`,t),-1===this.#Uo&&(this.#Uo=0,this.emit("trackChange",this.#Uo)),this.emit("playlistUpdate",this.playlist),r}existsTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");return e>=0&&e<this.#Vo.length}getTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);return this.#Vo[e]}async removeTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);this.log("info",`Removing track at index: ${e}`),e===this.#Uo?(await this.stop(),this.#Vo.splice(e,1),0===this.#Vo.length?this.#Uo=-1:this.#Uo>=this.#Vo.length&&(this.#Uo=0),this.emit("trackChange",this.#Uo)):(this.#Vo.splice(e,1),e<this.#Uo&&(this.#Uo-=1,this.emit("trackChange",this.#Uo))),this.emit("playlistUpdate",this.playlist)}searchTrack(e){if(Qi(this.#u),"string"!=typeof e&&"function"!=typeof e)throw new TypeError("Search query must be a string or a boolean evaluation function.");this.log("info","Searching playlist...",{query:e});const t=[];for(let r=0;r<this.#Vo.length;r++){const i=this.#Vo[r];let s=!1;if("function"==typeof e)s=Boolean(e(i));else{const t=e.toLowerCase(),r=i.title&&i.title.toLowerCase().includes(t),n=i.artist&&i.artist.toLowerCase().includes(t),o=i.album&&i.album.toLowerCase().includes(t);s=Boolean(r||n||o)}s&&t.push({track:i,index:r})}return this.log("info",`Search completed. Found ${t.length} results.`),t}async clearPlaylist(){Qi(this.#u),this.log("info","Clearing entire playlist."),await this.stop(),this.#Vo=[],this.#Uo=-1,this.emit("playlistUpdate",this.playlist),this.emit("trackChange",this.#Uo)}async play(){Qi(this.#u),this.log("info",`Attempting to play track at index: ${this.#Uo}`);const e=this.#ca();if(e){this.#ra?await this.#ua(this.#Xo):e.setVolume(this.#Xo);try{await e.play(this.#Vo[this.#Uo]),this.#Yo&&await e.mute(),this.#Go=!0,this.log("info","Playback started successfully."),this.emit("play",this.#Uo)}catch(e){throw this.log("error","Failed to play track:",e),e}}else this.log("error","Failed to play track:",`Active adapter not found for track at index ${this.#Uo}.`)}async pause(){Qi(this.#u),this.log("info","Attempting to pause playback.");const e=this.#ca();e&&(this.#ra&&await this.#ua(0),await e.pause(),this.#Go=!1,this.log("info","Playback paused."),this.emit("pause",this.#Uo))}async stop(){Qi(this.#u),this.log("info","Attempting to stop playback.");const e=this.#ca();e&&(this.#ia&&await this.#ua(0),await e.stop(),this.#Go=!1,this.log("info","Playback stopped."),this.emit("stop",this.#Uo))}async next(){if(Qi(this.#u),0!==this.#Vo.length){if(this.log("info","Next track requested."),await this.stop(),"TRACK"===this.#Ko)return this.log("info","Loop mode: TRACK. Repeating current track."),void await this.play();if(this.#Jo)this.#Uo=this._getWeightedRandomIndex(),this.log("info",`Random mode: Selected index ${this.#Uo}`);else{let e=this.#Uo+1;if(e>=this.#Vo.length){if("PLAYLIST"!==this.#Ko)return void this.log("info","End of playlist reached. Stopping.");e=0,this.log("info","Loop mode: PLAYLIST. Returning to start.")}this.#Uo=e}this.emit("trackChange",this.#Uo),await this.play()}}async prev(){if(Qi(this.#u),0!==this.#Vo.length){if(this.#ea&&!this.#ta)return this.log("info",'UX: Repeat current track on first "prev" click.'),this.#ta=!0,this.#na&&clearTimeout(this.#na),this.#na=setTimeout(()=>{this.#ta=!1,this.#na=null},2e3),await this.stop(),void await this.play();if(this.#na&&(clearTimeout(this.#na),this.#na=null),this.#ta=!1,this.log("info","Previous track requested."),await this.stop(),this.#Jo)this.#Uo=this._getWeightedRandomIndex(),this.log("info",`Random mode: Selected index ${this.#Uo}`);else{let e=this.#Uo-1;if(e<0){if("PLAYLIST"!==this.#Ko)return void this.log("info","Start of playlist reached. Stopping.");e=this.#Vo.length-1,this.log("info","Loop mode: PLAYLIST. Returning to end.")}this.#Uo=e}this.emit("trackChange",this.#Uo),await this.play()}}async skipTo(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);this.log("info",`Skipping to index: ${e}`),await this.stop(),this.#Uo=e,this.emit("trackChange",this.#Uo),await this.play()}async seek(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Seek time must be a number in milliseconds.");if(e<0)throw new RangeError("Seek time cannot be negative.");this.log("info",`Seeking to: ${e}ms`);const t=this.#ca();t&&(await t.seek(e),this.emit("seek",e))}async step(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Step amount must be a number in milliseconds.");this.log("info",`Stepping by: ${e}ms`);const t=this.#ca();if(!t)return;let r=t.getCurrentTime()+e;r<0&&(r=0),await this.seek(r)}getCurrentTime(){Qi(this.#u);try{const e=this.#ca();return e?e.getCurrentTime():0}catch{return 0}}getTotalDuration(){Qi(this.#u);try{const e=this.#ca();return e?e.getTotalDuration():0}catch{return 0}}getRemainingTime(){Qi(this.#u);try{const e=this.#ca();return e?e.getRemainingTime():0}catch{return 0}}getPlaybackPercentage(){Qi(this.#u);try{const e=this.#ca();return e?e.getPlaybackPercentage():0}catch{return 0}}get isPaused(){Qi(this.#u);try{const e=this.#ca();return!!e&&e.isPaused()}catch{return!1}}get isEnded(){Qi(this.#u);try{const e=this.#ca();return!e||e.isEnded()}catch{return!0}}async getContentData(){Qi(this.#u);const e={id:"",createdAt:"",artistId:"",artistName:"",description:"",title:"",duration:0,avatar:"",url:""};try{const t=this.#ca();return t?t.getContentData():e}catch{return e}}async waitIsReady(){Qi(this.#u);const e=this.#ca();if(e)return e.waitIsReady()}async destroy(){if(!this.#u){this.log("info","Destroying TinyMediaPlayer instance.");try{this.#Go&&await this.stop()}catch(e){this.log("error","Non-fatal error during playback termination:",e),console.warn("[TinyMediaPlayer] Non-fatal error during playback termination:",e)}this.#na&&clearTimeout(this.#na),this.#Vo=[],this.#Uo=-1,this.#Go=!1,this.#ta=!1,this.destroyAllAdapters(),this.removeAllListeners(),this.#pa.clear(),this.#u=!0,this.emit("destroyed")}}}const es=Zi,ts=class{#u=!1;get destroyed(){return this.#u}#vt;#ga=[];#wa=new WeakMap;#ba;constructor(e){if(!v(e))throw new TypeError('TinyUploadClicker: "options" must be a valid object.');this.#vt={multiple:!1,accept:"",inputAttributes:{},inputStyles:{display:"none"},onClick:null,onFileLoad:null,...e};const{triggers:t}=e;if(!(Array.isArray(t)||"string"==typeof t||t instanceof HTMLElement))throw new TypeError('TinyUploadClicker: "triggers" is required and must be a string, HTMLElement, or an array of them.');const r=(Array.isArray(this.#vt.triggers)?this.#vt.triggers:[this.#vt.triggers]).map(e=>{if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`TinyUploadClicker: No element found for selector "${e}".`);return t}if(!(e instanceof HTMLElement))throw new TypeError("TinyUploadClicker: All triggers must be either strings (selectors) or HTMLElements.");return e});if(void 0!==e.accept&&"string"!=typeof e.accept&&!Array.isArray(e.accept))throw new TypeError('TinyUploadClicker: "accept" must be a string or an array of strings.');if(void 0!==e.onClick&&"function"!=typeof e.onClick&&null!==e.onClick)throw new TypeError('TinyUploadClicker: "onClick" must be a function or null.');if(void 0!==e.onFileLoad&&"function"!=typeof e.onFileLoad&&null!==e.onFileLoad)throw new TypeError('TinyUploadClicker: "onFileLoad" must be a function or null.');if(void 0!==e.inputAttributes&&!v(e.inputAttributes))throw new TypeError('TinyUploadClicker: "inputAttributes" must be an object.');if(void 0!==e.inputStyles&&!v(e.inputStyles))throw new TypeError('TinyUploadClicker: "inputStyles" must be an object.');this.#ba=this.#va.bind(this),this.#ga=r,this.#ga.forEach(e=>{if(!(e instanceof HTMLElement))return;const t=document.createElement("input");t.type="file",this.#vt.multiple&&(t.multiple=!0),"string"==typeof this.#vt.accept?t.accept=this.#vt.accept:Array.isArray(this.#vt.accept)&&(t.accept=this.#vt.accept.join(","));const r=this.#vt.inputAttributes;if(r&&"object"==typeof r)for(const[e,i]of Object.entries(r))t.setAttribute(e,i);Object.assign(t.style,this.#vt.inputStyles||{display:"none"}),t.addEventListener("change",()=>{t.files&&"function"==typeof this.#vt.onFileLoad&&this.#vt.onFileLoad(t.files,e),t.value=""}),document.body.appendChild(t),this.#wa.set(e,t),e.addEventListener("click",this.#ba)})}#va(e){const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const r=this.#wa.get(t);r&&("function"==typeof this.#vt.onClick&&this.#vt.onClick(t),r.click())}destroy(){if(!this.destroyed){for(const e of this.#ga){if(!(e instanceof HTMLElement))return;e.removeEventListener("click",this.#ba);const t=this.#wa.get(e);t&&t.parentNode&&t.remove(),this.#wa.delete(e)}this.#ga=[],this.#u=!0}}};var rs=r(939);const is={header:"\n=== {projectName} ===\n",divider:"\n-----------------------------------------",itemValid:" [✔] {path}",itemInvalid:" [✘] {path}",itemMissing:" Missing: {errorPath}",successHeader:"SUCCESS: All exports are correctly mapped.",failureHeader:"FAILURE: {errorCount} export(s) are missing or invalid.",errorLoad:"Error: package.json not loaded in the current directory.",noExports:'[!] No "exports" field found in package.json.',errorNotFound:"Error: package.json not found in the current directory.",errorParse:"Error: Failed to parse package.json. Ensure it is valid JSON.",errorUnexpected:"An unexpected error occurred: {message}"},ss=Object.keys(is),ns=class{#Ea={RESET:"",GREEN:"",RED:"",YELLOW:"",CYAN:"",DIM:""};get COLORS(){return structuredClone(this.#Ea)}set COLORS(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("The provided configuration must be a non-null object.");const t=Object.keys(this.#Ea),r=Object.keys(e);if(t.length!==r.length||!t.every(e=>r.includes(e)))throw new TypeError("The new configuration must contain the exact same keys as the original color set.");for(const r of t)if("string"!=typeof e[r])throw new TypeError(`The value for key "${r}" must be a string.`);this.#Ea=structuredClone(e)}#Ta={};#Sa;#xa;#Aa;#Ca=!1;#Ia;#Da;#ka;get packageData(){return structuredClone(this.#Ta)}get packageJsonPath(){return this.#Sa}get rootDir(){return this.#xa}get results(){return structuredClone(this.#Aa)}get started(){return this.#Ca}get projectName(){return this.#Ia}get silent(){return this.#Da}constructor(e,t,r={}){if("string"!=typeof e)throw new TypeError('The "packageJsonPath" argument must be a string.');if("string"!=typeof t)throw new TypeError('The "rootDir" argument must be a string.');this.#Ma(r),this.#Sa=e,this.#xa=t,this.#Aa=[],this.#Ia=r.projectName??"Tiny-Essentials Export Validation",this.#Da=!!r.silent,this.#ka={...is,...r.messages??{}}}#Ma(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError('The "options" argument must be a non-null object.');if(void 0!==e.projectName&&"string"!=typeof e.projectName)throw new TypeError('The "options.projectName" property must be a string.');if(void 0!==e.silent&&"boolean"!=typeof e.silent)throw new TypeError('The "options.silent" property must be a boolean.');if(void 0!==e.messages){if("object"!=typeof e.messages||null===e.messages||Array.isArray(e.messages))throw new TypeError('The "options.messages" property must be a non-null object.');for(const t of ss)if("string"!=typeof e.messages[t])throw new TypeError(`The "options.messages.${t}" property must be a string.`)}}#La(e,t){if("string"!=typeof e)throw new TypeError("The template must be a string.");if("object"!=typeof t||null===t)throw new TypeError("The context must be a non-null object.");return e.replace(/{(\w+)}/g,(e,r)=>void 0!==t[r]?t[r]:e)}#Na(e,t,r={}){if(this.#Da)return;const i=["error","warning","success","info","dim","cyan"];if(!i.includes(e))throw new TypeError(`Invalid log type: "${e}". Valid types are: ${i.join(", ")}`);if("string"!=typeof t)throw new TypeError("The templateKey must be a string.");if("object"!=typeof r||null===r)throw new TypeError("The context must be a non-null object.");const s=this.#ka[t]||t,n=this.#La(s,{...r,projectName:this.#Ia});switch(e){case"error":console.error(`${this.#Ea.RED}${n}${this.#Ea.RESET}`);break;case"warning":console.log(`${this.#Ea.YELLOW}${n}${this.#Ea.RESET}`);break;case"success":console.log(`${this.#Ea.GREEN}${n}${this.#Ea.RESET}`);break;case"cyan":console.log(`${this.#Ea.CYAN}${n}${this.#Ea.RESET}`);break;case"dim":console.log(`${this.#Ea.DIM}${n}${this.#Ea.RESET}`);break;default:console.log(n)}}async execCommandTester(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError('The "actions" argument must be a non-null object.');if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))throw new TypeError('The "args" argument must be a string array.');const r=t[2],i=Object.keys(e);if(r)"function"==typeof e[r]?(this.#Na("cyan",`> Executing: ${r}`),await e[r]()):(this.#Na("error","errorUnexpected",{message:`Unknown argument: "${r}"`}),this.#Na("dim",`Valid arguments are: ${i.join(", ")}`));else{this.#Na("cyan","header"),this.#Na("dim","Running all registered commands...");for(const t of i)this.#Na("cyan",`> Executing: ${t}`),await e[t]()}}async start(){if(!this.#Ca){this.#Ca=!0;try{const e=await(0,rs.readFile)(this.#Sa,"utf-8"),t=JSON.parse(e);if("object"!=typeof t||null===t)throw this.#Ca=!1,new TypeError('The "packageData" argument must be a non-null object.');this.#Ta=t}catch(e){throw this.#Ca=!1,e}}}async validate(){if(!this.#Ca)return this.#Na("error","errorLoad"),!0;const e=this.#Ta.exports;if(!e)return this.#Na("warning","noExports"),!0;this.#Aa=[];try{await this.#_a(e)}catch(e){throw e instanceof Error&&(e instanceof SyntaxError?this.#Na("error","errorParse"):"code"in e&&"ENOENT"===e.code?this.#Na("error","errorNotFound"):this.#Na("error","errorUnexpected",{message:e.message})),e}return this.#Pa()}async#_a(e,t=""){if("string"!=typeof t)throw new TypeError('The "currentKey" argument must be a string.');if("string"==typeof e)await this.#Ra(e,t);else{if("object"!=typeof e||null===e)throw new TypeError('The "node" argument must be a string or a non-null object.');{const r=Object.keys(e);for(const i of r){const r=t?`${t} -> ${i}`:i;await this.#_a(e[i],r)}}}}async#Ra(e,r){if("string"!=typeof e)throw new TypeError('The "relativePath" argument must be a string.');if("string"!=typeof r)throw new TypeError('The "context" argument must be a string.');const i=e.replace(/\*/g,""),s=(0,t().resolve)(this.#xa,i);try{await(0,rs.access)(s),this.#Aa.push({path:r,valid:!0})}catch{this.#Aa.push({path:r,valid:!1,errorPath:e})}}#Pa(){this.#Na("cyan","header");let e=0;for(const t of this.#Aa)t.valid?this.#Na("success","itemValid",{path:t.path}):(this.#Na("error","itemInvalid",{path:t.path}),this.#Na("dim","itemMissing",{errorPath:t.errorPath}),e++);return this.#Na("cyan","divider"),0===e?(this.#Na("success","successHeader"),!0):(this.#Na("error","failureHeader",{errorCount:e}),!1)}},os=(e,t,r)=>{if(null===e||"string"!=typeof e&&!(e instanceof RegExp))throw new TypeError("The searchValue must be a string or a RegExp.");if("function"!=typeof t)throw new TypeError("The replaceValue must be a function.");if("object"!=typeof r||null===r)throw new TypeError("The errorConfig must be an object.");if("string"!=typeof r.pathPatternErrorMsg)throw new TypeError("The errorConfig.pathPatternErrorMsg property must be a string.");return i=>{if("string"!=typeof i)throw new TypeError(r.pathPatternErrorMsg);let s=!1;const n=[],o=i.replace(e,(e,...r)=>t(n,e,...r)),a=new RegExp(`^${o}$`);return{regex:a,paramNames:n,exec:e=>{const t={},r=e.match(a);return s=!0,r?(n.forEach((e,i)=>{t[e]=decodeURIComponent(r[i+1])}),{params:t,match:!0}):{params:t,match:!1}}}}},as=os(/:([^/]+)/g,(e,t,r)=>(e.push(r),"([^/]+)"),{pathPatternErrorMsg:'The argument must be a string (e.g., "/user/:id")'}),ls=le("TinyRouter"),{q:hs,N:us}=o,cs=class extends Ji{static SegmentExtractor=a;#ja=[];#Oa;#$a;#Ca=!1;#Ha;#Fa;#Kn=[];#za;#Ba=-1;#i=new ae;#hr=!1;constructor(e={}){if("object"!=typeof e||null===e)throw new TypeError("Options must be a non-null object.");if(void 0!==e.detectHistoryChange&&"boolean"!=typeof e.detectHistoryChange)throw new TypeError("detectHistoryChange must be a boolean.");if(void 0!==e.onRouteChanged&&"function"!=typeof e.onRouteChanged)throw new TypeError("onRouteChanged must be a function.");if(void 0!==e.onRouteNotFound&&"function"!=typeof e.onRouteNotFound)throw new TypeError("onRouteNotFound must be a function.");if(void 0!==e.historyLimit&&(!Number.isInteger(e.historyLimit)||e.historyLimit<-1))throw new TypeError("historyLimit must be an integer and greater than or equal to -1.");super({id:"[_main_class_TinyRouter_reset_]",logger:e.logger??console,debugMode:e.debugMode??!1,useLogColors:e.useLogColors??!1}),this.#Oa=e.onRouteChanged||(()=>{}),this.#$a=e.onRouteNotFound||(()=>{}),this.#Fa=e.detectHistoryChange??!0,this.#Ba=-1,this.#za=e.historyLimit??0,this.#Ha=this.#Wa.bind(this)}get isDestroyed(){return this.#hr}get historyIndex(){return ls(this.#hr),this.#Ba}get historyLimit(){return ls(this.#hr),this.#za}get detectHistoryChange(){return ls(this.#hr),this.#Fa}set detectHistoryChange(e){if(ls(this.#hr),"boolean"!=typeof e)throw new TypeError("detectHistoryChange must be a boolean.");this.#Fa=e}get onRouteChanged(){return ls(this.#hr),this.#Oa}set onRouteChanged(e){if(ls(this.#hr),"function"!=typeof e)throw new TypeError("onRouteChanged must be a function.");this.#Oa=e}get onRouteNotFound(){return ls(this.#hr),this.#$a}set onRouteNotFound(e){if(ls(this.#hr),"function"!=typeof e)throw new TypeError("onRouteNotFound must be a function.");this.#$a=e}get started(){return ls(this.#hr),this.#Ca}get size(){return ls(this.#hr),this.#ja.length}get routes(){return ls(this.#hr),this.#ja.map(e=>e.segmentExtractor.pattern??"")}get history(){return ls(this.#hr),this.#Kn.map(e=>({...e}))}set history(e){if(ls(this.#hr),!Array.isArray(e))throw new TypeError("History data must be an array.");for(const t of e){if("object"!=typeof t||null===t)throw new TypeError("Each history entry must be an object.");if("string"!=typeof t.path)throw new TypeError('Each history entry must have a string "path" property.');if("number"!=typeof t.timestamp)throw new TypeError('Each history entry must have a number "timestamp" property.')}this.#Kn=e.map(e=>({...e})),this.log("info","History has been successfully imported.")}add(e,t){ls(this.#hr);let r={};if("string"==typeof e)r=us(e),r.pattern=e;else{if("object"!=typeof e||null===e)throw new TypeError('The first argument must be a string (e.g., "/user/:id") or an object of SegmentExtractor maker.');if("function"==typeof e.callback){const t=e;t.callback(t.pattern)}else{const t=e;r=hs(t.searchValue,t.replaceValue,t.errorConfig)(t.pattern)}r.pattern=e.pattern}if("function"!=typeof t)throw new TypeError("The callback must be a function.");if(this.has(r.pattern))throw new Error(`Route with pattern "${r.pattern}" is already registered.`);this.#ja.push({segmentExtractor:r,callback:t}),this.emit("RouteAdded",r.pattern),this.log("info",`New route registered: ${r.pattern}`)}remove(e){if(ls(this.#hr),"string"!=typeof e)throw new TypeError("pathPattern must be a string.");const t=this.#ja.length;this.#ja=this.#ja.filter(t=>t.segmentExtractor.pattern!==e),this.#ja.length===t?this.log("warn",`Attempted to remove non-existent route: ${e}`):(this.emit("RouteRemoved",e),this.log("info",`Route removed: ${e}`))}has(e){if(ls(this.#hr),"string"!=typeof e)throw new TypeError("pathPattern must be a string.");return this.#ja.some(t=>t.segmentExtractor.pattern===e)}async navigate(e,t={}){ls(this.#hr),window.location.pathname+window.location.search!==e&&(window.history.pushState(t,"",e),await this.#i.enqueue(()=>this.#Wa()),this.log("info",`Navigated to: ${e}`))}start(){return this.#Ca?new Promise((e,t)=>t(new Error("Router has already been started."))):(this.#Ha=()=>{const e=window.location.pathname;if(0!==this.#za){const t=this.#Kn.findIndex(t=>t.path===e);-1!==t&&(this.#Ba=t)}return this.#Wa()},window.addEventListener("popstate",this.#Ha),this.#Ca=!0,this.#i.enqueue(()=>new Promise((e,t)=>{let r;try{ls(this.#hr)}catch(e){r=e}if(r)return t(r);this.#Wa().then(()=>{this.emit("RouterStarted"),this.log("info","Router started successfully."),e()}).catch(t)})))}stop(){ls(this.#hr),window.removeEventListener("popstate",this.#Ha),this.#Ca=!1,this.clearAll(),this.emit("RouterStopped"),this.log("info","Router stopped and event listeners removed.")}async go(e){if(ls(this.#hr),!this.#Ca)return this.log("warn","Attempted to navigate while the router is stopped."),!1;if(!Number.isInteger(e))throw new TypeError('The "delta" parameter must be an integer.');if(0!==this.#za){const t=this.#Ba+e;if(t>=0&&t<this.#Kn.length){const e=this.#Kn[t].path;return window.history.pushState(null,"",e),await this.#i.enqueue(()=>this.#Wa()),!0}return!1}if(!this.#Fa)return window.history.go(e),this.log("info",`Navigation command: go(${e}) (detection disabled)`),!0;const t=window.location.pathname+window.location.search;return this.#i.enqueue(()=>new Promise(r=>{const i=()=>{window.removeEventListener("popstate",i);const e=window.location.pathname+window.location.search;r(t!==e)};window.addEventListener("popstate",i),setTimeout(()=>{window.removeEventListener("popstate",i);const e=window.location.pathname+window.location.search;r(t!==e)},100),window.history.go(e),this.log("info",`Navigation command: go(${e})`)}))}async back(){return this.go(-1)}async forward(){return this.go(1)}#qa(e){ls(this.#hr),0!==this.#za&&(this.#Ba>=0&&this.#Kn[this.#Ba].path===e||(this.#Ba>=0&&(this.#Kn=this.#Kn.slice(0,this.#Ba+1)),this.#Kn.push({path:e,timestamp:Date.now()}),this.#Ba++,this.#za>0&&this.#Kn.length>this.#za&&(this.#Kn.shift(),this.#Ba--),this.emit("HistoryRecorded",{...this.#Kn[this.#Ba]})))}async#Wa(){ls(this.#hr);const e=window.location.pathname,t=window.location.search,r=new URLSearchParams(t);for(const t of this.#ja){const{params:i,match:s}=t.segmentExtractor.exec(e);if(s){const s={path:e,params:i,query:r};return this.#qa(e),this.emit("BeforeRouteChanged",s),await t.callback(s),this.#Oa(s),this.emit("AfterRouteChanged",s),void this.log("info",`Route matched: ${e}`)}}const i={path:e,query:r};this.#$a(i),this.emit("RouteNotFound",i),this.log("warn",`No route matched the current URL: ${e}`)}removeHistoryEntry(e){if(ls(this.#hr),!Number.isInteger(e))throw new TypeError("The index must be an integer.");if(e<0||e>=this.#Kn.length)throw new RangeError("The provided index is out of bounds.");this.#Kn.splice(e,1),this.emit("HistoryEntryRemoved",e),this.log("info",`History entry at index ${e} was removed.`)}clearHistory(){ls(this.#hr),this.#Kn=[],this.emit("HistoryCleared"),this.log("info","Navigation history has been cleared.")}clear(){ls(this.#hr),this.#ja=[],this.emit("RoutesCleared"),this.log("info","All routes have been cleared.")}clearAll(){ls(this.#hr),this.clear(),this.clearHistory()}destroy(){this.#hr||(this.stop(),this.#hr=!0)}},ds=e().EventEmitter;class ps extends ds{static#Va=new Set;static get activeInstances(){return Array.from(ps.#Va)}static get activeInstancesSize(){return ps.#Va.size}constructor(){super()}#Ua=new Map;#Ka=3e5;get ttl(){return this.#Ka}set ttl(e){if("number"!=typeof e)throw new TypeError("The TTL value must be a number.");if(e<0)throw new RangeError("The TTL value cannot be negative.");this.#Ka=e}get size(){return this.#Ua.size}has(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");return this.purgeExpired(!0),this.#Ua.has(e)}delete(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0);const t=this.#Ua.delete(e);if(t){const t={key:e};this.emit("delete",t)}return t}set(e,t){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0),ps.#Va.has(this)||ps.#Va.add(this),this.#Ua.set(e,{data:t,timestamp:Date.now()});const r={key:e,data:t};this.emit("set",r)}get(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0);const t=this.#Ua.get(e);return t?t.data:null}get[Symbol.toStringTag](){return"TinyMapCache"}keys(){return this.purgeExpired(!0),this.#Ja().map(([e])=>e).values()}values(){return this.purgeExpired(!0),this.#Ja().map(([,e])=>e).values()}entries(){return this.purgeExpired(!0),this.#Ja().values()}[Symbol.iterator](){return this.entries()}forEach(e,t){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.purgeExpired(!0);for(const[r,i]of this.#Ja())e.call(t,i,r,this)}#Ja(){const e=[];for(const[t,r]of this.#Ua.entries())e.push([t,r.data]);return e}purgeExpired(e=!1){const t=Date.now();let r=0;for(const[e,i]of this.#Ua.entries())if(t-i.timestamp>this.#Ka){this.#Ua.delete(e),r++;const t={key:e,data:i.data};this.emit("expire",t)}if(r>0){const e={count:r};this.emit("purge",e)}this.#Ua.size<1&&ps.#Va.delete(this),e&&ps.#Va.forEach(e=>{e!==this&&e.purgeExpired(!1)})}clear(){ps.#Va.delete(this),this.#Ua.clear(),this.emit("clear")}}const ms=ps;class fs{#Ga=0;#Ya=0;#Xa=0;#Qa=null;constructor(e){if("string"!=typeof e)throw new TypeError("[TinyVersion] Expected version to be a string, received type: "+typeof e);const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/),r=e=>{"string"==typeof e[1]&&(this.#Ga=parseInt(e[1],10)),"string"==typeof e[2]&&(this.#Ya=parseInt(e[2],10)),"string"==typeof e[3]&&(this.#Xa=parseInt(e[3],10)),"string"==typeof e[4]&&(this.#Qa=e[4])};if(t)r(t);else{const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(t)r(t);else{const t=e.match(/^(\d+)\.(\d+)$/);if(t)r(t);else{const t=e.match(/^(\d+)$/);if(!t)throw new Error(`[TinyVersion] Invalid version format: "${e}". Expected format: "X.Y.Z" or "X.Y.Z-tag".`);r(t)}}}}get major(){return this.#Ga}get minor(){return this.#Ya}get patch(){return this.#Xa}get tag(){return this.#Qa}isGreaterThan(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return this.#Ga!==e.major?this.#Ga>e.major:this.#Ya!==e.minor?this.#Ya>e.minor:this.#Xa!==e.patch?this.#Xa>e.patch:null===this.#Qa&&null!==e.tag||(null===this.#Qa||null!==e.tag)&&(null!==this.#Qa||null!==e.tag)&&(this.#Qa??"")>(e.tag??"")}isEqualTo(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return this.#Ga===e.major&&this.#Ya===e.minor&&this.#Xa===e.patch&&this.#Qa===e.tag}isLessThan(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return!this.isGreaterThan(e)&&!this.isEqualTo(e)}toString(){const e=`${this.#Ga}.${this.#Ya}.${this.#Xa}`;return this.#Qa?`${e}-${this.#Qa}`:e}}const ys=fs,gs=le("TinyPlugin"),ws=(e,t)=>t instanceof Set?t.has("*")||t.has(e):t.indexOf("*")>-1||t.indexOf(e)>-1;async function bs(e,t,r,i,s,n={name:"RSASSA-PKCS1-v1_5"}){if("string"!=typeof e||0===e.length)throw new TypeError("pluginId must be a non-empty string.");if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw new TypeError("authors must be an array of strings.");if(!Array.isArray(r)||r.some(e=>"string"!=typeof e))throw new TypeError("categories must be an array of strings.");if(!Array.isArray(i)||i.some(e=>"string"!=typeof e))throw new TypeError("tags must be an array of strings.");if(!(s instanceof CryptoKey))throw new TypeError("privateKey must be a valid CryptoKey instance.");const o={id:e,authors:[...t].sort(),categories:[...r].sort(),tags:[...i].sort()},a=JSON.stringify(o),l=(new TextEncoder).encode(a);try{return await crypto.subtle.sign(n,s,l)}catch(e){throw new Error(`Failed to sign plugin identity: ${e instanceof Error?e.message:"Unknown error"}`)}}const vs=(e,t,r,i)=>{if("string"!=typeof e)throw new TypeError("Security Error: Cryptographic mode enabled, but pluginId is missing.");if(!Array.isArray(t))throw new TypeError("Security Error: Cryptographic mode enabled, but authors is missing.");if(!t.every(e=>"string"==typeof e))throw new TypeError("Security Error: Cryptographic mode enabled, but authors is invalid.");return JSON.stringify({id:e,authors:[...t].sort(),categories:[...r].sort(),tags:[...i].sort()})},Es=(e,t,r)=>{const i=(e,t)=>{if(!Array.isArray(t)||!t.every(e=>"string"==typeof e||"symbol"==typeof e))throw new TypeError(`The ${e} of sandbox blacklist must be an array of strings.`)};if(v(r)&&v(e?.sandboxBlacklist)){const{get:t,set:s}=e.sandboxBlacklist;void 0!==t&&(i("get",t),t.forEach(e=>r.get.add(e))),void 0!==s&&(i("set",s),s.forEach(e=>r.set.add(e)))}if(v(e?.accessControl)){const{mode:r,whitelist:s,blacklist:n,publicKey:o,cryptoAlgorithm:a,importAlgorithm:l,importKeyFormat:h}=e.accessControl;if("none"!==r&&"whitelist"!==r&&"blacklist"!==r&&"cryptographic"!==r)throw new TypeError('accessControl.mode must be "none", "whitelist", "blacklist", or "cryptographic".');if("cryptographic"===r&&"string"!=typeof o)throw new TypeError("In cryptographic mode, accessControl.publicKey must be a string (PEM format).");v(s)&&(void 0!==s.ids&&(i("whitelist ids",s.ids),s.ids.forEach(e=>t.whitelist.ids.add(e))),void 0!==s.authors&&(i("whistlist authors",s.authors),s.authors.forEach(e=>t.whitelist.authors.add(e))),void 0!==s.categories&&(i("whistlist categories",s.categories),s.categories.forEach(e=>t.whitelist.categories.add(e))),void 0!==s.tags&&(i("whistlist tags",s.tags),s.tags.forEach(e=>t.whitelist.tags.add(e)))),v(n)&&(void 0!==n.ids&&(i("blacklist ids",n.ids),n.ids.forEach(e=>t.blacklist.ids.add(e))),void 0!==n.authors&&(i("blacklist authors",n.authors),n.authors.forEach(e=>t.blacklist.authors.add(e))),void 0!==n.categories&&(i("blacklist categories",n.categories),n.categories.forEach(e=>t.blacklist.categories.add(e))),void 0!==n.tags&&(i("blacklist tags",n.tags),n.tags.forEach(e=>t.blacklist.tags.add(e)))),"string"==typeof r&&(t.mode=r),"string"==typeof o&&(t.publicKey=o),void 0!==a&&(t.cryptoAlgorithm=a),void 0!==l&&(t.importAlgorithm=l),void 0!==h&&(t.importKeyFormat=h)}},Ts=e=>{const t=globalThis.atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer},Ss=async(e,t,r,i,s,n,o)=>{const{publicKey:a,cryptoAlgorithm:l,importKeyFormat:h,importAlgorithm:u}=e,c=vs(r,i,s,n);try{if("string"!=typeof a)throw new TypeError("Security Error: Cryptographic mode enabled, but public key is missing.");if(!("string"==typeof o||o instanceof ArrayBuffer||o instanceof Uint8Array))throw new TypeError("Security Error: Cryptographic mode enabled, but signature is invalid (must be string, ArrayBuffer, or Uint8Array).");const e=(new TextEncoder).encode(c);let i;i="spki"===h||"pkcs8"===h?(e=>{const t=e.replace(/(-----(BEGIN|END) [^-]+-----)/g,"").replace(/\s+/g,"");return Ts(t)})(a):"string"==typeof a?Ts(a):a;const s="string"==typeof o?Ts(o):o,n=await crypto.subtle.importKey(h,i,u,!1,["verify"]),d=await crypto.subtle.verify(l,n,s,e);return d&&t.add(r),d}catch(e){return console.error(e),!1}},xs=(e,t,r,i,s,n,o,a)=>{if("cryptographic"===e)return a.has(t);if("whitelist"===e){const e=ws(t,n.ids),o=r.some(e=>ws(e,n.authors)),a=i.some(e=>ws(e,n.categories)),l=s.some(e=>ws(e,n.tags));return e||o||a||l}if("blacklist"===e){const e=ws(t,o.ids),n=r.some(e=>ws(e,o.authors)),a=i.some(e=>ws(e,o.categories)),l=s.some(e=>ws(e,o.tags));return!(e||n||a||l)}return!0},As=()=>({mode:"none",importKeyFormat:"spki",importAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},cryptoAlgorithm:{name:"RSASSA-PKCS1-v1_5"},publicKey:null,whitelist:{ids:new Set,authors:new Set,categories:new Set,tags:new Set},blacklist:{ids:new Set,authors:new Set,categories:new Set,tags:new Set}}),Cs=(e,t,r,i,s,n,o)=>{const a=[...i],l=[...s],h=t??{get:[],set:[]},u=[...n??[],...h.get],c=[...u,...h.set,...o??[]];return v(r)&&(u.forEach(e=>r.get.add(e)),c.forEach(e=>r.set.add(e))),new Proxy(e,{get(e,t){if(l.includes(t)||l.includes("*")){const r=Reflect.get(e,t,e);return"function"==typeof r?r.bind(e):r}throw new Error(`Security Error: Access to property "${String(t)}" is denied by the sandbox.`)},set(e,t,r){if(a.includes(t)||a.includes("*"))return Reflect.set(e,t,r);throw new Error("Security Error: Cannot modify read-only properties on the plugin sandbox.")},setPrototypeOf(){throw new Error("Security Error: Prototype manipulation is forbidden.")}})};class Is extends Ji{#Za=!1;#el=new Set;#tl=As();get isReady(){return this.#Za}get accessControlWhitelist(){return Object.freeze({ids:Object.freeze([...this.#tl.whitelist.ids]),authors:Object.freeze([...this.#tl.whitelist.authors]),categories:Object.freeze([...this.#tl.whitelist.categories]),tags:Object.freeze([...this.#tl.whitelist.tags])})}get accessControlBlacklist(){return Object.freeze({ids:Object.freeze([...this.#tl.blacklist.ids]),authors:Object.freeze([...this.#tl.blacklist.authors]),categories:Object.freeze([...this.#tl.blacklist.categories]),tags:Object.freeze([...this.#tl.blacklist.tags])})}get accessControlMode(){return this.#tl.mode}constructor(e){super(e?.logCfg??{id:"[_main_class_TinyPluginLayer_reset_]",logger:console,autoHideId:!0,debugMode:!1,useLogColors:!1}),Es(e??{},this.#tl)}_startLayer(e,t,...r){if(this.#Za)throw new Error("TinyPluginLayer: The layer has already been initialized.");return this.logSubId=e.logSubId,"function"==typeof t&&t(...r),this.#Za=!0,this}canAccessLayer(e,t,r,i){const{mode:s,whitelist:n,blacklist:o}=this.#tl;return xs(s,e,t,r,i,n,o,this.#el)}async verifyPluginSignature(e,t,r,i,s){return Ss(this.#tl,this.#el,e,t,r,i,s)}_createSandbox(e,t){return Cs(this,null,null,[...e],["isReady","accessControlMode","accessControlWhitelist","accessControlBlacklist","verifyPluginSignature","canAccessLayer",...t])}}class Ds extends Ji{static#rl=Is;static get TinyPluginLayer(){return Ds.#rl}static#il="pluginsDestroyed";#sl={get:new Set,set:new Set};#tl=As();#el=new Set;static get pluginsDestroyEventName(){return Ds.pluginsDestroyEventName}static set pluginsDestroyEventName(e){if("string"!=typeof e)throw new TypeError("pluginsDestroyEventName must be a string.");Ds.pluginsDestroyEventName=e}#nl=new Map;get sandboxBlacklist(){return Object.freeze({set:Object.freeze([...this.#sl.set]),get:Object.freeze([...this.#sl.get])})}get plugins(){return Object.fromEntries(this.#nl)}get pluginsSize(){return this.#nl.size}get accessControlWhitelist(){return Object.freeze({ids:Object.freeze([...this.#tl.whitelist.ids]),authors:Object.freeze([...this.#tl.whitelist.authors]),categories:Object.freeze([...this.#tl.whitelist.categories]),tags:Object.freeze([...this.#tl.whitelist.tags])})}get accessControlBlacklist(){return Object.freeze({ids:Object.freeze([...this.#tl.blacklist.ids]),authors:Object.freeze([...this.#tl.blacklist.authors]),categories:Object.freeze([...this.#tl.blacklist.categories]),tags:Object.freeze([...this.#tl.blacklist.tags])})}get accessControlMode(){return this.#tl.mode}constructor(e){super(e.logCfg),Es(e,this.#tl,this.#sl)}canAccessEngine(e,t,r,i){const{mode:s,whitelist:n,blacklist:o}=this.#tl;return xs(s,e,t,r,i,n,o,this.#el)}async verifyPluginSignature(e,t,r,i,s){return Ss(this.#tl,this.#el,e,t,r,i,s)}_addPlugin(e){if(!(e instanceof ks))throw new TypeError("The provided plugin must be an instance of TinyPlugin.");if(!this.canAccessEngine(e.id,e.authors,e.categories,e.tags))throw new Error(`Security Error: Access to the core is denied for plugin "${e.id}" based on current access control rules.`);this.#nl.set(e.id,e)}installPlugin(e,...t){return ks._addModuleToCore(this,e,...t)}hasPlugin(e){return this.#nl.has("string"==typeof e?e:e.id)}getPlugin(e){const t=this.#nl.get(e);return t&&!t.isDestroyed?t:void 0}_getPlugin(e,t){if(!(t instanceof ks))throw new TypeError("The provided external plugin must be an instance of TinyPlugin.");const r=this.#nl.get(e);if(r&&!r.isDestroyed){if(!r.layer.canAccessLayer(t.id,t.authors,t.categories,t.tags))throw new Error(`Security Error: Access to the plugin "${e}" is denied for plugin "${t.id}" based on current plugin access control rules.`);return r}}destroyPlugins(){this.#el.clear(),this.#nl.forEach(e=>e.destroy()),this.emit(Ds.#il)}}class ks extends Ji{static#ol={id:"[_main_class_TinyPlugin_reset_]",autoHideId:!0,logger:console,debugMode:!1,canEmitLogs:!1,useLogColors:!0};static get logCfg(){return{...ks.#ol}}static set logCfg(e){this.#ol=e}static _addModuleToCore(e,t,...r){if(!(e instanceof Ds))throw new TypeError("The provided engine must be an instance of TinyPluginCore.");const i=new ks({engine:e,installer:t,logCfg:{...ks.#ol,debugMode:e.debugMode}},...r);if(i._startPlugin(),e.hasPlugin(i))throw new Error(`A plugin with the name "${i.id}" is already registered.`);return e._addPlugin(i),i}#sl={get:new Set,set:new Set};#al="";#ll="";#hl=new Set;#ul=new Set;#cl=new Set;#dl=new Set;#ee=null;#pl;#ml;#wn;#Za=!1;#fl=null;#hr=!1;#yl=new Set;#gl=new Set;get isDestroyed(){return this.#hr}get plugins(){return gs(this.#hr),Object.keys(this.#pl.plugins)}get pluginsSize(){return gs(this.#hr),this.#pl.pluginsSize}getPlugin(e){return gs(this.#hr),this.#pl._getPlugin(e,this)}hasPlugin(e){return gs(this.#hr),this.#pl.hasPlugin(e)}get isReady(){return gs(this.#hr),this.#Za}get id(){if(gs(this.#hr),0===this.#al.length)throw new Error("Plugin id is not set.");return this.#al}set id(e){if(gs(this.#hr),0!==this.#al.length)throw new Error("Id is already set.");if("string"!=typeof e)throw new TypeError("Id must be a string.");if(0===e.length)throw new TypeError("Id cannot be empty.");this.#al=e,this.logSubId=`${this.#pl.logId} [_sub_class_${e}_reset_]`}get description(){if(gs(this.#hr),0===this.#ll.length)throw new Error("Plugin description is not set.");return this.#ll}set description(e){if(gs(this.#hr),0!==this.#ll.length)throw new Error("Description is already set.");if("string"!=typeof e)throw new TypeError("Description must be a string.");if(0===e.length)throw new TypeError("Description cannot be empty.");this.#ll=e}get authors(){if(gs(this.#hr),0===this.#hl.size)throw new Error("Plugin authors is not set.");return Object.freeze([...this.#hl])}set authors(e){if(gs(this.#hr),0!==this.#hl.size)throw new Error("Authors is already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Authors must be a array of non-empty strings.");if(0===e.length)throw new TypeError("Authors cannot be empty.");e.forEach(e=>this.#hl.add(e))}get contributors(){if(gs(this.#hr),0===this.#ul.size)throw new Error("Plugin contributors is not set.");return Object.freeze([...this.#ul])}set contributors(e){if(gs(this.#hr),0!==this.#ul.size)throw new Error("Authors is already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Authors must be a array of non-empty strings.");if(0===e.length)throw new TypeError("Authors cannot be empty.");e.forEach(e=>this.#ul.add(e))}get categories(){if(gs(this.#hr),0===this.#cl.size)throw new Error("Plugin categories are not set.");return Object.freeze([...this.#cl])}set categories(e){if(gs(this.#hr),0!==this.#cl.size)throw new Error("Categories are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Categories must be an array of non-empty strings.");if(0===e.length)throw new TypeError("Categories cannot be empty.");e.forEach(e=>this.#cl.add(e))}get tags(){if(gs(this.#hr),0===this.#dl.size)throw new Error("Plugin tags are not set.");return Object.freeze([...this.#dl])}set tags(e){if(gs(this.#hr),0!==this.#dl.size)throw new Error("Tags are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Tags must be an array of non-empty strings.");if(0===e.length)throw new TypeError("Tags cannot be empty.");e.forEach(e=>this.#dl.add(e))}get allowedSets(){return gs(this.#hr),[...this.#gl]}set allowedSets(e){if(gs(this.#hr),0!==this.#gl.size||this.#Za)throw new Error("AllowedSets are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("AllowedSets must be an array of non-empty strings.");if(0===e.length)throw new TypeError("AllowedSets cannot be empty.");e.forEach(e=>this.#gl.add(e))}get allowedGets(){return gs(this.#hr),[...this.#yl]}set allowedGets(e){if(gs(this.#hr),0!==this.#yl.size||this.#Za)throw new Error("AllowedGets are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("AllowedGets must be an array of non-empty strings.");if(0===e.length)throw new TypeError("AllowedGets cannot be empty.");e.forEach(e=>this.#yl.add(e))}get version(){if(gs(this.#hr),!this.#ee)throw new Error("Plugin version is not set.");return this.#ee.toString()}set version(e){if(gs(this.#hr),this.#ee)throw new Error("Version is already set.");if("string"!=typeof e)throw new TypeError("Version must be a string.");if(0===e.length)throw new TypeError("Version cannot be empty.");this.#ee=new ys(e)}get tinyVersion(){if(gs(this.#hr),!this.#ee)throw new Error("Plugin version is not set.");return this.#ee}get layer(){if(gs(this.#hr),null===this.#fl)throw new Error("Plugin layer is not set.");return this.#fl._createSandbox([...this.#gl],[...this.#yl])}get engine(){if(gs(this.#hr),!this.#pl.canAccessEngine(this.#al,[...this.#hl],[...this.#cl],[...this.#dl]))throw new Error(`Security Error: Access to the engine is denied for plugin "${this.id}" based on current access control rules.`);const e=this.#sl;return new Proxy(this.#pl,{get(t,r){if(e.get.has(r))throw new Error(`Security Error: Access to property "${String(r)}" is denied by the sandbox.`);const i=Reflect.get(t,r,t);return"function"==typeof i?i.bind(t):i},set(t,r,i){if(e.set.has(r))throw new Error("Security Error: Cannot modify read-only properties on the plugin sandbox.");return Reflect.set(t,r,i)},setPrototypeOf(){throw new Error("Security Error: Prototype manipulation is forbidden.")}})}get options(){return gs(this.#hr),this.#wn}get engineBlacklist(){return gs(this.#hr),this.#pl.sandboxBlacklist}constructor({engine:e,logCfg:t,installer:r},...i){super(t),this.#pl=e,this.#ml=r,this.#wn=i}#wl(){const e=["id","version","description","authors","contributors","categories","tags","allowedGets","allowedSets"];return Cs(this,this.#pl.sandboxBlacklist,this.#sl,e,[...e,"tinyVersion","isReady","layer","options","engine","engineBlacklist","isDestroyed","pluginsSize","plugins","hasPlugin","getPlugin","log","logClear","logGroupEnd","logLabel","logTimeLabel","logAssert","logDir","logTable","toConsole","isDestroyed"],["getPlugin","_getPlugin","plugins","installPlugin","_addPlugin","destroyPlugins"],["accessControlMode","accessControlWhitelist","accessControlBlacklist","verifyPluginSignature","canAccessEngine"])}_startPlugin(){if(gs(this.#hr),this.#Za)throw new Error("Plugin is already ready.");this.#wn&&Object.freeze(this.#wn);const e=this.#wl();try{if(this.#fl=this.#ml(e,...this.#wn),!(this.#fl instanceof Is))throw new TypeError("Plugin layer is not a valid TinyPluginLayer instance.");if(this.#fl.debugMode=this.debugMode,this.#fl.isReady||this.#fl._startLayer(this),0===this.#al.length)throw new Error("Plugin id is not set.");if(0===this.#ll.length)throw new Error("Plugin description is not set.");if(0===this.#hl.size)throw new Error("Plugin authors are not set.");if(0===this.#ul.size)throw new Error("Plugin contributors are not set.");if(0===this.#cl.size)throw new Error("Plugin categories are not set.");if(0===this.#dl.size)throw new Error("Plugin tags are not set.");if(!this.#ee)throw new Error("Plugin version is not set.");this.#Za=!0}catch(e){throw this.emit("error",e),this.destroy(),new Error(`Plugin initialization failed: ${e instanceof Error?e.message:"Unknown Error"}`)}}destroy(){this.#hr||(this.emit("destroyed"),this.#fl?.emit("destroyed"),this.#hr=!0)}}const Ms=Object.freeze({NOTIFICATION:"notification",DATA:"data",SYNC:"sync",COMMAND:"command",UNKNOWN:"unknown"});class Ls{static PUSH_TYPE=Ms;static#bl=Object.freeze(["actions","badge"]);static toBrowser(e,t={}){if(null!==e&&("object"!=typeof e||Array.isArray(e)))throw new TypeError("[TinyNotificationAdapter] toBrowser: notification must be a non-null object.");if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("[TinyNotificationAdapter] toBrowser: overrides must be a non-null object.");const{title:r,...i}=e??{},s={};for(const[e,t]of Object.entries(i))Ls.#bl.includes(e)||void 0!==t&&(s[e]=t);return"auto"!==s.dir&&"ltr"!==s.dir&&"rtl"!==s.dir&&delete s.dir,!0===s.renotify&&"string"!=typeof s.tag&&delete s.renotify,{title:"string"==typeof r&&""!==r?r:"Notification",options:{...s,...t}}}static toServiceWorker(e,t={}){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("[TinyNotificationAdapter] toServiceWorker: notification must be a non-null object.");if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("[TinyNotificationAdapter] toServiceWorker: overrides must be a non-null object.");const{title:r="Notification",options:i={}}=e,s={...i,...t};return{title:r,body:"string"==typeof s.body?s.body:"",options:s}}}const Ns=Ls,_s=async()=>{if(!("Notification"in window))throw new Error("Notification API is not supported in this browser.");return"granted"===Notification.permission?"granted":"denied"===Notification.permission?"denied":await Notification.requestPermission()},Ps=le("TinyServiceWorker"),Rs=(e,t)=>{if(!("serviceWorker"in navigator)||!navigator.serviceWorker.controller)throw new Error("Service Worker is not available or not controlling the page.");return navigator.serviceWorker.controller.postMessage(e,t??[])};class js extends Ds{static postMessage=Rs;static#vl=Ms;static get PUSH_TYPE(){return js.#vl}static#El(e){if("string"!=typeof e||""===e.trim())throw new TypeError("The event type must be a non-empty string.");if(e.startsWith("sw:"))throw new TypeError(`The event type "${e}" is reserved for internal PWA lifecycle management and cannot be used for Service Worker messaging.`)}static#Tl(e){if("string"!=typeof e||""===e.trim())throw new TypeError("The event name must be a non-empty string.")}static async waitForReady(){return navigator.serviceWorker.ready}#Sl=null;#al;#xl;#ee;#Za=!1;#Al=!1;#Cl=null;#Il=null;#Dl="browser";#kl=new Map;#Ml=new Map;#Ll=null;#Nl=null;#_l=null;#Pl=new(e().EventEmitter);#hr=!1;#Rl=new Set;get pushEvents(){return this.#Pl}get isReady(){return this.#Za}get isFailed(){return this.#Al}get isDestroyed(){return this.#hr}#jl(){this.emit("sw:NoSwControllerWarn"),this.log("warn","No active controller to receive message.")}get isSwAvailable(){return Ps(this.#hr),"serviceWorker"in navigator&&!!navigator.serviceWorker.controller}get id(){return Ps(this.#hr),this.#al}get swUrl(){return Ps(this.#hr),this.#xl}get version(){return Ps(this.#hr),this.#ee}get registration(){return Ps(this.#hr),this.#Sl}#Ol=new Set;get eventListeners(){return Ps(this.#hr),Array.from(this.#Ol)}get displayMode(){return Ps(this.#hr),this.#Dl}#$l=!0;get autoNotifyPush(){return Ps(this.#hr),this.#$l}set autoNotifyPush(e){if(Ps(this.#hr),"boolean"!=typeof e)throw new TypeError("autoNotifyPush must be a boolean.");this.#$l=e}get eventBlacklist(){return Ps(this.#hr),Array.from(this.#Rl)}addToEventBlacklist(e){Ps(this.#hr),js.#Tl(e),this.#Rl.add(e)}removeFromEventBlacklist(e){return Ps(this.#hr),js.#Tl(e),this.#Rl.delete(e)}hasInEventBlacklist(e){return Ps(this.#hr),js.#Tl(e),this.#Rl.has(e)}clearEventBlacklist(){Ps(this.#hr),this.#Rl.clear()}constructor(e){if(Array.isArray(e)||"object"!=typeof e||null===e)throw new TypeError('The "options" argument must be a non-null object.');const{id:t,swUrl:r,version:i,logger:s,debugMode:n,useLogColors:o}=e;if("string"!=typeof t||""===t.trim())throw new TypeError('The "id" parameter must be a non-empty string.');if("string"!=typeof r&&!(r instanceof URL))throw new TypeError('The "swUrl" parameter must be a string or URL.');if("string"!=typeof i)throw new TypeError('The "version" parameter must be a string.');super({logCfg:{id:"[_sub_class_TinyServiceWorker_reset_]",logger:s??console,debugMode:n??!1,useLogColors:o??!1}}),this.#al=t,this.#xl=r,this.#ee=i,this.#Hl()}#Hl(){const e=window.matchMedia("(display-mode: standalone)").matches;document.referrer.startsWith("android-app://")?this.#Dl="twa":navigator.standalone||e?this.#Dl="standalone":this.#Dl="browser",this.emit("sw:DisplayModeChanged",{displayMode:this.#Dl}),this.log("info",`DISPLAY_MODE_CHANGED: ${this.#Dl}`)}#Fl(){this.#Ll=()=>this.#Hl(),window.matchMedia("(display-mode: standalone)").addEventListener("change",this.#Ll),this.#Nl=e=>{this.#Il=e,this.emit("sw:BeforeInstallPrompt",{event:e}),this.log("info","beforeinstallprompt event fired.")},window.addEventListener("beforeinstallprompt",this.#Nl),this.#_l=()=>{this.#Il=null,this.emit("sw:AppInstalled"),this.log("info","PWA was installed")},window.addEventListener("appinstalled",this.#_l)}async promptInstallation(){if(Ps(this.#hr),!this.#Il)throw new Error("Cannot show installation prompt: beforeinstallprompt event has not fired.");this.#Il.prompt();const{outcome:e}=await this.#Il.userChoice;this.log("info",`User installation choice: ${e}`),this.#Il=null}async waitForReady(){if(Ps(this.#hr),this.#Al)throw new Error("Service Worker registration failed. Cannot wait for ready state.");if(!this.#Za||!navigator.serviceWorker.controller)return new Promise((e,t)=>{const r=()=>{this.#Za&&navigator.serviceWorker.controller&&(s(),e())},i=e=>{s(),t(e instanceof Error?e:new Error(String(e)))},s=()=>{navigator.serviceWorker.removeEventListener("controllerchange",r),this.off("sw:RegistrationFailed",i)};navigator.serviceWorker.addEventListener("controllerchange",r),this.on("sw:RegistrationFailed",i),this.#Za&&navigator.serviceWorker.controller&&(s(),e())})}async registerSync(e){if(Ps(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError("[TinyServiceWorker] registerSync: tag must be a non-empty string.");const t=await js.waitForReady();if(!t.sync)throw new Error("[TinyServiceWorker] registerSync: Background Sync API is not supported in this browser.");try{await t.sync.register(e),this.log("info",`Sync tag registered: ${e}`)}catch(t){throw this.log("error",`Failed to register sync tag "${e}":`,t),t}}async requestNotificationPermission(){Ps(this.#hr);try{const e=await _s();return"granted"===e?(this.emit("sw:NotificationPermissionChanged",{permission:"granted"}),e):"denied"===e?(this.log("warn","Notification permission was denied by the user."),this.emit("sw:NotificationPermissionChanged",{permission:"denied"}),e):(this.log("info",`Notification permission status: ${e}`),this.emit("sw:NotificationPermissionChanged",{permission:e}),e)}catch(e){throw this.log("error","Error requesting notification permission:",e),e}}#zl(e,t){const r=!0===e.notificationShown,i=e.notification??null,s=(e={})=>{if(!("Notification"in window))return this.log("warn","Push received, but the Notification API is not supported."),null;const t=Ns.toBrowser(i,e),r=new Notification(t.title,t.options),s=e=>{const r=Ns.toServiceWorker(t);this.#Bl(e,r,!1)};return r.onclick=()=>s("sw:NotificationClicked"),r.onclose=()=>s("sw:NotificationClosed"),r};!r&&"browser"===this.displayMode&&this.#$l&&s(),this.#Pl.emit(e.topic??"push",{data:{...e,notificationShown:r},event:t,notificationShown:r,showNotification:s})}async register(e){if(Ps(this.#hr),void 0!==e&&(Array.isArray(e)||"object"!=typeof e||null===e))throw new TypeError('The "options" argument must be a non-null object.');if("serviceWorker"in navigator)try{const t=`${this.#al}_sw_version`,r=localStorage.getItem(t);r!==this.#ee&&(this.log("warn",`Version mismatch detected: ${r} -> ${this.#ee}. Signaling update...`),this.emit("sw:VersionUpdateAvailable"),this.#Bl("sw:PrepareUpdate"),localStorage.setItem(t,this.#ee));const i=new URL(this.#xl,location.origin);i.searchParams.set("v",this.#ee),this.debugMode&&i.searchParams.set("t",Date.now().toString()),this.#Sl=await navigator.serviceWorker.register(i.toString(),e),navigator.serviceWorker.addEventListener("controllerchange",e=>{this.emit("sw:NewVersionReady",{event:e}),this.log("info","New Service Worker is now in control.")}),this.#Cl=e=>{const t=e.data;if(!Array.isArray(t)&&"object"==typeof t&&null!==t&&"string"==typeof t.type)if(this.#Rl.has(t.type))this.log("warn",`Ignored blacklisted event: ${t.type}`);else if(void 0===t.data||!Array.isArray(t.data)&&"object"==typeof t.data&&null!==t.data)if("sw:PushReceived"!==t.type){if("sw:ApiResponse"===t.type){if("string"!=typeof t.correlationId)return void this.log("error",'Received message with missing or invalid "correlationId" string.');const e=this.#kl.get(t.correlationId);return void(e&&(clearTimeout(e.timer),this.#kl.delete(t.correlationId),t.error?e.reject(new Error(t.error)):e.resolve(t.data)))}if(!0===t.isApi){if("string"!=typeof t.correlationId)return void this.log("error",'Received message with missing or invalid "correlationId" string.');const e=this.#Ml.get(t.type);if(!e)return void Rs({correlationId:t.correlationId,type:"sw:ApiResponse",error:`No API handler registered for type: ${t.type}`});try{const r=e=>Rs({correlationId:t.correlationId,type:"sw:ApiResponse",data:e}),i=e({data:t.data,correlationId:t.correlationId});i instanceof Promise?i.then(r):r(i)}catch(e){Rs({correlationId:t.correlationId,type:"sw:ApiResponse",error:e instanceof Error?e.message:String(e)})}return}this.emit(t.type,{data:t.data,event:e})}else this.#zl(t.data,e)},navigator.serviceWorker.addEventListener("message",this.#Cl),this.#Fl(),this.#Za=!0,this.log("info","Registered successfully.")}catch(e){this.#Al=!0,this.log("error","Registration error:",e)}else this.log("warn","Service Worker is not supported in this browser.")}async unregister(){if(Ps(this.#hr),!this.#Sl)return this.log("warn","No active ServiceWorkerRegistration found to unregister."),this.destroy(),!1;try{const e=await this.#Sl.unregister();return e?this.log("info","Service Worker unregistered successfully."):this.log("warn","The unregister() method returned false (the worker might already be inactive)."),this.destroy(),e}catch(e){throw this.log("error","Error during Service Worker unregistration:",e),e}}#Bl(e,t,r=!1){if(Ps(this.#hr),"string"!=typeof e)throw new TypeError("Payload.type must be a string.");if("boolean"!=typeof r)throw new TypeError('The "strictMode" argument must be a boolean.');if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError("Payload.data must be a non-null object.");return r&&js.#El(e),"serviceWorker"in navigator&&navigator.serviceWorker.controller?(navigator.serviceWorker.controller.postMessage({type:e,data:t}),!0):(this.#jl(),!1)}offApi(e){if("string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');return this.#Ml.delete(e)}onApi(e,t){if("string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');if("function"!=typeof t)throw new TypeError("Callback must be a function.");this.#Ml.set(e,t)}async emitApi(e,t,r=1e4){if(Ps(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError('The "data" argument must be a non-null object.');if("number"!=typeof r)throw new TypeError('The "timeout" argument must be a number.');if(!Number.isFinite(r)||r<0)throw new RangeError('The "timeout" argument must be a finite number greater than or equal to 0.');const i=crypto.randomUUID();return new Promise((s,n)=>{const o=setTimeout(()=>{this.#kl.has(i)&&(this.#kl.delete(i),n(new Error(`API request timeout: ${e} (ID: ${i})`)))},r);this.#kl.set(i,{resolve:s,reject:n,timer:o}),Rs({type:e,data:t,correlationId:i,isApi:!0})})}emitMessage(e,t){return this.#Bl(e,t,!0)}postMessage(e){if(Ps(this.#hr),Array.isArray(e)||"object"!=typeof e||null===e)throw new TypeError("Payload must be an object.");if("string"!=typeof e.type)throw new TypeError("Payload.type must be a string.");if(void 0!==e.data&&(Array.isArray(e.data)||"object"!=typeof e.data||null===e.data))throw new TypeError("Payload.data must be a non-null object.");js.#El(e.type),"serviceWorker"in navigator&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(e):this.#jl()}addEventListener(e){if(Ps(this.#hr),"function"!=typeof e)throw new TypeError("The callback must be a function.");"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",e),this.#Ol.add(e)):this.#jl()}removeEventListener(e){if(Ps(this.#hr),"function"!=typeof e)throw new TypeError("The callback must be a function.");return"serviceWorker"in navigator?(navigator.serviceWorker.removeEventListener("message",e),this.#Ol.delete(e)):(this.#jl(),!1)}destroy(){if(!this.#hr){if("serviceWorker"in navigator){this.#Cl&&(navigator.serviceWorker.removeEventListener("message",this.#Cl),this.#Cl=null);for(const e of this.#Ol)navigator.serviceWorker.removeEventListener("message",e);this.#Ol.clear()}this.#Ll&&(window.matchMedia("(display-mode: standalone)").removeEventListener("change",this.#Ll),this.#Ll=null),this.#Nl&&(window.removeEventListener("beforeinstallprompt",this.#Nl),this.#Nl=null),this.#_l&&(window.removeEventListener("appinstalled",this.#_l),this.#_l=null),this.removeAllListeners(),this.#Pl.removeAllListeners(),this.#Sl=null,this.#Il=null,this.destroyPlugins(),this.#hr=!0,this.log("info",`[${this.#al}] Destroyed successfully.`)}}}const Os=js,$s=P(),Hs=R();class Fs{#Wl=!1;get isolationMode(){return this.#Wl}static#ql=!0;static get defaultIsDeep(){return Fs.#ql}static set defaultIsDeep(e){if("boolean"!=typeof e)throw new TypeError("The defaultIsDeep property must be a boolean.");Fs.#ql=e}constructor(e={isolationMode:!1}){if("object"!=typeof e||null===e)throw new TypeError("Options must be a non-null object.");if(void 0!==e.isolationMode&&"boolean"!=typeof e.isolationMode)throw new TypeError('The property "isolationMode" must be a boolean.');this.#Wl=!!e.isolationMode,this.#Wl&&(this.#nl=Fs.#Vl.map(e=>({...e})))}static _createObjectPlugin(e){if("string"!=typeof e)throw new TypeError("Id must be a string.");return{id:e,canHandle:e=>null!==e&&"object"==typeof e,clone:(e,t,r)=>{const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t?r.clone(e[s],t):e[s]);return i}}}static#Vl=[];static validatePlugin(e){if("function"!=typeof e?.canHandle||"function"!=typeof e?.clone)throw new TypeError("Each plugin must implement the required interface: canHandle(item) and clone(item, cloner).");if("string"!=typeof e?.id)throw new TypeError("Each plugin must implement the required interface: the plugin id string.")}static get plugins(){return Fs.#Vl.map(e=>({...e}))}static get size(){return Fs.#Vl.length}static get ids(){return Fs.#Vl.map(e=>e.id)}static set plugins(e){if(!Array.isArray(e))throw new TypeError("The defaultPlugins property must be an array.");Fs.#Vl=e.map(e=>(Fs.validatePlugin(e),{...e}))}static addPlugin(e,t="start",r=0){if(Fs.validatePlugin(e),Fs.hasPlugin(e.id))throw new TypeError(`A plugin with the ID "${e.id}" already exists in the global registry.`);const i={...e};if("start"===t)Fs.#Vl.unshift(i);else if("end"===t)Fs.#Vl.push(i);else{if("index"!==t)throw new TypeError('Position must be "start", "end", or "index".');if(!Number.isInteger(r)||r<0)throw new TypeError('When position is "index", the index must be a non-negative integer.');Fs.#Vl.splice(r,0,i)}}static hasPlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");return Fs.#Vl.some(t=>t.id===e)}static removePlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");const t=Fs.#Vl.findIndex(t=>t.id===e);return-1!==t&&(Fs.#Vl.splice(t,1),!0)}static filterPlugins(e){if("function"!=typeof e)throw new TypeError("Predicate must be a function.");Fs.#Vl=Fs.#Vl.filter(t=>!e({...t}))}static updatePlugin(e,t){if(e<0||e>=Fs.#Vl.length)throw new RangeError("Index out of bounds.");Fs.validatePlugin(t),Fs.#Vl[e]={...t}}static reorderPlugins(e){Fs.#Vl=Fs.#Vl.sort(e?(t,r)=>e({...t},{...r}):void 0)}#nl=[];get size(){return this.#nl.length}get ids(){return this.#nl.map(e=>e.id)}get plugins(){return this.#nl.map(e=>({...e}))}set plugins(e){if(!Array.isArray(e))throw new TypeError("The plugins property must be an array.");this.#nl=e.map(e=>(Fs.validatePlugin(e),{...e}))}addPlugin(e,t="start",r=0){if(Fs.validatePlugin(e),this.hasPlugin(e.id))throw new TypeError(`A plugin with the ID "${e.id}" already exists in this instance.`);const i={...e};if("start"===t)this.#nl.unshift(i);else if("end"===t)this.#nl.push(i);else{if("index"!==t)throw new TypeError('Position must be "start", "end", or "index".');if(!Number.isInteger(r)||r<0)throw new TypeError('When position is "index", the index must be a non-negative integer.');this.#nl.splice(r,0,i)}}hasPlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");return this.#nl.some(t=>t.id===e)}removePlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");const t=this.#nl.findIndex(t=>t.id===e);return-1!==t&&(this.#nl.splice(t,1),!0)}filterPlugins(e){if("function"!=typeof e)throw new TypeError("Predicate must be a function.");this.#nl=this.#nl.filter(t=>!e({...t}))}updatePlugin(e,t){if(e<0||e>=this.#nl.length)throw new RangeError("Index out of bounds.");Fs.validatePlugin(t),this.#nl[e]={...t}}reorderPlugins(e){this.#nl=this.#nl.sort(e?(t,r)=>e({...t},{...r}):void 0)}static clone(e,t=Fs.#ql){for(const r of Fs.#Vl)if(r.canHandle(e))return r.clone(e,t,Fs);return e}clone(e,t=Fs.#ql){for(const r of this.#nl)if(r.canHandle(e))return r.clone(e,t,this);if(!this.#Wl)for(const r of Fs.#Vl)if(r.canHandle(e))return r.clone(e,t,this);return e}}Fs.plugins=Hs.filter(e=>$s[e]).map(e=>({id:e,canHandle:$s[e].validator,clone:$s[e].cloner}));const zs=Fs,Bs={100:{name:"Continue",summary:"",description:""},101:{name:"Switching Protocols",summary:"",description:""},102:{name:"Processing",summary:"",description:""},103:{name:"Early Hints",summary:"",description:""},200:{name:"OK",summary:"",description:""},201:{name:"Created",summary:"",description:""},202:{name:"Accepted",summary:"",description:""},203:{name:"Non-Authoritative Information",summary:"",description:""},204:{name:"No Content",summary:"",description:""},205:{name:"Reset Content",summary:"",description:""},206:{name:"Partial Content",summary:"",description:""},207:{name:"Multi-Status",summary:"",description:""},208:{name:"Already Reported",summary:"",description:""},226:{name:"IM Used",summary:"",description:""},300:{name:"Multiple Choices",summary:"",description:""},301:{name:"Moved Permanently",summary:"",description:""},302:{name:"Found",summary:"",description:""},303:{name:"See Other",summary:"",description:""},304:{name:"Not Modified",summary:"",description:""},305:{name:"Use Proxy",summary:"",description:""},306:{name:"Unused",summary:"",description:""},307:{name:"Temporary Redirect",summary:"",description:""},308:{name:"Permanent Redirect",summary:"",description:""},400:{name:"Bad Request",summary:"",description:""},401:{name:"Unauthorized",summary:"",description:""},402:{name:"Payment Required",summary:"",description:""},403:{name:"Forbidden",summary:"",description:""},404:{name:"Not Found",summary:"",description:""},405:{name:"Method Not Allowed",summary:"",description:""},406:{name:"Not Acceptable",summary:"",description:""},407:{name:"Proxy Authentication Required",summary:"",description:""},408:{name:"Request Timeout",summary:"",description:""},409:{name:"Conflict",summary:"",description:""},410:{name:"Gone",summary:"",description:""},411:{name:"Length Required",summary:"",description:""},412:{name:"Precondition Failed",summary:"",description:""},413:{name:"Content Too Large",summary:"",description:""},414:{name:"URI Too Long",summary:"",description:""},415:{name:"Unsupported Media Type",summary:"",description:""},416:{name:"Range Not Satisfiable",summary:"",description:""},417:{name:"Expectation Failed",summary:"",description:""},418:{name:"I'm a teapot",summary:"",description:""},421:{name:"Misdirected Request",summary:"",description:""},422:{name:"Unprocessable Content",summary:"",description:""},423:{name:"Locked",summary:"",description:""},424:{name:"Failed Dependency",summary:"",description:""},425:{name:"Too Early",summary:"",description:""},426:{name:"Upgrade Required",summary:"",description:""},428:{name:"Precondition Required",summary:"",description:""},429:{name:"Too Many Requests",summary:"",description:""},431:{name:"Request Header Fields Too Large",summary:"",description:""},451:{name:"Unavailable For Legal Reasons",summary:"",description:""},500:{name:"Internal Server Error",summary:"",description:""},501:{name:"Not Implemented",summary:"",description:""},502:{name:"Bad Gateway",summary:"",description:""},503:{name:"Service Unavailable",summary:"",description:""},504:{name:"Gateway Timeout",summary:"",description:""},505:{name:"HTTP Version Not Supported",summary:"",description:""},506:{name:"Variant Also Negotiates",summary:"",description:""},507:{name:"Insufficient Storage",summary:"",description:""},508:{name:"Loop Detected",summary:"",description:""},510:{name:"Not Extended",summary:"",description:""},511:{name:"Network Authentication Required",summary:"",description:""}};class Ws{static#Ul=Bs;static codeIs=Object.freeze({info:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=100&&e<=199},success:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=200&&e<=299},redirect:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=300&&e<=399},clientError:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=400&&e<=499},serverError:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=500&&e<=599}});static get defaultRequestCodes(){return structuredClone(Ws.#Ul)}static set defaultRequestCodes(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("The value must be a non-null object.");for(const[t,r]of Object.entries(e)){if(Number.isNaN(Number(t)))throw new TypeError(`Invalid key: "${t}". Status code keys must be numeric.`);if("object"!=typeof r||null===r||Array.isArray(r))throw new TypeError(`The value for status code ${t} must be an object.`);if("string"!=typeof r.name)throw new TypeError(`Property 'name' in status ${t} must be a string.`);if("string"!=typeof r.summary)throw new TypeError(`Property 'summary' in status ${t} must be a string.`);if("string"!=typeof r.description)throw new TypeError(`Property 'description' in status ${t} must be a string.`)}Ws.#Ul=structuredClone(e)}#Kl=new Set;#Jl;#Gl="en";constructor(e,t={}){if(!v(t))throw new TypeError("Initial responses must be an object.");if(this.#Jl=new e({defaultLocale:"en",mode:"local",strict:!1,acceptNullResults:!0}),!(this.#Jl instanceof ui))throw new TypeError('The "i18" must be an instance of TinyI18.');this.#Jl.loadLocaleLocal(this.#Gl,{});for(const e in Ws.#Ul){const t=Ws.#Ul[e];this.addResponse(Number(e),t)}for(const e in t){const r=t[e];this.addResponse(Number(e),r)}}#Yl(e,t){if("object"!=typeof t||null===t)throw new TypeError("Response must be a non-null object.");if("string"!=typeof t.name)throw new TypeError('The "name" property must be a string.');if("string"!=typeof t.summary)throw new TypeError('The "summary" property must be a string.');if("string"!=typeof t.description)throw new TypeError('The "description" property must be a string.');if(this.#Jl.get(String(e)))throw new Error(`Response with ID ${e} already exists in the registry.`)}addResponse(e,t,r=this.#Gl){this.#Yl(e,t),this.#Kl.add(e),this.#Jl.loadLocaleLocal(r,{[e]:{name:t.name,summary:t.summary,description:t.description}})}get(e,t={},r=this.#Gl){const i=this.#Jl.get(`${e}.name`,t,{locale:r}),s=this.#Jl.get(`${e}.summary`,t,{locale:r}),n=this.#Jl.get(`${e}.description`,t,{locale:r});return"string"!=typeof i||"string"!=typeof s||"string"!=typeof n?null:{name:i,summary:s,description:n}}has(e){return!!this.#Jl.get(String(e))}getAll(){const e={};return this.#Kl.forEach(t=>{const r=this.get(t);r&&(e[t]=r)}),e}}const qs=Ws,Vs=class extends qs{constructor(e){super(di,e)}},Us="(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";function Ks(){return new RegExp(`^${Us}\\.${Us}\\.${Us}\\.${Us}$`)}function Js(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(t??Ks()).test(e)}function Gs(){return new RegExp(`\\b${Us}(?:\\.${Us}){3}\\b`,"g")}function Ys(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(t??Gs())??[]}const Xs="[0-9a-fA-F]{1,4}",Qs=`((${Xs}:){7}${Xs}|(${Xs}:){1,7}:|(${Xs}:){1,6}:${Xs}|(${Xs}:){1,5}(:${Xs}){1,2}|(${Xs}:){1,4}(:${Xs}){1,3}|(${Xs}:){1,3}(:${Xs}){1,4}|(${Xs}:){1,2}(:${Xs}){1,5}|${Xs}:((:${Xs}){1,6})|:((:${Xs}){1,7}|:))`;function Zs(){return new RegExp(`^${Qs}$`)}function en(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(t??Zs()).test(e)}function tn(){return new RegExp(`\\b${Qs}\\b`,"g")}function rn(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(t??tn())??[]}const sn=(e={})=>{(e=>{if(void 0!==e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be an object.");if(void 0!==e.protocol&&"string"!=typeof e.protocol)throw new TypeError('The "protocol" property must be a string.');if(void 0!==e.subDomain&&"string"!=typeof e.subDomain)throw new TypeError('The "subDomain" property must be a string.');if(void 0!==e.subDomainOptional&&"boolean"!=typeof e.subDomainOptional)throw new TypeError('The "subDomainOptional" property must be a boolean.');if(void 0!==e.nameMaxLength&&(!Array.isArray(e.nameMaxLength)||2!==e.nameMaxLength.length||"number"!=typeof e.nameMaxLength[0]||"number"!=typeof e.nameMaxLength[1]))throw new TypeError('The "nameMaxLength" property must be an array of two numbers.');if(void 0!==e.topLevelDomainLength&&(!Array.isArray(e.topLevelDomainLength)||2!==e.topLevelDomainLength.length||"number"!=typeof e.topLevelDomainLength[0]||"number"!=typeof e.topLevelDomainLength[1]))throw new TypeError('The "topLevelDomainLength" property must be an array of two numbers.')}})(e);const{protocol:t="https?",subDomain:r="",subDomainOptional:i=!0,nameMaxLength:s=[1,256],topLevelDomainLength:n=[1,6]}=e;return`${t}:\\/\\/${r?`(${r}\\.)${i?"?":""}`:""}[-a-zA-Z0-9@:%._\\+~#=]{${String(s[0])},${String(s[1])}}\\.[a-zA-Z0-9()]{${String(n[0])},${String(n[1])}}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)`};function nn(e){return new RegExp(`^${sn(e)}$`)}function on(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(r??nn(t)).test(e)}function an(e){return new RegExp(`\\b${sn(e)}\\b`,"g")}function ln(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(r??an(t))??[]}const hn=(e={})=>{(e=>{if(void 0===e)return;if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be an object.");const t=(e,t)=>{if(void 0!==e){if(!Array.isArray(e))throw new TypeError(`${t} must be an array.`);for(let r=0;r<e.length;r++)if("string"!=typeof e[r])throw new TypeError(`All elements in ${t} must be strings.`)}};if(t(e.blacklistDomains,"blacklistDomains"),t(e.whitelistDomains,"whitelistDomains"),t(e.blacklistUsernames,"blacklistUsernames"),t(e.whitelistUsernames,"whitelistUsernames"),void 0!==e.customValidator&&"function"!=typeof e.customValidator)throw new TypeError("customValidator must be a function.")})(e);const{validName:t="[a-zA-Z0-9._%+-]+",validDomain:r="[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"}=e;return`${t}@${r}`};function un(e){return new RegExp(`^${hn(e)}$`)}function cn(e,t={}){if("function"==typeof t.customValidator&&!t.customValidator(e))return!1;const[r,i]=e.split("@");return!(Array.isArray(t.whitelistDomains)&&t.whitelistDomains.length>0&&!t.whitelistDomains.includes(i)||Array.isArray(t.whitelistUsernames)&&t.whitelistUsernames.length>0&&!t.whitelistUsernames.includes(r)||Array.isArray(t.blacklistDomains)&&t.blacklistDomains.length>0&&t.blacklistDomains.includes(i)||Array.isArray(t.blacklistUsernames)&&t.blacklistUsernames.length>0&&t.blacklistUsernames.includes(r))}function dn(e,t={},r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return!!(r??un(t)).test(e)&&cn(e,t)}function pn(e){return new RegExp(`\\b${hn(e)}\\b`,"g")}function mn(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(r??pn(t))?.filter(e=>cn(e,t))??[]}const fn=e=>String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yn=(e,t)=>{if(null!=t&&"function"!=typeof t&&"lowercase"!==t&&"uppercase"!==t)throw new TypeError('The "transform" property must be a function, "lowercase", or "uppercase".');return"function"==typeof t?t(e):"lowercase"===t?e.toLowerCase():"uppercase"===t?e.toUpperCase():e},gn=({validValues:e="[a-zA-Z0-9_]",length:t=[3,20]}={})=>{if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "validValues" property must be a string.');if(void 0!==t){if(!Array.isArray(t)||"number"!=typeof t[0]||"number"!=typeof t[1])throw new TypeError('The "length" property must be an array of two numbers.');if(t[0]>t[1])throw new RangeError("The minimum length (length[0]) cannot be greater than the maximum length (length[1]).");if(t[0]<0)throw new RangeError("The length cannot be negative.")}return`(?:${e}){${String(t[0])},${String(t[1])}}`};function wn(e){return`${function({prefix:e,start:t}={}){if(void 0!==t&&"string"!=typeof t)throw new TypeError('The "start" property must be a string.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "prefix" property must be a string.');return`${t??""}${e?fn(e):""}`}(e)}${gn(e)}${function({domain:e,domainPattern:t,end:r}={}){if(void 0!==r&&"string"!=typeof r)throw new TypeError('The "end" property must be a string.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "domain" property must be a string.');if(void 0!==t&&"string"!=typeof t)throw new TypeError('The "domainPattern" property must be a string.');return t?`(?:${t})${r??""}`:e?`(?:${fn(e)})${r??""}`:r??""}(e)}`}const bn=e=>{if(void 0===e)return;const t=Array.isArray(e)?e:[e];for(const e of t)if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be a plain object or an array of plain objects.")};function vn(e){if(bn(e),Array.isArray(e)){const t=e.map(wn).join("|");return new RegExp(`^(?:${t})$`)}return new RegExp(`^${wn(e)}$`)}function En(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(r??vn(t)).test(e)}function Tn(e){bn(e);const t=Array.isArray(e)?e[0]:e,r=t?.prefix||t?.start,i=r?"(?:^|(?<=\\W))":"\\b",s=r?"(?=\\W|$)":"\\b";if(Array.isArray(e)){const t=e.map(wn).join("|");return new RegExp(`${i}(?:${t})${s}`,"g")}return new RegExp(`${i}${wn(e)}${s}`,"g")}function Sn(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");const i=e.match(r??Tn(t));if(!i)return[];const s=Array.isArray(t)?t[0]?.transform:t?.transform;return s?i.map(e=>yn(e,s)):i}const xn=class{#Xl;#Ql=[];#Zl=!1;#eh;#th="";constructor(e){const t=e.tagName;if("string"!=typeof t)throw new TypeError("The tagName must be a string.");if(/[<>\s]/.test(t))throw new TypeError("The tagName must be a single word without spaces or < > characters.");if(this.#Xl=t,e.attributes){if(!Array.isArray(e.attributes))throw new TypeError("The attributes property must be an array of strings.");for(const t of e.attributes)if("string"!=typeof t||/[<>\s]/.test(t))throw new TypeError("Each attribute name must be a single word string without spaces or < > characters.");this.#Ql=e.attributes}if("boolean"!=typeof e.captureAllAttributes)throw new TypeError("captureAllAttributes must be a boolean.");this.#eh=e.captureAllAttributes,this.freeMode=e.freeMode??!1,this.contentPattern=e.contentPattern||(this.#Zl?"[\\s\\S]*?":".*?")}get tagName(){return this.#Xl}get attributes(){return[...this.#Ql]}get freeMode(){return this.#Zl}set freeMode(e){if("boolean"!=typeof e)throw new TypeError("freeMode must be a boolean.");this.#Zl=e}get captureAllAttributes(){return this.#eh}get contentPattern(){return this.#th}set contentPattern(e){if("string"!=typeof e)throw new TypeError("contentPattern must be a string.");this.#th=e}toString(){let e=`<${this.#Xl}`;if(this.#eh)e+="([^>]*)";else{for(const t of this.#Ql)e+=`(?=[^>]*?\\s+${t}(?:=(?:["']([^"']*)["']|([^"'>\\s]+)))?(?=\\s|>|\\/))`;e+="[^>]*"}return e+=`>(${this.#th})</${this.#Xl}>`,e}toRegExp(e="g"){return new RegExp(this.toString(),e)}parse(e){const t=this.toRegExp("g"),r=[];let i;for(;null!==(i=t.exec(e));){const e={};let t="";if(this.#eh){const r=i[1]||"";t=i[2]||"";const s=/([^\s=]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s"'>]+)))?/g;let n;for(;null!==(n=s.exec(r));){const t=n[1],r=n[2]??n[3]??n[4]??!0;e[t]=r}}else{for(let t=0;t<this.#Ql.length;t++){const r=this.#Ql[t],s=i[2*t+1],n=i[2*t+2];e[r]=s??n??!0}t=i[2*this.#Ql.length+1]||""}r.push({attributes:e,child:t})}return r}},An=le("TinyUriParser"),Cn=class{static buildParserPair(e,t,r,i){return Object.freeze([e,t,t=>({type:e,data:r(t)}),i])}#hr=!1;get isDestroyed(){return this.#hr}#rh;get parsers(){return An(this.#hr),Array.from(this.#rh).map(e=>[...e])}get size(){return An(this.#hr),this.#rh.size}constructor(...e){for(const[t,r]of e.entries()){if(!Array.isArray(r))throw new TypeError(`Parser at index ${t} must be an array representing a ParserPair.`);if(4!==r.length)throw new TypeError(`Parser at index ${t} must contain exactly 4 elements.`);if("string"!=typeof r[0])throw new TypeError(`The first element of the parser at index ${t} must be a string (Type).`);if("function"!=typeof r[1])throw new TypeError(`The second element of the parser at index ${t} must be a function (ParseChecker).`);if("function"!=typeof r[2])throw new TypeError(`The third element of the parser at index ${t} must be a function (ParserCallback).`);if("function"!=typeof r[3])throw new TypeError(`The fourth element of the parser at index ${t} must be a function (StringifyCallback).`)}this.#rh=new Set(e)}parse(e){if(An(this.#hr),"string"!=typeof e)throw new TypeError("The input must be a string.");for(const t of this.#rh)if(t[1](e))return t[2](e);throw new Error(`Unable to determine the protocol for the provided URI: ${e}`)}stringify(e){if(An(this.#hr),!v(e)||"string"!=typeof e.type)throw new TypeError('The input must be a valid ParsedUri object with a "type" property.');for(const t of this.#rh){const[r,,,i]=t;if(r===e.type&&"function"==typeof i){const t=i(e.data);if("string"==typeof t)return t}}throw new Error(`No reconstructor found for the parsed type: ${e.type}`)}destroy(){this.#hr||(this.#rh.clear(),this.#hr=!0)}},In=le("TinyBrowserMonitor"),Dn=e().EventEmitter;class kn extends Dn{static#ih=["connectivity","quality","battery","device","cpu","gpu","performance","resource","paint","navigation","layout-shift","lcp","longtask","memory-usage","fps","window","screen"];static get VALID_SYSTEMS(){return Object.freeze([...kn.#ih])}#hr=!1;#sh=new Set;#nh={isOnline:navigator.onLine};#oh=null;#ah;#lh;#hh={usedJSHeapSize:0,totalJSHeapSize:0,jsHeapSizeLimit:0,enabled:!!performance.memory};#uh={downlink:0,rtt:0,effectiveType:"unknown",saveData:!1,enabled:!!navigator.connection};#ch=[];#dh={level:1,charging:!0,chargingTime:0,dischargingTime:0,enabled:!1};#ph={memory:0,cpu:{logicalCores:0},gpu:{vendor:"unknown",renderer:"unknown"},enabled:!!navigator.deviceMemory};#mh={fps:60,timestamp:performance.now()};#fh=null;#yh={paint:{firstPaint:0,firstContentfulPaint:0},navigation:null,layoutShift:0,lcp:0,fps:this.#mh,longTasks:[]};#gh={width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio};#wh={width:window.screen.width,height:window.screen.height,availWidth:window.screen.availWidth,availHeight:window.screen.availHeight,colorDepth:window.screen.colorDepth,pixelDepth:window.screen.pixelDepth,orientation:window.screen.orientation?.type||"unknown"};#bh;#vh=[];constructor(e={}){super();const{resourceLimit:t=1e3,systems:r=[],memoryIntervalMs:i=100,fpsIntervalMs:s=1e3}=e;if("number"!=typeof t||t<-1)throw new TypeError("The resourceLimit must be a number greater than or equal to -1.");if("number"!=typeof i||i<16)throw new TypeError("The memoryIntervalMs must be a number greater than or equal to 16.");if("number"!=typeof s||s<0)throw new TypeError("The fpsIntervalMs must be a number greater than or equal to 0.");if(!Array.isArray(r))throw new TypeError("The systems option must be an array.");for(const e of r)if(!kn.#ih.includes(e))throw new TypeError(`Invalid system identifier: "${e}". Must be one of: ${kn.#ih.join(", ")}`);this.#bh=t,this.#ah=i,this.#lh=s,this.#sh=0===r.length?new Set(kn.#ih):new Set(r),this.#Eh(),this.#Th()}#Eh(){this.#sh.has("connectivity")&&this.#Sh(),this.#sh.has("quality")&&this.#xh(),this.#sh.has("battery")&&this.#Ah(),this.#sh.has("memory-usage")&&this.#Ch(),this.#sh.has("fps")&&this.#Ih(),this.#sh.has("window")&&this.#Dh(),this.#sh.has("screen")&&this.#kh(),(this.#sh.has("device")||this.#sh.has("cpu")||this.#sh.has("gpu"))&&this.#Mh();const e=this.#sh.has("performance"),t=["resource","paint","navigation","layout-shift","lcp","longtask"].some(e=>this.#sh.has(e));(e||t)&&this.#Lh(e)}get isDestroyed(){return this.#hr}get connectivity(){return In(this.#hr),Object.freeze({...this.#nh})}get quality(){return In(this.#hr),Object.freeze({...this.#uh})}get resources(){return In(this.#hr),Object.freeze(this.#ch.map(e=>Object.freeze({...e})))}get battery(){return In(this.#hr),Object.freeze({...this.#dh})}get windowMetrics(){return In(this.#hr),Object.freeze({...this.#gh})}get screenMetrics(){return In(this.#hr),Object.freeze({...this.#wh})}get device(){return In(this.#hr),Object.freeze({...this.#ph})}get fps(){return In(this.#hr),Object.freeze({...this.#mh})}get performance(){return In(this.#hr),Object.freeze({...this.#yh,paint:Object.freeze({...this.#yh.paint}),fps:Object.freeze({...this.#yh.fps}),navigation:this.#yh.navigation?Object.freeze({...this.#yh.navigation}):null})}get memoryUsage(){return In(this.#hr),Object.freeze({...this.#hh})}get enabledSystems(){return In(this.#hr),Object.freeze([...this.#sh])}has(e){if(In(this.#hr),"string"!=typeof e)throw new TypeError("The system identifier must be a string.");return this.#sh.has(e)}get size(){return In(this.#hr),this.#sh.size}getFormattedMemoryUsage(e,t=this.#hh){In(this.#hr);const r=["bytes","KB","MB","GB"];if("string"!=typeof e||!r.includes(e))throw new TypeError(`Invalid format: "${e}". Must be one of: ${r.join(", ")}`);if("object"!=typeof t||null===t)throw new TypeError("The memoryUsage argument must be a non-null object.");const i=["usedJSHeapSize","totalJSHeapSize","jsHeapSizeLimit"];for(const e of i)if("number"!=typeof t[e]||Number.isNaN(t[e]))throw new TypeError(`Invalid memoryUsage: Property "${e}" must be a valid number.`);const s={bytes:1,KB:1024,MB:Math.pow(1024,2),GB:Math.pow(1024,3)}[e],n=e=>e/s;return{used:n(t.usedJSHeapSize),total:n(t.totalJSHeapSize),limit:n(t.jsHeapSizeLimit)}}#Dh(){window.addEventListener("resize",this.#Nh),this.#_h()}#_h(){this.#gh={width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio}}#kh(){this.#wh={width:window.screen.width,height:window.screen.height,availWidth:window.screen.availWidth,availHeight:window.screen.availHeight,colorDepth:window.screen.colorDepth,pixelDepth:window.screen.pixelDepth,orientation:window.screen.orientation?.type||"unknown"}}#Nh=()=>{this.#_h(),this.emit("WindowResize",Object.freeze({...this.#gh}))};#Sh(){window.addEventListener("online",this.#Ph),window.addEventListener("offline",this.#Ph),navigator.connection&&navigator.connection.addEventListener("change",this.#Ph)}#Ih(){let e=0,t=performance.now();const r=i=>{e++,i-t>=this.#lh&&(this.#mh={fps:Math.round(1e3*e/(i-t)),timestamp:i},e=0,t=i,this.emit("FPS",Object.freeze({...this.#mh}))),this.#fh=requestAnimationFrame(r)};this.#fh=requestAnimationFrame(r)}#Mh(){this.#ph={memory:0,cpu:{logicalCores:0},gpu:{vendor:"unknown",renderer:"unknown"},enabled:!1};let e=!1;if(this.#sh.has("device")&&("number"==typeof navigator.deviceMemory&&(this.#ph.memory=navigator.deviceMemory,e=!0),this.#sh.has("cpu")&&"number"==typeof navigator.hardwareConcurrency&&(this.#ph.cpu.logicalCores=navigator.hardwareConcurrency,e=!0),this.#sh.has("gpu")))try{const t=document.createElement("canvas"),r=t.getContext("webgl")||t.getContext("experimental-webgl");if(r instanceof WebGLRenderingContext){const t=r.getExtension("WEBGL_debug_renderer_info");t&&(this.#ph.gpu.vendor=r.getParameter(t.UNMASKED_VENDOR_WEBGL)||"unknown",this.#ph.gpu.renderer=r.getParameter(t.UNMASKED_RENDERER_WEBGL)||"unknown",e=!0)}}catch(e){console.warn("TinyBrowserMonitor: GPU retrieval failed.",e)}this.#ph.enabled=e}async#Ah(){if(navigator.getBattery)try{const e=await navigator.getBattery();this.#dh.enabled=!0;const t=()=>{this.#dh={level:e.level,charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,enabled:!0},this.emit("BatteryUpdated",Object.freeze({...this.#dh})),this.#Th()};e.addEventListener("levelchange",t),e.addEventListener("chargingchange",t),e.addEventListener("chargingtimechange",t),e.addEventListener("dischargingtimechange",t),t()}catch(e){console.warn("Battery Status API failed to initialize:",e)}}#Ch(){if(performance.memory){const e=()=>{const e=performance.memory;e&&(this.#hh={usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit,enabled:!0},this.emit("MemoryUsage",Object.freeze({...this.#hh})))};this.#oh=setInterval(e,this.#ah),e()}}#Lh(e=!1){const t=[{key:"resource",type:"resource",callback:this.#Rh.bind(this)},{key:"paint",type:"paint",callback:this.#jh.bind(this)},{key:"navigation",type:"navigation",callback:this.#Oh.bind(this)},{key:"layout-shift",type:"layout-shift",callback:this.#$h.bind(this)},{key:"lcp",type:"largest-contentful-paint",callback:this.#Hh.bind(this)},{key:"longtask",type:"longtask",callback:this.#Fh.bind(this)}];for(const r of t)if(e||this.#sh.has(r.key))try{const e=new PerformanceObserver(r.callback);e.observe({type:r.type,buffered:!0}),this.#vh.push(e)}catch(e){console.error(e)}}#Rh(e){const t=e.getEntries(),r=new Ai(this.#ch.map(e=>({...e})),{idKey:"name"});t.forEach(e=>{this.#ch.push({name:e.name,duration:e.duration,entryType:e.entryType})}),this.#bh>0&&this.#ch.length>this.#bh&&this.#ch.splice(0,this.#ch.length-this.#bh);const i=r.compare(this.#ch);for(const e of i)this.emit("Resource"+("added"===e.status?"Added":"deleted"===e.status?"Deleted":"Edited"),e.oldItem,e.item);this.#Th()}#jh(e){e.getEntries().forEach(e=>{"first-paint"===e.name?this.#yh.paint.firstPaint=e.startTime:"first-contentful-paint"===e.name&&(this.#yh.paint.firstContentfulPaint=e.startTime)}),this.emit("PaintUpdated",Object.freeze({...this.#yh.paint})),this.#Th()}#Oh(e){const t=e.getEntries()[0];t&&(this.#yh.navigation={ttfb:t.responseStart-t.requestStart,domContentLoaded:t.domContentLoadedEventEnd-t.startTime,loadEvent:t.loadEventEnd-t.startTime}),this.emit("NavigationUpdated",Object.freeze({...this.#yh.navigation})),this.#Th()}#$h(e){e.getEntries().forEach(e=>{const t=e;t.hadRecentInput||(this.#yh.layoutShift+=t.value)}),this.emit("LayoutShiftUpdated",{layoutShift:this.#yh.layoutShift}),this.#Th()}#Hh(e){const t=e.getEntries().pop();t&&(this.#yh.lcp=t.startTime),this.emit("LcpUpdated",{lcp:this.#yh.lcp}),this.#Th()}#Fh(e){e.getEntries().forEach(e=>{this.#yh.longTasks.push(e.duration)}),this.emit("LongTaskUpdated",{lcp:[...this.#yh.longTasks]}),this.#Th()}#Ph=e=>{this.#sh.has("connectivity")&&this.#zh(),this.#sh.has("quality")&&this.#xh(),this.#Th(e)};#zh(){this.#nh={isOnline:navigator.onLine},this.emit("ConnectivityUpdated",{...this.#nh})}#xh(){if(navigator.connection){const{downlink:e,rtt:t,effectiveType:r,saveData:i}=navigator.connection;this.#uh={downlink:"number"==typeof e?e:0,rtt:"number"==typeof t?t:0,effectiveType:"string"==typeof r?r:"unknown",saveData:"boolean"==typeof i&&i,enabled:!0}}}#Th(e){this.#Bh();const t={connectivity:Object.freeze({...this.#nh}),quality:Object.freeze({...this.#uh}),resources:Object.freeze(this.#ch.map(e=>Object.freeze({...e}))),battery:Object.freeze({...this.#dh}),device:Object.freeze({...this.#ph}),performance:this.performance,memoryUsage:Object.freeze({...this.#hh}),windowMetrics:Object.freeze({...this.#gh}),screenMetrics:Object.freeze({...this.#wh}),event:e};this.emit("NetworkUpdated",t)}#Bh(){if("boolean"!=typeof this.#nh.isOnline)throw new TypeError("Internal Error: Connectivity status is invalid.");if("number"!=typeof this.#uh.downlink)throw new TypeError("Internal Error: Quality metrics are invalid.")}destroy(){this.#hr||(this.#sh.has("connectivity")&&(window.removeEventListener("online",this.#Ph),window.removeEventListener("offline",this.#Ph)),this.#sh.has("window")&&window.removeEventListener("resize",this.#Nh),this.#sh.has("quality")&&navigator.connection&&navigator.connection.removeEventListener("change",this.#Ph),this.#sh.has("performance")&&(this.#vh.forEach(e=>e.disconnect()),this.#vh=[]),this.#oh&&clearInterval(this.#oh),this.#fh&&cancelAnimationFrame(this.#fh),this.removeAllListeners(),this.#hr=!0,this.emit("Destroyed"))}}const Mn=kn,Ln=le("TinyThrottledApi"),Nn=e().EventEmitter,_n=class extends Nn{static TinyTimeout=kr;#Wh=0;#qh;#i=new ae;#Vh;#Uh;#Kh=100;#Jh=5e3;#hr=!1;#Gh=!1;constructor(e,t,r=null){if(super(),"number"!=typeof e||e<=0)throw new TypeError("Concurrency limit must be a positive number.");if("function"!=typeof t)throw new TypeError("API must be a function.");if(null!=r&&!(r instanceof kr))throw new TypeError("timeoutInstance must be a TinyTimeout instance.");this.#qh=e,this.#Vh=t,this.#Uh=r??null}async exec(...e){Ln(this.#hr);const t=crypto.randomUUID();if(this.#Wh<this.#qh){this.#Wh++,this.emit("ExecTask",t);const r=await this.#Yh(...e);return this.emit("TaskEnded",t),r}return this.#i.enqueue(async()=>{this.emit("WaitingTask",t);const r=()=>Cr(()=>this.#Wh<this.#qh),i=async()=>{this.#Uh&&await new Promise(e=>{this.#Uh?this.#Uh.set("api_throttle",e,this.#Kh,this.#Jh):e(void 0)})};this.#Gh?(await i(),await r()):(await r(),await i()),this.#Wh++,this.emit("ExecTask",t);const s=await this.#Yh(...e);return this.emit("TaskEnded",t),s},void 0,t)}destroy(){this.#hr||(this.removeAllListeners(),this.#hr=!0,this.emit("Destroyed"))}async#Yh(...e){try{const t=this.#Vh;return await t(...e)}finally{this.#Wh--}}get isDestroyed(){return this.#hr}get queue(){return Ln(this.#hr),this.#i}get api(){return Ln(this.#hr),this.#Vh}get concurrencyLimit(){return Ln(this.#hr),this.#qh}set concurrencyLimit(e){if(Ln(this.#hr),"number"!=typeof e||e<=0)throw new TypeError("Concurrency limit must be a positive number.");this.#qh=e,this.emit("SetConcurrencyLimit",e)}get timeoutInstance(){return Ln(this.#hr),this.#Uh}get timeoutValue(){return Ln(this.#hr),this.#Kh}set timeoutValue(e){if(Ln(this.#hr),"number"!=typeof e)throw new TypeError("Timeout value must be a number.");if(e<0)throw new RangeError("Timeout value cannot be negative.");this.#Kh=e,this.emit("SetTimeoutValue",e)}get timeoutLimit(){return Ln(this.#hr),this.#Jh}get timeoutFirst(){return this.#Gh}set timeoutFirst(e){if("boolean"!=typeof e)throw new TypeError("timeoutFirst must be a boolean.");this.#Gh=e}set timeoutLimit(e){if(Ln(this.#hr),"number"!=typeof e)throw new TypeError("Timeout limit must be a number.");if(e<0)throw new RangeError("Timeout limit cannot be negative.");this.#Jh=e,this.emit("SetTimeoutLimit",e)}get activeCount(){return Ln(this.#hr),this.#Wh}get queuedCount(){return Ln(this.#hr),this.#i.getQueuedIds().length}},Pn=(e,t=!0)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("GLOB pattern must be a string or an array of strings.");if(Array.isArray(e)&&!e.every(e=>"string"==typeof e))throw new TypeError("All elements in the GLOB array must be strings.");if("boolean"!=typeof t)throw new TypeError("Strict mode must be a boolean.");const r=Array.isArray(e)?e.join(""):e,i=["^"];let s=0,n=!1,o=!1;for(;s<r.length;){const e=r[s];if("\\"===e){const e=r[s+1]||"";i.push("\\"+e),s+=2;continue}if(o)"]"===e?(o=!1,i.push("]")):"!"===e&&"["===r[s-1]?i.push("^"):i.push(e),s++;else{switch(e){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":i.push("\\"+e);break;case"?":i.push("[^/]");break;case"[":o=!0,i.push(e);break;case"]":i.push("\\]");break;case"{":n=!0,i.push("(");break;case"}":n?(n=!1,i.push(")")):i.push("\\}");break;case",":i.push(n?"|":"\\,");break;case"*":let t=1;for(;"*"===r[s+1];)t++,s++;t>1?i.push(".*"):i.push("[^/]*");break;default:i.push(e)}s++}}if(t){if(o)throw new SyntaxError('Unmatched bracket "[" in GLOB pattern.');if(n)throw new SyntaxError('Unmatched brace "{" in GLOB pattern.')}return i.push("$"),i},Rn=(e,t="",r=!0)=>{if("string"!=typeof t)throw new TypeError("RegExp flags must be a string.");return new RegExp(Pn(e,r).join(""),t)},jn=e=>{if(!(e instanceof RegExp||"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)))throw new TypeError("Argument must be a RegExp instance or string stuff.");let t="string"==typeof e?e:Array.isArray(e)?e.join(""):e.source;const r=[];t.startsWith("^")&&(t=t.slice(1)),t.endsWith("$")&&(t=t.slice(0,-1));let i=0;for(;i<t.length;){const e=t[i];if("\\"===e){const e=t[i+1]||"";r.push(e),i+=2;continue}if("."!==e||"*"!==t[i+1]){if("["===e){if("[^/]*"===t.slice(i,i+5)){r.push("*"),i+=5;continue}if("[^/]"===t.slice(i,i+4)){r.push("?"),i+=4;continue}if("^"===t[i+1]){r.push("[!"),i+=2;continue}}"("!==e?"|"!==e?")"!==e?(r.push(e),i++):(r.push("}"),i++):(r.push(","),i++):(r.push("{"),i++)}else r.push("**"),i+=2}return r},On=e=>{try{return Pn(e,!0),!0}catch(e){if(e instanceof SyntaxError)return!1;throw e}},$n=le("TinyWebWorker");class Hn extends Ds{static#El(e){if(e.startsWith("ww:"))throw new TypeError(`The event type "${e}" is reserved for internal Web Worker lifecycle management.`)}#Xh=null;#al;#Qh;#Zh;#Za=!1;#hr=!1;#kl=new Map;#Ml=new Map;#Cl=null;#eu=null;get isReady(){return this.#Za}get isDestroyed(){return this.#hr}get worker(){return $n(this.#hr),this.#Xh}constructor({id:e,workerUrl:t,workerOptions:r={},logger:i,debugMode:s,useLogColors:n}){if(super({logCfg:{id:"[_sub_class_TinyWebWorker_reset_]",logger:i??console,debugMode:s??!1,useLogColors:n??!1}}),"string"!=typeof e||""===e.trim())throw new TypeError('The "id" parameter must be a non-empty string.');if("string"!=typeof t&&!(t instanceof URL))throw new TypeError('The "workerUrl" parameter must be a string or URL.');this.#al=e,this.#Qh=t,this.#Zh=r}async init(){if($n(this.#hr),this.#Xh)throw new Error("Worker is already initialized.");return new Promise((e,t)=>{try{this.#Xh=new Worker(this.#Qh,this.#Zh)}catch(e){return this.log("error","Failed to instantiate Worker:",e),t(e)}this.#Cl=t=>{const r=t.data;if(Array.isArray(r)||"object"!=typeof r||null===r)return;if("string"!=typeof r.type)return;if("ww:EngineReady"===r.type)return this.#Za=!0,super.emit("ww:Started"),void e();const i=r.type,s=r.data,n=r.correlationId,o=r.isApi;if("ww:ApiResponse"===i){if("string"!=typeof n)return;const e=this.#kl.get(n);return void(e&&(clearTimeout(e.timer),this.#kl.delete(n),r.error?e.reject(new Error(r.error)):e.resolve(s)))}if(!0===o){if("string"!=typeof n)return;const e=this.#Ml.get(i);if(!e)return void this.#Xh?.postMessage({correlationId:n,type:"ww:ApiResponse",error:`No API handler registered in Main Thread for type: ${i}`});try{const t=e=>this.#Xh?.postMessage({correlationId:n,type:"ww:ApiResponse",data:e}),r=e({data:s,correlationId:n});r instanceof Promise?r.then(t).catch(e=>{this.#Xh?.postMessage({correlationId:n,type:"ww:ApiResponse",error:e instanceof Error?e.message:String(e)})}):t(r)}catch(e){this.#Xh?.postMessage({correlationId:n,type:"ww:ApiResponse",error:e instanceof Error?e.message:String(e)})}return}super.emit(i,{data:s,event:t})},this.#eu=e=>{this.log("error",`Worker Error [${this.#al}]:`,e.message),super.emit("ww:Error",{error:e}),t(new Error(`Web Worker [${this.#al}] failed to start: ${e.message||"unknown error"}`))},this.#Xh.addEventListener("message",this.#Cl),this.#Xh.addEventListener("error",this.#eu)})}#Bl(e,t,r=!1){if($n(this.#hr),!this.#Xh)throw new Error("Worker is not initialized.");if("string"!=typeof e)throw new TypeError("Payload.type must be a string.");if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError("Payload.data must be a non-null object.");r&&Hn.#El(e),this.#Xh.postMessage({type:e,data:t})}emitMessage(e,t){this.#Bl(e,t,!0)}onApi(e,t){if("function"!=typeof t)throw new TypeError("Callback must be a function.");this.#Ml.set(e,t)}offApi(e){return this.#Ml.delete(e)}async emitApi(e,t,r=1e4){if($n(this.#hr),!this.#Xh)throw new Error("Worker is not initialized.");const i=crypto.randomUUID();return new Promise((s,n)=>{const o=setTimeout(()=>{this.#kl.has(i)&&(this.#kl.delete(i),n(new Error(`API request timeout: ${e} (ID: ${i})`)))},r);this.#kl.set(i,{resolve:s,reject:n,timer:o}),this.#Xh?.postMessage({type:e,data:t,correlationId:i,isApi:!0})})}terminate(){this.#hr||(this.#Xh&&(this.#Cl&&this.#Xh.removeEventListener("message",this.#Cl),this.#eu&&this.#Xh.removeEventListener("error",this.#eu),this.#Xh.terminate(),this.log("info",`Web Worker [${this.#al}] terminated.`)),this.#Xh=null,this.#Cl=null,this.#eu=null,this.#Za=!1,super.emit("ww:Terminated"))}destroy(){this.#hr||(this.terminate(),this.removeAllListeners(),this.destroyPlugins(),this.#hr=!0,this.log("info",`[${this.#al}] Destroyed successfully.`))}}const Fn=Hn,zn=Object.freeze({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:64,O_EXCL:128,O_TRUNC:512,O_APPEND:1024}),Bn=(Object.freeze({OWNER_READ:256,OWNER_WRITE:128,OWNER_EXECUTE:64,GROUP_READ:32,GROUP_WRITE:16,GROUP_EXECUTE:8,OTHER_READ:4,OTHER_WRITE:2,OTHER_EXECUTE:1,SETUID:2048,SETGID:1024,STICKY:512}),Object.freeze({FILE:32768,DIRECTORY:16384,SYMBOLIC_LINK:40960})),Wn=Object.freeze(["utf8","utf-8","base64","hex"]),qn=(e,t,r,i="")=>{const s=i.length>0?`, ${i}`:"",n=new Error(`${e}: ${t} '${r}'${s}`);return n.code=e,n.errno=e,n.syscall=t,n.path=r,n},Vn=(e,t,r,i="ENOTDIR")=>{if("undefined"!=typeof DOMException&&e instanceof DOMException)switch(e.name){case"NotFoundError":return qn("ENOENT",t,r);case"TypeMismatchError":return qn(i,t,r);case"InvalidModificationError":return qn("ENOTEMPTY",t,r);case"NoModificationAllowedError":return qn("EBUSY",t,r);case"NotAllowedError":return qn("EACCES",t,r);default:return qn("EIO",t,r,e.message)}return e instanceof Error?e:new Error(String(e))},Un=(e,t)=>{if("string"!=typeof e)throw new TypeError(`The "${t}" argument must be of type string. Received ${null===e?"null":typeof e}`);if(0===e.length)throw qn("ENOENT","open",e,"path must not be empty");if(e.includes("\0"))throw new TypeError('The "path" argument must not contain null bytes');return e},Kn=(e,t)=>{if(null===e||"object"!=typeof e||Array.isArray(e)){const r=null===e?"null":Array.isArray(e)?"Array":typeof e;throw new TypeError(`The "options" argument must be of type object. Received ${r} in ${t}()`)}return e},Jn=(e,t)=>{if(null==e)return null;if("string"!=typeof e||!Wn.includes(e))throw new TypeError(`The "encoding" option must be one of ${Wn.join(", ")}. Received ${String(e)} in ${t}()`);return e},Gn=(e,t)=>{if("number"!=typeof e||!Number.isInteger(e))throw new TypeError(`The "${t}" argument must be an integer`);if(e<0)throw new RangeError(`The "${t}" argument must not be negative`);return e};class Yn{#wn;constructor(e){this.#wn=Object.freeze({...e})}get path(){return this.#wn.path}get name(){return this.#wn.name}get size(){return"directory"===this.#wn.kind?0:this.#wn.size}get mode(){return this.#wn.mode}get uid(){return this.#wn.uid}get gid(){return this.#wn.gid}get ino(){return this.#wn.ino}get nlink(){return 1}get atimeMs(){return this.#wn.atimeMs}get mtimeMs(){return this.#wn.mtimeMs}get birthtimeMs(){return this.#wn.birthtimeMs}get atime(){return new Date(this.#wn.atimeMs)}get mtime(){return new Date(this.#wn.mtimeMs)}get ctime(){return new Date(this.#wn.mtimeMs)}get birthtime(){return new Date(this.#wn.birthtimeMs)}isFile(){return"file"===this.#wn.kind}isDirectory(){return"directory"===this.#wn.kind}isSymbolicLink(){return"symbolic-link"===this.#wn.kind}isBlockDevice(){return!1}isCharacterDevice(){return!1}isFIFO(){return!1}isSocket(){return!1}get modeWithType(){return(this.isDirectory()?Bn.DIRECTORY:Bn.FILE)|this.#wn.mode}}class Xn{#eo;#tu;constructor(e,t){this.#eo=e,this.#tu=t}get name(){return this.#eo}isFile(){return"file"===this.#tu}isDirectory(){return"directory"===this.#tu}isSymbolicLink(){return"symbolic-link"===this.#tu}isBlockDevice(){return!1}isCharacterDevice(){return!1}isFIFO(){return!1}isSocket(){return!1}}class Qn{#ru;#iu;#su;#nu;constructor(e,t,r){this.#ru=e,this.#iu=t,this.#su=r,this.#nu=!1}get path(){return this.#iu}get flags(){return this.#su}get closed(){return this.#nu}async readFile(e){return this.#ou(),this.#ru.readFile(this.#iu,e)}async writeFile(e,t){return this.#ou(),this.#ru.writeFile(this.#iu,e,t)}async appendFile(e,t){return this.#ou(),this.#ru.appendFile(this.#iu,e,t)}async stat(){return this.#ou(),this.#ru.stat(this.#iu)}async truncate(e){return this.#ou(),this.#ru.truncate(this.#iu,e)}async close(){this.#nu=!0}#ou(){if(this.#nu)throw qn("EBADF","read",this.#iu,"file handle is closed")}}const Zn=e=>{const t=[];for(const r of e.split("/"))0!==r.length&&"."!==r&&(".."!==r?t.push(r):t.pop());return t},eo=class{#au=new Map;#lu;#hu;#uu;constructor(e={}){const{cwd:t="/",umask:r=18,identity:i}=Kn(e,"constructor");this.#lu="string"==typeof t?t:"/",this.#hu="number"==typeof r?r:18,this.#uu={uid:i?.uid??0,gid:i?.gid??0,groups:i?.groups??[]}}static get capabilities(){return Object.freeze({permissions:!1,ownership:!1,symlinks:!1,timestamps:!1,atomicRename:!1,seekableHandles:!1})}get cwd(){return this.#lu}get umask(){return this.#hu}get identity(){return this.#uu}async _readFile(e){throw this.#cu("readFile",e)}async _writeFile(e,t,r){throw this.#cu("writeFile",e)}async _readdir(e){throw this.#cu("readdir",e)}async _mkdir(e,t){throw this.#cu("mkdir",e)}async _rm(e,t){throw this.#cu("rm",e)}async _stat(e){throw this.#cu("stat",e)}async _rename(e,t){throw this.#cu("rename",e)}async _copyFile(e,t,r){throw this.#cu("copyFile",e)}async _readMetadata(e){return this.#au.get(e)??{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null}}async _writeMetadata(e,t){this.#au.set(e,t)}async readFile(e,t={}){const r=Un(e,"path"),{encoding:i}=Kn(t,"readFile"),s=Jn(i,"readFile");return((e,t)=>null===t?e:"base64"===t?(e=>{let t="";for(const r of e)t+=String.fromCharCode(r);return btoa(t)})(e):"hex"===t?(e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""))(e):new TextDecoder("utf-8").decode(e))(await this._readFile(r),s)}async writeFile(e,t,r={}){const i=Un(e,"path"),{encoding:s,append:n,mode:o}=Kn(r,"writeFile"),a=((e,t)=>{if("string"==typeof e)return"base64"===t?(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r})(e):"hex"===t?(e=>{if(e.length%2!=0)throw new TypeError('The "hex" encoded string must have an even length');const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(2*r,2*r+2),16);return t})(e):(new TextEncoder).encode(e);if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError('The "data" argument must be a string, an ArrayBuffer or an ArrayBufferView')})(t,Jn(s,"writeFile")),l=await this.exists(i);if(await this._writeFile(i,a,{append:!0===n,mode:"number"==typeof o?o:void 0}),!l){const e="number"==typeof o?o:438;await this._writeMetadata(i,{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null,mode:e&~this.#hu,uid:this.#uu.uid,gid:this.#uu.gid,birthtimeMs:Date.now(),mtimeMs:Date.now(),atimeMs:Date.now()})}}async appendFile(e,t,r={}){const i=Un(e,"path"),s=Kn(r,"appendFile");return this.writeFile(i,t,{...s,append:!0})}async readdir(e,t={}){const r=Un(e,"path"),{withFileTypes:i,recursive:s}=Kn(t,"readdir"),n=await this._readdir(r),o=[];for(const e of n)if(o.push(!0===i?new Xn(e.name,e.kind):e.name),!0===s&&"directory"===e.kind){const s=`${r.replace(/\/$/,"")}/${e.name}`,n=await this.readdir(s,t);for(const t of n){const r="string"==typeof t?t:t.name;o.push(!0===i?new Xn(`${e.name}/${r}`,"file"):`${e.name}/${r}`)}}return o}async mkdir(e,t={}){const r=Un(e,"path"),{recursive:i,mode:s}=Kn(t,"mkdir");await this._mkdir(r,{recursive:!0===i});const n="number"==typeof s?s:511;return await this._writeMetadata(r,{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null,mode:n&~this.#hu,uid:this.#uu.uid,gid:this.#uu.gid,birthtimeMs:Date.now(),mtimeMs:Date.now(),atimeMs:Date.now()}),!0===i?r:void 0}async rm(e,t={}){const r=Un(e,"path"),{recursive:i,force:s}=Kn(t,"rm");await this._rm(r,{recursive:!0===i,force:!0===s}),this.#au.delete(r)}async unlink(e){const t=Un(e,"path"),r=await this.__stat(t);if(r?.isDirectory())throw qn("EISDIR","unlink",t);await this.rm(t,{force:!1})}async rmdir(e,t={}){const r=Un(e,"path"),{recursive:i}=Kn(t,"rmdir");await this.rm(r,{recursive:!0===i})}async rename(e,t){const r=Un(e,"oldPath"),i=Un(t,"newPath");await this._rename(r,i);const s=await this._readMetadata(r);await this._writeMetadata(i,s),this.#au.delete(r)}async copyFile(e,t,r=0){const i=Un(e,"sourcePath"),s=Un(t,"destinationPath"),n="number"==typeof r?r:0;await this._copyFile(i,s,n);const o=await this._readMetadata(i);await this._writeMetadata(s,o)}async __stat(e,t={}){const r=Un(e,"path"),{throwIfNoEntry:i}=Kn(t,"stat"),s=await this._stat(r);if(void 0===s){if(!1===i)return;throw qn("ENOENT","stat",r)}const n=await this._readMetadata(r),o="directory"===s.kind?511:438;return new Yn({path:r,name:s.name,kind:s.kind,size:s.size,mode:n.mode??o,uid:n.uid??0,gid:n.gid??0,atimeMs:n.atimeMs??s.mtimeMs,mtimeMs:n.mtimeMs??s.mtimeMs,birthtimeMs:n.birthtimeMs??s.mtimeMs,ino:0})}async stat(e,t={}){const r=Un(e,"path"),i=await this.__stat(r,t);if(void 0===i)throw qn("ENOENT","stat",r);return i}async lstat(e,t={}){return this.stat(e,t)}async access(e,t=zn.F_OK){const r=Un(e,"path");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError('The "mode" argument must be an integer');const i=await this.__stat(r);if(t===zn.F_OK)return;if(!i)throw qn("ENOENT","access",r);const s=this.#du(i.uid,i.gid),n=i.mode>>s&7;if(t&zn.R_OK&&!(4&n))throw qn("EACCES","access",r);if(t&zn.W_OK&&!(2&n))throw qn("EACCES","access",r);if(t&zn.X_OK&&!(1&n))throw qn("EACCES","access",r)}async chmod(e,t){const r=Un(e,"path"),i=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e))throw new TypeError(`The "${t}" argument must be an integer`);if(e<0||e>4095)throw new RangeError(`The "${t}" argument must be between 0o0000 and 0o7777`);return e})(t,"mode"),s=await this._readMetadata(r);await this._writeMetadata(r,{...s,mode:i})}async chown(e,t,r){const i=Un(e,"path"),s=Gn(t,"uid"),n=void 0===r?s:Gn(r,"gid"),o=await this._readMetadata(i);await this._writeMetadata(i,{...o,uid:s,gid:n})}async utimes(e,t,r){const i=Un(e,"path"),s=Gn(t,"atimeMs"),n=void 0===r?s:Gn(r,"mtimeMs"),o=await this._readMetadata(i);await this._writeMetadata(i,{...o,atimeMs:s,mtimeMs:n})}async truncate(e,t=0){const r=Un(e,"path"),i=Gn(t,"length"),s=await this.readFile(r),n=new Uint8Array(i);n.set(s.subarray(0,i)),await this.writeFile(r,n)}async realpath(e){const t=Un(e,"path");return await this.__stat(t),`/${Zn(t).join("/")}`}async open(e,t="r"){const r=Un(e,"path");if("string"!=typeof t)throw new TypeError('The "flags" argument must be of type string');return t.includes("w")?await this.writeFile(r,new Uint8Array(0)):t.includes("a")?await this.writeFile(r,new Uint8Array(0),{append:!0}):await this.__stat(r),new Qn(this,r,t)}async exists(e){return void 0!==await this.__stat(e,{throwIfNoEntry:!1})}#cu(e,t){return qn("ENOSYS",e,t,`${e}() is not implemented by ${this.constructor.name}`)}#du(e,t){return e===this.#uu.uid?6:t===this.#uu.gid||this.#uu.groups.includes(t)?3:0}},to=class extends eo{#pu;constructor(e={}){super(e),this.#pu=e.root??null}static get capabilities(){return Object.freeze({permissions:!1,ownership:!1,symlinks:!1,timestamps:!1,atomicRename:!1,seekableHandles:!1})}async _resolveRoot(){if(null!==this.#pu)return this.#pu;if("undefined"==typeof navigator||"function"!=typeof navigator.storage?.getDirectory)throw qn("ENOSYS","getDirectory","/","OPFS is not available in this environment");return this.#pu=await navigator.storage.getDirectory(),this.#pu}async#mu(e,t,r,i){let s=await this._resolveRoot();for(const n of e)try{s=await s.getDirectoryHandle(n,{create:t})}catch(e){throw Vn(e,r,i)}return s}async#fu(e,t){const r=Zn(e),i=r.pop();if(void 0===i)throw qn("EINVAL",t,e,"the root has no parent");return{parent:await this.#mu(r,!1,t,e),name:i}}async#yu(e,t){const r=[];try{for await(const[t,i]of e.entries())r.push({name:t,kind:i.kind})}catch(e){throw Vn(e,"readdir",t)}return r.sort((e,t)=>e.name.localeCompare(t.name))}async#gu(e,t){for await(const[r,i]of e.entries()){if("directory"===i.kind){const e=await t.getDirectoryHandle(r,{create:!0});await this.#gu(i,e);continue}const e=i,s=await e.getFile(),n=await t.getFileHandle(r,{create:!0}),o=await n.createWritable();await o.write(await s.arrayBuffer()),await o.close()}}async _readFile(e){const{parent:t,name:r}=await this.#fu(e,"readFile");try{const e=await t.getFileHandle(r),i=await e.getFile();return new Uint8Array(await i.arrayBuffer())}catch(t){throw Vn(t,"readFile",e,"EISDIR")}}async _writeFile(e,t,r){const{parent:i,name:s}=await this.#fu(e,"writeFile"),n=t;try{const e=await i.getFileHandle(s,{create:!0}),t=await e.createWritable({keepExistingData:!0===r.append});if(!0===r.append){const r=await e.getFile();await t.write({type:"write",position:r.size,data:n})}else await t.write(n);await t.close()}catch(t){throw Vn(t,"writeFile",e)}}async _readdir(e){const t=await this.#mu(Zn(e),!1,"readdir",e);return this.#yu(t,e)}async _mkdir(e,t){const r=Zn(e);if(0===r.length){if(!0===t.recursive)return;throw qn("EEXIST","mkdir",e)}if(!0===t.recursive)return void await this.#mu(r,!0,"mkdir",e);const{parent:i,name:s}=await this.#fu(e,"mkdir");if((await this.#yu(i,e)).some(e=>e.name===s))throw qn("EEXIST","mkdir",e);try{await i.getDirectoryHandle(s,{create:!0})}catch(t){throw Vn(t,"mkdir",e)}}async _rm(e,t){const{parent:r,name:i}=await this.#fu(e,"rm"),s=(await this.#yu(r,e)).find(e=>e.name===i);if(void 0===s){if(!0===t.force)return;throw qn("ENOENT","rm",e)}if("directory"===s.kind&&!0!==t.recursive){const t=await r.getDirectoryHandle(i);if((await this.#yu(t,e)).length>0)throw qn("ENOTEMPTY","rm",e)}try{await r.removeEntry(i,{recursive:!0===t.recursive})}catch(t){throw Vn(t,"rm",e)}}async _stat(e){const t=Zn(e);if(0===t.length)return{name:"/",kind:"directory",size:0,mtimeMs:Date.now()};const r=t.pop(),i=await this.#mu(t,!1,"stat",e),s=(await this.#yu(i,e)).find(e=>e.name===r);if(void 0===s)return;if("directory"===s.kind)return{name:r,kind:"directory",size:0,mtimeMs:Date.now()};const n=await i.getFileHandle(r),o=await n.getFile();return{name:r,kind:"file",size:o.size,mtimeMs:o.lastModified}}async _rename(e,t){const r=await this._stat(e);if(void 0===r)throw qn("ENOENT","rename",e);if("directory"===r.kind){const r=await this.#mu(Zn(e),!1,"rename",e),i=await this.#mu(Zn(t),!0,"rename",t);await this.#gu(r,i)}else{const r=await this._readFile(e);await this._writeFile(t,r,{append:!1})}await this._rm(e,{recursive:!0,force:!0})}async _copyFile(e,t){const r=await this._readFile(e);await this._writeFile(t,r,{append:!1})}},ro="tiny-fs";class io extends to{#wu;#bu;#vu=null;constructor(e={}){super(e);const t=(e=>{if(void 0===e)return{name:ro,options:{}};if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError('The "bucket" option must be of type object');const{name:t,durability:r,persisted:i,quota:s,expires:n}=e;if(void 0!==t&&("string"!=typeof t||0===t.length))throw new TypeError('The "bucket.name" option must be a non-empty string');if(void 0!==r&&"strict"!==r&&"relaxed"!==r)throw new TypeError('The "bucket.durability" option must be "strict" or "relaxed"');if(void 0!==i&&"boolean"!=typeof i)throw new TypeError('The "bucket.persisted" option must be of type boolean');if(void 0!==s){if(!Number.isInteger(s))throw new TypeError('The "bucket.quota" option must be an integer');if(s<0)throw new RangeError('The "bucket.quota" option must not be negative')}if(void 0!==n){if(!Number.isInteger(n))throw new TypeError('The "bucket.expires" option must be an integer');if(n<0)throw new RangeError('The "bucket.expires" option must not be negative')}return{name:t??ro,options:{durability:r,persisted:i,quota:s,expires:n}}})(e.bucket);this.#wu=t.name,this.#bu=t.options}static get isSupported(){return"undefined"!=typeof navigator&&"object"==typeof navigator.storageBuckets&&null!==navigator.storageBuckets}static async listBuckets(){return io.#Eu("keys"),navigator.storageBuckets.keys()}static async deleteBucket(e){if("string"!=typeof e||0===e.length)throw new TypeError('The "name" argument must be a non-empty string');return io.#Eu("delete"),navigator.storageBuckets.delete(e)}get bucketName(){return this.#wu}async _resolveRoot(){if(null!==this.#vu)return this.#vu;io.#Eu("open");const e=await navigator.storageBuckets.open(this.#wu,this.#bu);return this.#vu=await e.getDirectory(),this.#vu}static#Eu(e){if(!io.isSupported)throw qn("ENOSYS",e,"/","the Storage Buckets API is not available in this environment")}}const so=io;function no(e,t="value"){if("string"!=typeof e||0===e.length)throw new TypeError(`The "${t}" argument must be a non-empty string.`)}class oo{#Tu;#Su;#xu=new ae;#Au=new ae;#xr=null;#Cu=!1;constructor({storeName:e,openDatabase:t}){if(no(e,"storeName"),"function"!=typeof t)throw new TypeError('The "openDatabase" option must be a function.');this.#Tu=e,this.#Su=t}get storeName(){return this.#Tu}get isReady(){return this.#Cu}get[Symbol.toStringTag](){return this.constructor.name}hydrate(){return this.#xr??=this.#To(),this.#xr}_action(e){return this.#Au.enqueue(e)}_write(e){return this.#xu.enqueue(e)}async _persist(e){const t=await this.#Su();await new Promise((r,i)=>{const s=t.transaction(this.#Tu,"readwrite").objectStore(this.#Tu).put(e);s.onsuccess=()=>r(void 0),s.onerror=()=>i(s.error)})}async _remove(e){const t=await this.#Su();await new Promise((r,i)=>{const s=t.transaction(this.#Tu,"readwrite").objectStore(this.#Tu).delete(e);s.onsuccess=()=>r(void 0),s.onerror=()=>i(s.error)})}async _clear(){const e=await this.#Su();await new Promise((t,r)=>{const i=e.transaction(this.#Tu,"readwrite").objectStore(this.#Tu).clear();i.onsuccess=()=>t(void 0),i.onerror=()=>r(i.error)})}async#To(){const e=await this.#Su(),t=await oo.#Iu(e,this.#Tu);this._load(t),this.#Cu=!0}_load(e){throw new Error(`The "_load" method of "${this.constructor.name}" is not implemented.`)}static#Iu(e,t){return new Promise((r,i)=>{const s=e.transaction(t,"readonly").objectStore(t).getAll();s.onsuccess=()=>r(s.result),s.onerror=()=>i(s.error)})}}class ao extends oo{#Du;#Ua=new Set;constructor({storeName:e,openDatabase:t,validate:r=null}){if(super({storeName:e,openDatabase:t}),null!==r&&"function"!=typeof r)throw new TypeError('The "validate" option must be a function or null.');this.#Du=r}get size(){return this.#Ua.size}async has(e){no(e),this.#ku(e),await this.hydrate();let t=!1;return await this._action(async()=>{t=this.#Ua.has(e)}),t}async add(e){no(e),this.#ku(e),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Ua.has(e)||(await this._write(()=>this._persist({value:e,timestamp:Date.now()})),this.#Ua.add(e),t=!0)}),t}async delete(e){no(e),this.#ku(e),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Ua.has(e)&&(await this._write(()=>this._remove(e)),this.#Ua.delete(e),t=!0)}),t}async clear(){await this.hydrate(),await this._action(async()=>{await this._write(()=>this._clear()),this.#Ua.clear()})}async toArray(){return await this.hydrate(),[...this.#Ua]}async toJSON(){return this.toArray()}async*values(){await this.hydrate();for(const e of[...this.#Ua])yield e}keys(){return this.values()}async*entries(){for await(const e of this.values())yield[e,e]}[Symbol.asyncIterator](){return this.values()}async forEach(e,t){if("function"!=typeof e)throw new TypeError('The "callbackFn" argument must be a function.');await this.hydrate();for(const r of[...this.#Ua])e.call(t,r,r,this)}async union(...e){await this.hydrate();const t=new Set(this.#Ua);for(const r of e){const e=await ao.#Mu(r);for(const r of e)t.add(r)}return t}async intersection(e){const t=await ao.#Mu(e);await this.hydrate();const r=new Set;for(const e of this.#Ua)t.has(e)&&r.add(e);return r}async difference(e){const t=await ao.#Mu(e);await this.hydrate();const r=new Set;for(const e of this.#Ua)t.has(e)||r.add(e);return r}async symmetricDifference(e){const t=await ao.#Mu(e);await this.hydrate();const r=new Set;for(const e of this.#Ua)t.has(e)||r.add(e);for(const e of t)this.#Ua.has(e)||r.add(e);return r}async isSubsetOf(e){const t=await ao.#Mu(e);await this.hydrate();for(const e of this.#Ua)if(!t.has(e))return!1;return!0}async isSupersetOf(e){const t=await ao.#Mu(e);await this.hydrate();for(const e of t)if(!this.#Ua.has(e))return!1;return!0}async isDisjointFrom(e){const t=await ao.#Mu(e);await this.hydrate();for(const e of this.#Ua)if(t.has(e))return!1;return!0}_load(e){for(const t of e.sort((e,t)=>e.timestamp-t.timestamp))this.#Ua.add(t.value)}static async#Mu(e){if(e instanceof ao)return new Set(await e.toArray());if(e instanceof Set)return new Set(e);if(Array.isArray(e))return new Set(e);throw new TypeError('The "other" argument must be a TinySetDb, a Set, or an Array.')}#ku(e){if(null!==this.#Du&&!this.#Du(e))throw new TypeError(`The value is rejected by the "${this.storeName}" table validator.`)}}class lo extends oo{#Du;#Ua=new Map;constructor({storeName:e,openDatabase:t,validate:r=null}){if(super({storeName:e,openDatabase:t}),null!==r&&"function"!=typeof r)throw new TypeError('The "validate" option must be a function or null.');this.#Du=r}get size(){return this.#Ua.size}async has(e){no(e,"key"),await this.hydrate();let t=!1;return await this._action(async()=>{t=this.#Ua.has(e)}),t}async get(e){let t;return no(e,"key"),await this.hydrate(),await this._action(async()=>{t=this.#Ua.get(e)}),t}async set(e,t){return no(e,"key"),this.#ku(e,t),await this.hydrate(),await this._action(async()=>{await this._write(()=>this._persist({key:e,value:t,timestamp:Date.now()})),this.#Ua.set(e,t)}),this}async delete(e){no(e,"key"),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Ua.has(e)&&(await this._write(()=>this._remove(e)),this.#Ua.delete(e),t=!0)}),t}async clear(){await this.hydrate(),await this._action(async()=>{await this._write(()=>this._clear()),this.#Ua.clear()})}async toArray(){return await this.hydrate(),[...this.#Ua.entries()]}async toJSON(){return this.toArray()}async*keys(){await this.hydrate();for(const e of[...this.#Ua.keys()])yield e}async*values(){await this.hydrate();for(const e of[...this.#Ua.values()])yield e}async*entries(){await this.hydrate();for(const e of[...this.#Ua.entries()])yield e}[Symbol.asyncIterator](){return this.entries()}async forEach(e,t){if("function"!=typeof e)throw new TypeError('The "callbackFn" argument must be a function.');await this.hydrate();for(const[r,i]of[...this.#Ua])e.call(t,i,r,this)}_load(e){for(const t of e.sort((e,t)=>e.timestamp-t.timestamp))this.#Ua.set(t.key,t.value)}#ku(e,t){if(null!==this.#Du&&!this.#Du(e,t))throw new TypeError(`The entry is rejected by the "${this.storeName}" table validator.`)}}class ho{#eo;#ee;#Lu=new Map;#Nu;#xr;constructor(e,t){if(no(e,"name"),!Array.isArray(t)||0===t.length)throw new TypeError('The "migrations" argument must be a non-empty array.');this.#eo=e,this.#ee=t.length;const r=t.map((e,t)=>ho.#_u(e,t)),i=ho.#Pu(r);this.#Nu=ho.#Su(e,r);for(const e of i.values()){const t={storeName:e.name,validate:e.validate,openDatabase:()=>this.#Nu};"map"===e.type?this.#Lu.set(e.name,new lo(t)):this.#Lu.set(e.name,new ao(t))}this.#xr=this.#Nu.then(()=>Promise.all([...this.#Lu.values()].map(e=>e.hydrate())).then(()=>{})),this.#xr.catch(()=>{})}get name(){return this.#eo}get version(){return this.#ee}get tableNames(){return[...this.#Lu.keys()]}get ready(){return this.#xr}tableSet(e){no(e,"tableName");const t=this.#Lu.get(e);if(void 0===t)throw new RangeError(`The "${e}" table is not declared in this database.`);if(!(t instanceof ao))throw new Error(`The "${e}" table is not a Set instance.`);return t}tableMap(e){no(e,"tableName");const t=this.#Lu.get(e);if(void 0===t)throw new RangeError(`The "${e}" table is not declared in this database.`);if(!(t instanceof lo))throw new Error(`The "${e}" table is not a Map instance.`);return t}has(e){return no(e,"tableName"),this.#Lu.has(e)}async close(){(await this.#Nu).close()}static#Ru(e){if("string"==typeof e)return{name:e,type:"set",validate:null};if("object"!=typeof e||null===e)throw new TypeError('Each table must be a string or an object with a "name" property.');const{name:t,type:r,validate:i=null}=e;if(no(t,"table.name"),"set"!==r&&"map"!==r)throw new TypeError(`The "type" option of the "${t}" table must be "set" or "map".`);if(null!==i&&"function"!=typeof i)throw new TypeError(`The "validate" option of the "${t}" table must be a function.`);return{name:t,type:r,validate:i}}static#Su(e,t){return new Promise((r,i)=>{if("undefined"==typeof indexedDB)return void i(new ReferenceError("IndexedDB is not available in the current environment."));const s=indexedDB.open(e,t.length);s.onupgradeneeded=e=>{try{for(let r=e.oldVersion+1;r<=t.length;r+=1)ho.#ju(s.result,t[r-1])}catch(e){i(e),s.transaction?.abort()}},s.onsuccess=()=>{const e=s.result;e.onversionchange=()=>e.close(),r(e)},s.onerror=()=>i(s.error)})}static#ju(e,t){for(const r of t.delete)e.objectStoreNames.contains(r)&&e.deleteObjectStore(r);for(const r of t.create)e.createObjectStore(r.name,{keyPath:"map"===r.type?"key":"value"})}static#_u(e,t){if("object"!=typeof e||null===e)throw new TypeError(`The migration at index ${t} must be an object.`);const{create:r=[],delete:i=[]}=e;if(!Array.isArray(r))throw new TypeError(`The "create" list of the migration at index ${t} must be an array.`);if(!Array.isArray(i))throw new TypeError(`The "delete" list of the migration at index ${t} must be an array.`);for(const e of i)no(e,`migrations[${t}].delete[]`);return{create:r.map(e=>ho.#Ru(e)),delete:[...i]}}static#Pu(e){const t=new Map;for(const r of e){for(const e of r.delete)t.delete(e);for(const e of r.create){if(t.has(e.name))throw new Error(`The "${e.name}" table is created twice.`);t.set(e.name,e)}}return t}}class uo{static#vl=Ms;static get PUSH_TYPE(){return uo.#vl}static#Ou=null;static#$u=null;static isSupported(){return"undefined"!=typeof globalThis&&"serviceWorker"in navigator&&"PushManager"in globalThis&&"Notification"in globalThis}static get permission(){return uo.isSupported()?Notification.permission:"denied"}static async requestPermission(){if(!uo.isSupported())throw new Error("[TinyPushManager] Push API is not supported in this browser.");return await _s()}static decodeVapidKey(e){if("string"!=typeof e||""===e)throw new TypeError("[TinyPushManager] decodeVapidKey: base64 must be a non-empty string.");if(uo.#$u===e&&uo.#Ou)return uo.#Ou;const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),i=Uint8Array.from(r,e=>e.charCodeAt(0));return uo.#Ou=i,uo.#$u=e,i}#Sl;#Hu;#Fu;#zu;#An;#Bu={status:"unsubscribed",subscription:null,error:null};constructor(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("[TinyPushManager] constructor: options must be a non-null object.");const{registration:t,vapidPublicKey:r,endpoints:i={},fetch:s,onChange:n}=e;if("object"!=typeof t||null===t)throw new TypeError("[TinyPushManager] constructor: options.registration is required.");if("string"!=typeof r||""===r)throw new TypeError("[TinyPushManager] constructor: options.vapidPublicKey is required.");if(void 0!==i.subscribe&&"string"!=typeof i.subscribe)throw new TypeError("[TinyPushManager] constructor: endpoints.subscribe must be a string.");if(void 0!==i.unsubscribe&&"string"!=typeof i.unsubscribe)throw new TypeError("[TinyPushManager] constructor: endpoints.unsubscribe must be a string.");if(void 0!==n&&"function"!=typeof n)throw new TypeError("[TinyPushManager] constructor: onChange must be a function.");this.#Sl=t,this.#Hu=r,this.#Fu=i,this.#zu=s??globalThis.fetch.bind(globalThis),this.#An=n??null}get state(){return Object.freeze({...this.#Bu})}async getSubscription(){return uo.isSupported()?this.#Sl.pushManager.getSubscription():null}async subscribe(e={}){if(!uo.isSupported())throw new Error("[TinyPushManager] Push API is not supported in this browser.");this.#Wu({status:"pending",error:null});const t=await uo.requestPermission();if("granted"!==t)throw this.#Wu({status:"denied",subscription:null}),new Error(`[TinyPushManager] Notification permission was not granted: ${t}.`);const r=await this.getSubscription()??await this.#Sl.pushManager.subscribe({...e,userVisibleOnly:!0,applicationServerKey:uo.decodeVapidKey(this.#Hu)});return await this.#qu(r),this.#Wu({status:"subscribed",subscription:r,error:null}),r}async unsubscribe(){const e=await this.getSubscription();return e?(this.#Fu.unsubscribe&&await this.#zu(this.#Fu.unsubscribe,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e.endpoint})}).catch(()=>{}),await e.unsubscribe(),this.#Wu({status:"unsubscribed",subscription:null,error:null}),!0):(this.#Wu({status:"unsubscribed",subscription:null}),!1)}async syncWithServer(){const e=await this.getSubscription();return e?(await this.#qu(e),this.#Wu({status:"subscribed",subscription:e,error:null}),e):null}async#qu(e){if(!this.#Fu.subscribe)return;const t=await this.#zu(this.#Fu.subscribe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.toJSON())});if(!t.ok)throw new Error(`[TinyPushManager] Failed to upload subscription: ${t.status}.`)}#Wu(e){this.#Bu={...this.#Bu,...e},this.#An?.(this.state)}}const co=uo})(),window.TinyEssentials=i})();
1
+ (()=>{var e={606(e){var t,r,i=e.exports={};function s(){throw new Error("setTimeout has not been defined")}function n(){throw new Error("clearTimeout has not been defined")}function o(e){if(t===setTimeout)return setTimeout(e,0);if((t===s||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:s}catch(e){t=s}try{r="function"==typeof clearTimeout?clearTimeout:n}catch(e){r=n}}();var a,l=[],h=!1,u=-1;function c(){h&&a&&(h=!1,a.length?l=a.concat(l):u=-1,l.length&&d())}function d(){if(!h){var e=o(c);h=!0;for(var t=l.length;t;){for(a=l,l=[];++u<t;)a&&a[u].run();u=-1,t=l.length}a=null,h=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===n||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{return r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function m(e,t){this.fun=e,this.array=t}function p(){}i.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new m(e,t)),1!==l.length||h||o(d)},m.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=p,i.addListener=p,i.once=p,i.off=p,i.removeListener=p,i.removeAllListeners=p,i.emit=p,i.prependListener=p,i.prependOnceListener=p,i.listeners=function(e){return[]},i.binding=function(e){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(e){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},133(){},370(){},913(){},942(){},939(){}};const t={};function r(i){const s=t[i];if(void 0!==s)return s.exports;const n=t[i]={exports:{}};return e[i](n,n.exports,r),n.exports}r.cw=e=>{var t;return()=>{if(e){var r=e;e=0,t={exports:{}},r.call(t.exports,t,t.exports)}return t.exports}},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let i={};(()=>{"use strict";r.r(i),r.d(i,{ColorSafeStringify:()=>oe,FuzzySet:()=>Mi,MamdaniInferenceSystem:()=>Li,TinyAdvancedRaffle:()=>ei,TinyAfterScrollWatcher:()=>lr,TinyAnalogClock:()=>Ei,TinyArrayComparator:()=>Ai,TinyArrayPaginator:()=>ti,TinyBrowserMonitor:()=>Mn,TinyClassManager:()=>_i,TinyClipboard:()=>Sr,TinyCloner:()=>zs,TinyColorConverter:()=>Ar,TinyColorValidator:()=>bi,TinyCookieConsent:()=>ni,TinyDayNightCycle:()=>Yr,TinyDebugger:()=>Gi,TinyDomReadyManager:()=>$t,TinyDragDropDetector:()=>Ae,TinyDragger:()=>Ot,TinyElementObserver:()=>Et,TinyFetchLoader:()=>Wo,TinyGamepad:()=>Gr,TinyHtml:()=>Rt,TinyHtmlTagRegexBuilder:()=>xn,TinyHttpResponseRegistry:()=>qs,TinyI18:()=>di,TinyIframeEvents:()=>Fr,TinyImageLoader:()=>zo,TinyInventory:()=>ii,TinyInventoryTrader:()=>si,TinyLevelUp:()=>l,TinyLoadingScreen:()=>gi,TinyLocalStorage:()=>Pr,TinyMapCache:()=>ps,TinyMapDb:()=>lo,TinyMediaCache:()=>yo,TinyMediaLoader:()=>Eo,TinyMediaPlayer:()=>es,TinyNeedBar:()=>pi,TinyNewWinEvents:()=>Ur,TinyNotificationAdapter:()=>Ns,TinyNotifications:()=>Ht,TinyNotifyCenter:()=>me,TinyOPFSFileSystem:()=>to,TinyPkgExportValidator:()=>ns,TinyPlugin:()=>Ds,TinyPluginCore:()=>ks,TinyPluginLayer:()=>Is,TinyPromiseQueue:()=>ae,TinyPushManager:()=>co,TinyRadioFm:()=>Oi,TinyRateLimiter:()=>ue,TinyRouter:()=>cs,TinyServiceWorker:()=>Os,TinySetDb:()=>ao,TinySetMapDatabase:()=>ho,TinySimpleDice:()=>yi,TinySmartScroller:()=>Er,TinyStorageBucketFileSystem:()=>so,TinyTableDb:()=>oo,TinyTextDiffer:()=>Si,TinyTextRangeEditor:()=>Tr,TinyTextarea:()=>qr,TinyThrottledApi:()=>_n,TinyTimeout:()=>Dr,TinyToastNotify:()=>fe,TinyUploadClicker:()=>ts,TinyUriParser:()=>Cn,TinyVersion:()=>ys,TinyWebWorker:()=>Fn,UltraRandomMsgGen:()=>gr,addAiMarkerShortcut:()=>te,areElsCollBottom:()=>it,areElsCollLeft:()=>st,areElsCollPerfBottom:()=>at,areElsCollPerfLeft:()=>lt,areElsCollPerfRight:()=>ht,areElsCollPerfTop:()=>ot,areElsCollRight:()=>nt,areElsCollTop:()=>rt,areElsColliding:()=>ut,areElsPerfColliding:()=>ct,arraySortPositions:()=>d,assertYouTubeOEmbedResponse:()=>ea,asyncReplace:()=>Q,backupFile:()=>ze,breakdownDuration:()=>w,browserIs:()=>Vi,calculateMarketcap:()=>Y,checkObj:()=>_,clearDirectory:()=>Me,clearDirectoryAsync:()=>Ye,cloneObjTypeOrder:()=>D,compareMarketcap:()=>X,compileGlob:()=>Rn,compileGlobRegExp:()=>jn,countObj:()=>b,createCheckDestroyed:()=>le,createPluginIdChecker:()=>vs,createSingletonTask:()=>Ir,decompileGlob:()=>Pn,defuzzifyCentroid:()=>Ii,diffArrayList:()=>c,diffObjList:()=>ie,dirExists:()=>Ne,dirSize:()=>Fe,dirSizeAsync:()=>tt,documentIsFullScreen:()=>P,emailRegex:()=>un,emailStringRegexBuilder:()=>hn,ensureCopyFile:()=>Re,ensureDirectory:()=>De,exitFullScreen:()=>F,extendObjType:()=>I,extractEmails:()=>pn,extractIPsV4:()=>Ys,extractIPsV6:()=>rn,extractMediaId3Tags:()=>nr,extractUrls:()=>ln,extractUsernames:()=>Sn,extractYouTubeVideoId:()=>ta,fetchJson:()=>Ee,fetchText:()=>Te,fetchYouTubeOEmbed:()=>ra,fileExists:()=>Le,fileSize:()=>He,fileSizeAsync:()=>et,findEmailRegex:()=>mn,findIPv4Regex:()=>Js,findIPv6Regex:()=>tn,findUrlRegex:()=>an,findUsernameRegex:()=>Tn,formatBytes:()=>G,formatCustomTimer:()=>f,formatDayTimer:()=>g,formatTimer:()=>y,genFibonacciSeq:()=>J,getAge:()=>K,getBrowserCssPrefix:()=>Wi,getBrowserPings:()=>qi,getDuckTyping:()=>Ui,getElsCollDetails:()=>bt,getElsCollDirDepth:()=>wt,getElsCollOverlap:()=>pt,getElsCollOverlapPos:()=>ft,getElsColliding:()=>dt,getElsPerfColliding:()=>mt,getElsRelativeCenterOffset:()=>gt,getLatestBackupPath:()=>Be,getObjTypeOrder:()=>j,getObjTypeRegistry:()=>R,getPercentage:()=>V,getRectCenter:()=>yt,getSimplePerc:()=>q,getTimeDuration:()=>p,getUserTimeFormat:()=>m,getYouTubeThumbnailUrl:()=>ia,hashText:()=>se,installWindowHiddenScript:()=>Se,ipv4Regex:()=>Ks,ipv6Regex:()=>Zs,isAnyClassInstance:()=>x,isBrowser:()=>$i,isBrowserAgent:()=>Bi,isClass:()=>T,isClassInstance:()=>S,isDirEmpty:()=>_e,isDirEmptyAsync:()=>Xe,isFullScreenMode:()=>$,isJsonObject:()=>v,isObjType:()=>L,isScreenFilled:()=>O,isValidEmail:()=>dn,isValidGlob:()=>On,isValidIPv4:()=>Gs,isValidIPv6:()=>en,isValidObj:()=>E,isValidUrl:()=>on,isValidUsername:()=>En,jsonFilter:()=>Ft,jsonFilterByKeys:()=>Bt,jsonFilterRecursive:()=>zt,listDirs:()=>$e,listDirsAsync:()=>Ze,listFiles:()=>Oe,listFilesAsync:()=>Qe,makeSegmentExtractor:()=>os,multiplyArrayBlocks:()=>u,objType:()=>N,objTypeName:()=>M,offFullScreenChange:()=>W,onFullScreenChange:()=>B,parseMediaMetadata:()=>or,readBase64Blob:()=>ge,readFileBlob:()=>ye,readJsonBlob:()=>we,readJsonFile:()=>Ie,renameFileAddPrefixSuffix:()=>Ve,renameFileBatch:()=>Ue,renameFileNormalizeCase:()=>Ke,renameFilePadNumbers:()=>Ge,renameFileRegex:()=>qe,reorderObjTypeOrder:()=>k,requestFullScreen:()=>H,restoreLatestBackup:()=>We,ruleOfThree:()=>U,safeTextTrim:()=>re,saveJsonFile:()=>be,segmentExtractorV1:()=>as,shuffleArray:()=>h,signPluginIdentity:()=>bs,toTitleCase:()=>Z,toTitleCaseLowerFirst:()=>ee,trapezoid:()=>ki,tryDeleteFile:()=>je,urlRegex:()=>nn,urlStringRegexBuilder:()=>sn,usernameRegex:()=>vn,usernameStringRegexBuilder:()=>gn,valFetchMediaContent:()=>ir,valMediaContentMetadata:()=>sr,verifyPluginSignature:()=>Ss,waitForTrue:()=>Cr,writeJsonFile:()=>ke,writeTextFile:()=>Pe});var e=r.cw(function(e,t){var r,i="object"==typeof Reflect?Reflect:null,s=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};r=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise(function(r,i){function s(r){e.removeListener(t,n),i(r)}function n(){"function"==typeof e.removeListener&&e.removeListener("error",s),r([].slice.call(arguments))}y(e,t,n,{once:!0}),"error"!==t&&function(e,t){"function"==typeof e.on&&y(e,"error",t,{once:!0})}(e,s)})},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,r,i){var s,n,o,a;if(l(r),void 0===(n=e._events)?(n=e._events=Object.create(null),e._eventsCount=0):(void 0!==n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]),void 0===o)o=n[t]=r,++e._eventsCount;else if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),(s=h(e))>0&&o.length>s&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,a=u,console&&console.warn&&console.warn(a)}return e}function c(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,r){var i={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},s=c.bind(i);return s.listener=r,i.wrapFn=s,s}function m(e,t,r){var i=e._events;if(void 0===i)return[];var s=i[t];return void 0===s?[]:"function"==typeof s?r?[s.listener||s]:[s]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(s):f(s,s.length)}function p(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function f(e,t){for(var r=new Array(t),i=0;i<t;++i)r[i]=e[i];return r}function y(e,t,r,i){if("function"==typeof e.on)i.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function s(n){i.once&&e.removeEventListener(t,s),r(n)})}}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return h(this)},o.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,n=this._events;if(void 0!==n)i=i&&void 0===n.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=n[e];if(void 0===l)return!1;if("function"==typeof l)s(l,this,t);else{var h=l.length,u=f(l,h);for(r=0;r<h;++r)s(u[r],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return l(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var r,i,s,n,o;if(l(t),void 0===(i=this._events))return this;if(void 0===(r=i[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length-1;n>=0;n--)if(r[n]===t||r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;0===s?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,s),1===r.length&&(i[e]=r[0]),void 0!==i.removeListener&&this.emit("removeListener",e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,r,i;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var s,n=Object.keys(r);for(i=0;i<n.length;++i)"removeListener"!==(s=n[i])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(i=t.length-1;i>=0;i--)this.removeListener(e,t[i]);return this},o.prototype.listeners=function(e){return m(this,e,!0)},o.prototype.rawListeners=function(e){return m(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]}}),t=r.cw(function(e,t){var i=r(606);function s(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function n(e,t){for(var r,i="",s=0,n=-1,o=0,a=0;a<=e.length;++a){if(a<e.length)r=e.charCodeAt(a);else{if(47===r)break;r=47}if(47===r){if(n===a-1||1===o);else if(n!==a-1&&2===o){if(i.length<2||2!==s||46!==i.charCodeAt(i.length-1)||46!==i.charCodeAt(i.length-2))if(i.length>2){var l=i.lastIndexOf("/");if(l!==i.length-1){-1===l?(i="",s=0):s=(i=i.slice(0,l)).length-1-i.lastIndexOf("/"),n=a,o=0;continue}}else if(2===i.length||1===i.length){i="",s=0,n=a,o=0;continue}t&&(i.length>0?i+="/..":i="..",s=2)}else i.length>0?i+="/"+e.slice(n+1,a):i=e.slice(n+1,a),s=a-n-1;n=a,o=0}else 46===r&&-1!==o?++o:o=-1}return i}var o={resolve:function(){for(var e,t="",r=!1,o=arguments.length-1;o>=-1&&!r;o--){var a;o>=0?a=arguments[o]:(void 0===e&&(e=i.cwd()),a=e),s(a),0!==a.length&&(t=a+"/"+t,r=47===a.charCodeAt(0))}return t=n(t,!r),r?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(e){if(s(e),0===e.length)return".";var t=47===e.charCodeAt(0),r=47===e.charCodeAt(e.length-1);return 0!==(e=n(e,!t)).length||t||(e="."),e.length>0&&r&&(e+="/"),t?"/"+e:e},isAbsolute:function(e){return s(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,t=0;t<arguments.length;++t){var r=arguments[t];s(r),r.length>0&&(void 0===e?e=r:e+="/"+r)}return void 0===e?".":o.normalize(e)},relative:function(e,t){if(s(e),s(t),e===t)return"";if((e=o.resolve(e))===(t=o.resolve(t)))return"";for(var r=1;r<e.length&&47===e.charCodeAt(r);++r);for(var i=e.length,n=i-r,a=1;a<t.length&&47===t.charCodeAt(a);++a);for(var l=t.length-a,h=n<l?n:l,u=-1,c=0;c<=h;++c){if(c===h){if(l>h){if(47===t.charCodeAt(a+c))return t.slice(a+c+1);if(0===c)return t.slice(a+c)}else n>h&&(47===e.charCodeAt(r+c)?u=c:0===c&&(u=0));break}var d=e.charCodeAt(r+c);if(d!==t.charCodeAt(a+c))break;47===d&&(u=c)}var m="";for(c=r+u+1;c<=i;++c)c!==i&&47!==e.charCodeAt(c)||(0===m.length?m+="..":m+="/..");return m.length>0?m+t.slice(a+u):(a+=u,47===t.charCodeAt(a)&&++a,t.slice(a))},_makeLong:function(e){return e},dirname:function(e){if(s(e),0===e.length)return".";for(var t=e.charCodeAt(0),r=47===t,i=-1,n=!0,o=e.length-1;o>=1;--o)if(47===(t=e.charCodeAt(o))){if(!n){i=o;break}}else n=!1;return-1===i?r?"/":".":r&&1===i?"//":e.slice(0,i)},basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');s(e);var r,i=0,n=-1,o=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var a=t.length-1,l=-1;for(r=e.length-1;r>=0;--r){var h=e.charCodeAt(r);if(47===h){if(!o){i=r+1;break}}else-1===l&&(o=!1,l=r+1),a>=0&&(h===t.charCodeAt(a)?-1===--a&&(n=r):(a=-1,n=l))}return i===n?n=l:-1===n&&(n=e.length),e.slice(i,n)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!o){i=r+1;break}}else-1===n&&(o=!1,n=r+1);return-1===n?"":e.slice(i,n)},extname:function(e){s(e);for(var t=-1,r=0,i=-1,n=!0,o=0,a=e.length-1;a>=0;--a){var l=e.charCodeAt(a);if(47!==l)-1===i&&(n=!1,i=a+1),46===l?-1===t?t=a:1!==o&&(o=1):-1!==t&&(o=-1);else if(!n){r=a+1;break}}return-1===t||-1===i||0===o||1===o&&t===i-1&&t===r+1?"":e.slice(t,i)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var r=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return r?r===t.root?r+i:r+"/"+i:i}(0,e)},parse:function(e){s(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;var r,i=e.charCodeAt(0),n=47===i;n?(t.root="/",r=1):r=0;for(var o=-1,a=0,l=-1,h=!0,u=e.length-1,c=0;u>=r;--u)if(47!==(i=e.charCodeAt(u)))-1===l&&(h=!1,l=u+1),46===i?-1===o?o=u:1!==c&&(c=1):-1!==o&&(c=-1);else if(!h){a=u+1;break}return-1===o||-1===l||0===c||1===c&&o===l-1&&o===a+1?-1!==l&&(t.base=t.name=0===a&&n?e.slice(1,l):e.slice(a,l)):(0===a&&n?(t.name=e.slice(1,o),t.base=e.slice(1,l)):(t.name=e.slice(a,o),t.base=e.slice(a,l)),t.ext=e.slice(o,l)),a>0?t.dir=e.slice(0,a-1):n&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};o.posix=o,e.exports=o}),s={};r.r(s),r.d(s,{iu:()=>it,cq:()=>st,P8:()=>at,BO:()=>lt,eh:()=>ht,L2:()=>ot,lP:()=>nt,Kr:()=>rt,wE:()=>ut,D6:()=>ct,PN:()=>bt,t_:()=>wt,aI:()=>pt,ej:()=>ft,kx:()=>dt,Pd:()=>mt,NW:()=>gt,Qv:()=>yt});var n={};r.r(n),r.d(n,{areElsCollBottom:()=>it,areElsCollLeft:()=>st,areElsCollPerfBottom:()=>at,areElsCollPerfLeft:()=>lt,areElsCollPerfRight:()=>ht,areElsCollPerfTop:()=>ot,areElsCollRight:()=>nt,areElsCollTop:()=>rt,areElsColliding:()=>ut,areElsPerfColliding:()=>ct,getElsCollDetails:()=>bt,getElsCollDirDepth:()=>wt,getElsCollOverlap:()=>pt,getElsCollOverlapPos:()=>ft,getElsColliding:()=>dt,getElsPerfColliding:()=>mt,getElsRelativeCenterOffset:()=>gt,getRectCenter:()=>yt});var o={};r.r(o),r.d(o,{q:()=>os,N:()=>as});var a={};r.r(a),r.d(a,{makeSegmentExtractor:()=>os,segmentExtractorV1:()=>as});const l=class{constructor(e,t){if("number"!=typeof e||Number.isNaN(e))throw new Error("giveExp must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("expLevel must be a valid number");this.giveExp=e,this.expLevel=t}createUser(){return{exp:0,level:1,totalExp:0}}validateUser(e){if("number"!=typeof e.exp||Number.isNaN(e.exp))throw new Error("exp must be a valid number");if("number"!=typeof e.level||Number.isNaN(e.level))throw new Error("level must be a valid number");if(e.level<1)throw new Error("level must be at least 1");if("number"!=typeof e.totalExp||Number.isNaN(e.totalExp))throw new Error("totalExp must be a valid number")}isValidUser(e){return!("number"!=typeof e.exp||Number.isNaN(e.exp)||"number"!=typeof e.level||Number.isNaN(e.level)||e.level<1||"number"!=typeof e.totalExp||Number.isNaN(e.totalExp))}getGiveExpBase(){if("number"!=typeof this.giveExp||Number.isNaN(this.giveExp))throw new Error("giveExp must be a valid number");return this.giveExp}getExpLevelBase(){if("number"!=typeof this.expLevel||Number.isNaN(this.expLevel))throw new Error("expLevel must be a valid number");return this.expLevel}expValidator(e){const t=this.getExpLevelBase();this.validateUser(e);let r=0;const i=t*e.level;return e.exp>=i&&(e.level++,r=e.exp-i,e.exp=0,r>0)?this.give(e,r,"extra"):e.exp<1&&e.level>1&&(e.level--,r=Math.abs(e.exp),e.exp=t*e.level,r>0)?this.remove(e,r,"extra"):e}getTotalExp(e){this.validateUser(e);let t=0;for(let r=1;r<=e.level;r++)t+=this.getExpLevelBase()*r;return t+=e.exp,t}expGenerator(e=1){if("number"!=typeof e||Number.isNaN(e))throw new Error("multi must be a valid number");return Math.floor(Math.random()*this.getGiveExpBase())*e}getMissingExp(e){return this.getProgress(e)-e.exp}progress(e){return this.getProgress(e)}getProgress(e){return this.validateUser(e),this.getExpLevelBase()*e.level}set(e,t){if("number"!=typeof t||Number.isNaN(t))throw new Error("value must be a valid number");return e.exp=t,this.expValidator(e),e.totalExp=this.getTotalExp(e),e}give(e,t=0,r="add",i=1){if("number"!=typeof i||Number.isNaN(i))throw new Error("multi must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("extraExp must be a valid number");if("string"!=typeof r)throw new Error("type must be a valid string");return"add"===r?e.exp+=this.expGenerator(i)+t:"extra"===r&&(e.exp+=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}remove(e,t=0,r="add",i=1){if("number"!=typeof i||Number.isNaN(i))throw new Error("multi must be a valid number");if("number"!=typeof t||Number.isNaN(t))throw new Error("extraExp must be a valid number");if("string"!=typeof r)throw new Error("type must be a valid string");return"add"===r?e.exp-=this.expGenerator(i)+t:"extra"===r&&(e.exp-=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}};function h(e){if(!Array.isArray(e))throw new TypeError("Argument 'items' must be an array.");let t,r=e.length;for(;0!==r;)t=Math.floor(Math.random()*r),r--,[e[r],e[t]]=[e[t],e[r]];return e}function u(e,t){if(!Array.isArray(e))throw new TypeError("Argument 'phases' must be an array.");if(!Array.isArray(t))throw new TypeError("Argument 'counts' must be an array.");if(e.length!==t.length)throw new RangeError("The 'phases' and 'counts' arrays must have the same length.");const r=[];for(let i=0;i<e.length;i++){if("number"!=typeof t[i]||Number.isNaN(t[i]))throw new TypeError(`Element at counts[${i}] must be a valid number.`);for(let s=0;s<t[i];s++)r.push(e[i])}return r}function c(e,t){if(!Array.isArray(e))throw new TypeError("Argument 'oldItems' must be an array.");if(!Array.isArray(t))throw new TypeError("Argument 'newItems' must be an array.");const r=e.filter(e=>!t.includes(e));return{added:t.filter(t=>!e.includes(t)),removed:r}}function d(e,t=!1){if(null!=e&&"string"!=typeof e)throw new TypeError("Argument 'item' must be a string or null.");if("boolean"!=typeof t)throw new TypeError("Argument 'isReverse' must be a boolean.");return t?function(t,r){return(e?t[e]:t)>(e?r[e]:r)?-1:(e?t[e]:t)<(e?r[e]:r)?1:0}:function(t,r){return(e?t[e]:t)<(e?r[e]:r)?-1:(e?t[e]:t)>(e?r[e]:r)?1:0}}function m(){const e=new Intl.DateTimeFormat(void 0,{hour:"numeric"}).resolvedOptions().hourCycle;return e?.startsWith("h12")?12:24}function p(e=new Date,t="asSeconds",r=null){if(!(e instanceof Date))throw new TypeError("The 'timeData' argument must be an instance of Date.");if("string"!=typeof t)throw new TypeError("The 'durationType' argument must be a string.");const i=["asMilliseconds","asSeconds","asMinutes","asHours","asDays"];if(!i.includes(t))throw new RangeError(`The 'durationType' must be one of: ${i.join(", ")}.`);if(null!==r&&!(r instanceof Date))throw new TypeError("The 'now' argument must be an instance of Date or null.");const s=r instanceof Date?r:new Date,n=e.getTime()-s.getTime();switch(t){case"asMilliseconds":return n;case"asSeconds":default:return n/1e3;case"asMinutes":return n/6e4;case"asHours":return n/36e5;case"asDays":return n/864e5}}function f(e,t="seconds",r="{time}"){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'totalSeconds' argument must be a valid number.");if("string"!=typeof t)throw new TypeError("The 'level' argument must be a string.");const i=["seconds","minutes","hours","days","months","years"];if(!i.includes(t))throw new RangeError(`The 'level' must be one of: ${i.join(", ")}.`);if("string"!=typeof r)throw new TypeError("The 'format' argument must be a string.");e=Math.max(0,Math.floor(e));const s=i.indexOf(t),n=s>=5,o=s>=4,a=s>=3,l=s>=2,h=s>=1,u=s>=0,c={years:n?0:NaN,months:o?0:NaN,days:a?0:NaN,hours:l?0:NaN,minutes:h?0:NaN,seconds:u?0:NaN,total:NaN};let d=e;if(n||o||a){const e=new Date(1980,0,1),t=new Date(e.getTime()+1e3*d),r=new Date(e);if(n)for(;new Date(r.getFullYear()+1,r.getMonth(),r.getDate()).getTime()<=t.getTime();)r.setFullYear(r.getFullYear()+1),c.years++;if(o)for(;new Date(r.getFullYear(),r.getMonth()+1,r.getDate()).getTime()<=t.getTime();)r.setMonth(r.getMonth()+1),c.months++;if(a)for(;new Date(r.getFullYear(),r.getMonth(),r.getDate()+1).getTime()<=t.getTime();)r.setDate(r.getDate()+1),c.days++;d=Math.floor((t.getTime()-r.getTime())/1e3)}l&&(c.hours=Math.floor(d/3600),d%=3600),h&&(c.minutes=Math.floor(d/60),d%=60),u&&(c.seconds=d),c.total=+e.toFixed(2).replace(/\.00$/,"");const m=e=>{const t="string"==typeof e?parseInt(e):e;return Number.isNaN(t)?"NaN":String(t).padStart(2,"0")},p=[l?m(c.hours):null,h?m(c.minutes):null,u?m(c.seconds):null].filter(e=>null!==e).join(":");return r.replace(/\{years\}/g,String(c.years)).replace(/\{months\}/g,String(c.months)).replace(/\{days\}/g,String(c.days)).replace(/\{hours\}/g,m(c.hours)).replace(/\{minutes\}/g,m(c.minutes)).replace(/\{seconds\}/g,m(c.seconds)).replace(/\{time\}/g,p).replace(/\{total\}/g,String(c.total)).trim()}function y(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'seconds' argument must be a valid number.");return f(e,"hours","{hours}:{minutes}:{seconds}")}function g(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'seconds' argument must be a valid number.");return f(e,"days","{days}d {hours}:{minutes}:{seconds}")}function w(e,t="milliseconds"){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The 'totalMs' argument must be a valid number.");if("string"!=typeof t)throw new TypeError("The 'level' argument must be a string.");const r=["milliseconds","seconds","minutes","hours","days","months","years"];if(!r.includes(t))throw new RangeError(`The 'level' must be one of: ${r.join(", ")}.`);e=Math.max(0,Math.floor(e));const i=r.indexOf(t),s=i>=6,n=i>=5,o=i>=4,a=i>=3,l=i>=2,h=i>=1,u=i>=0,c={years:s?0:NaN,months:n?0:NaN,days:o?0:NaN,hours:a?0:NaN,minutes:l?0:NaN,seconds:h?0:NaN,milliseconds:u?0:NaN,total:NaN};let d=e;if(s||n||o){const e=new Date(1980,0,1),t=new Date(e.getTime()+d),r=new Date(e);if(s)for(;new Date(r.getFullYear()+1,r.getMonth(),r.getDate()).getTime()<=t.getTime();)r.setFullYear(r.getFullYear()+1),c.years++;if(n)for(;new Date(r.getFullYear(),r.getMonth()+1,r.getDate()).getTime()<=t.getTime();)r.setMonth(r.getMonth()+1),c.months++;if(o)for(;new Date(r.getFullYear(),r.getMonth(),r.getDate()+1).getTime()<=t.getTime();)r.setDate(r.getDate()+1),c.days++;d=t.getTime()-r.getTime()}return a&&(c.hours=Math.floor(d/36e5),d%=36e5),l&&(c.minutes=Math.floor(d/6e4),d%=6e4),h&&(c.seconds=Math.floor(d/1e3),d%=1e3),u&&(c.milliseconds=d),c.total=+e,c}function b(e){if(!Array.isArray(e)&&!v(e))throw new TypeError("Argument must be either an Array or a pure JSON Object.");return Array.isArray(e)?e.length:Object.keys(e).length}function v(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e)}function E(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}const T=e=>{if("function"!=typeof e)throw new TypeError("The 'target' argument must be a function. Received: "+typeof e);try{return e(),!1}catch(e){return e instanceof TypeError&&e.message.includes("Class constructor")}};function S(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!1;if("function"!=typeof e.constructor)return!1;const r=e.constructor.toString();return/^\s*class\b/.test(r)}function x(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return null!==t&&t!==Object.prototype&&"function"==typeof e.constructor}const A="undefined"!=typeof window&&void 0!==window.document,C={items:{},order:[]};function I(e,t){if("object"!=typeof e||null===e)throw new TypeError("Argument 'ni' must be an object or an array.");if(void 0!==t&&"number"!=typeof t)throw new TypeError("Argument 'index' must be a number.");const r=[];let i;i=Array.isArray(e)?e.length>0&&Array.isArray(e[0])?e:e.length>0?[e]:[]:Object.entries(e);for(const e of i){if(!Array.isArray(e)||e.length<2)throw new TypeError("Each item in the input must be a [key, function] pair.");const[i,s,n]=e;if(void 0!==n&&"function"!=typeof n)throw new TypeError(`Cloner for key '${i}' must be a function.`);const o="function"==typeof n?n:e=>e;if("string"!=typeof i)throw new TypeError("Validator key must be a string.");if("function"!=typeof s)throw new TypeError(`Validator for key '${i}' must be a function.`);if(!C.items.hasOwnProperty(i)){C.items[i]={validator:s,cloner:o};let e="number"==typeof t?t:-1;if(-1===e){const t=C.order.indexOf("object");e=t>-1?t:C.order.length}e=Math.min(Math.max(0,e),C.order.length),C.order.splice(e,0,i),r.push(i)}}return r}function k(e){if(!Array.isArray(e))throw new TypeError("Argument 'newOrder' must be an array of strings.");if(!e.every(e=>"string"==typeof e))throw new TypeError("All elements in 'newOrder' must be strings.");const t=[...C.order];return!!e.every(e=>t.includes(e))&&(C.order=e.slice(),!0)}function D(){return[...C.order]}const M=e=>{if(null===e)return"null";for(const t of C.order)if("function"!=typeof C.items[t].validator||C.items[t].validator(e))return t;return"unknown"};function L(e,t){if("string"!=typeof t)throw new TypeError("Argument 'type' must be a string.");return M(e)===t.toLowerCase()}function N(e,t){if(void 0===e)return null;if(void 0!==t&&"string"!=typeof t)throw new TypeError("Argument 'type' must be a string.");const r=M(e);return"string"==typeof t?r===t.toLowerCase():r}function _(e){const t={valid:null,type:null};for(const r of C.order)if("function"==typeof C.items[r].validator){const i=C.items[r].validator(e);if(i){t.valid=i,t.type=r;break}}return t}function R(){return Object.fromEntries(Object.entries(C.items).map(([e,t])=>[e,{...t}]))}const j=()=>[...C.order];I([["undefined",e=>void 0===e],["null",e=>null===e],["boolean",e=>"boolean"==typeof e],["number",e=>"number"==typeof e&&!Number.isNaN(e)],["nannumber",e=>"number"==typeof e&&Number.isNaN(e)],["bigint",e=>"bigint"==typeof e],["string",e=>"string"==typeof e],["symbol",e=>"symbol"==typeof e],["function",e=>"function"==typeof e]]),I(["array",e=>Array.isArray(e),(e,t,r)=>e.map(e=>t?r.clone(e,t):e)]),A&&I(["file",e=>"undefined"!=typeof File&&e instanceof File,e=>new File([e],e.name,{type:e.type,lastModified:e.lastModified})]),I(["date",e=>e instanceof Date,e=>new Date(e.getTime())]),I(["regexp",e=>e instanceof RegExp,e=>new RegExp(e.source,e.flags)]),I(["map",e=>e instanceof Map,(e,t,r)=>{const i=new Map;for(const[s,n]of e.entries())i.set(s,t?r.clone(n,t):n);return i}]),I(["set",e=>e instanceof Set,(e,t,r)=>{const i=new Set;for(const s of e)i.add(t?r.clone(s,t):s);return i}]),I([["weakmap",e=>e instanceof WeakMap],["weakset",e=>e instanceof WeakSet],["promise",e=>e instanceof Promise]]),I(["url",e=>e instanceof URL,e=>new URL(e.href)]),A&&I(["htmlelement",e=>"undefined"!=typeof HTMLElement&&e instanceof HTMLElement,e=>e.cloneNode(!0)]),I(["object",e=>v(e),(e,t,r)=>{const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t?r.clone(e[s],t):e[s]);return i}]);const P=()=>!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitIsFullScreen||document.mozFullScreen),O=()=>window.innerHeight===screen.height&&window.innerWidth===screen.width,$=()=>P()||O(),H=e=>new Promise(async(t,r)=>{const i=document.documentElement;try{i.requestFullscreen?await i.requestFullscreen(e):i.mozRequestFullScreen?i.mozRequestFullScreen(e):i.webkitRequestFullScreen?i.webkitRequestFullScreen(e):i.msRequestFullscreen&&i.msRequestFullscreen(e),t()}catch(e){r(e)}}),F=()=>new Promise((e,t)=>{if(document.exitFullscreen)document.exitFullscreen().then(e).catch(t);else try{if(document.mozCancelFullScreen)document.mozCancelFullScreen();else if(document.webkitCancelFullScreen)document.webkitCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Fullscreen API is not supported");document.msExitFullscreen()}e()}catch(e){t(e)}}),z=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],B=(e,t)=>{z.forEach(r=>{document.addEventListener(r,e,t)})},W=(e,t)=>{z.forEach(r=>{document.removeEventListener(r,e,t)})};function U(e,t,r,i=!1){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("val1 must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("val2 must be a finite number.");if("number"!=typeof r||!Number.isFinite(r))throw new TypeError("val3 must be a finite number.");if("boolean"!=typeof i)throw new TypeError("inverse must be a boolean.");return i?Number(e*t)/r:Number(r*t)/e}function q(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("price must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("percentage must be a finite number.");return e*(t/100)}function V(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("part must be a finite number.");if("number"!=typeof t||!Number.isFinite(t))throw new TypeError("total must be a finite number.");return 0===t?0:e/t*100}function K(e=0,t=null){if("number"!=typeof e&&"string"!=typeof e&&!(e instanceof Date))throw new TypeError("timeData must be a number, string, or Date object.");if(null!==t&&!(t instanceof Date))throw new TypeError("now must be a Date object or null.");const r=new Date(e);if(Number.isNaN(r.getTime()))return null;const i=t instanceof Date?t:new Date;let s=i.getFullYear()-r.getFullYear();const n=i.getMonth(),o=r.getMonth(),a=i.getDate(),l=r.getDate();return(n<o||n===o&&a<l)&&s--,Math.abs(s)}function G(e,t=null,r=null){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new TypeError("bytes must be a positive number.");if(0===e)return{unit:"Bytes",value:0};if(null!==t&&("number"!=typeof t||!Number.isFinite(t)))throw new TypeError("decimals must be a number or null.");const i=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"];if(null!==r){if("string"!=typeof r)throw new TypeError("maxUnit must be a string or null.");if(!i.includes(r))throw new RangeError(`maxUnit must be one of: ${i.join(", ")}`)}const s=r&&i.includes(r)?i.indexOf(r):i.length-1,n=Math.min(Math.floor(Math.log(e)/Math.log(1024)),s);let o=e/Math.pow(1024,n);if(null!==t){const e=t<0?0:t;o=parseFloat(o.toFixed(e))}return{unit:i[n],value:o}}function J({baseValues:e=[0,1],length:t=10,combiner:r=(e,t)=>e+t}={}){if(!Array.isArray(e)||2!==e.length||!e.every(e=>"number"==typeof e))throw new Error("baseValues must be an array of exactly two numbers.");if("number"!=typeof t||!Number.isInteger(t))throw new RangeError("length must be an integer.");if("function"!=typeof r)throw new TypeError("combiner must be a function.");const i=[...e.slice(0,2)];for(let e=2;e<t;e++){const t=r(i[e-2],i[e-1],e);i.push(t)}return i}function Y(e,t){if("number"!=typeof e||Number.isNaN(e)||!Number.isFinite(e))throw new TypeError("Original market cap must be a finite number.");if("number"!=typeof t||Number.isNaN(t)||!Number.isFinite(t))throw new TypeError("Circulating supply must be a finite number.");if(t<=0)throw new RangeError("Circulating supply must be greater than zero.");return e/t}function X(e,t,r){if("number"!=typeof r||Number.isNaN(r)||!Number.isFinite(r))throw new TypeError("New market cap must be a finite number.");const i=Y(e,t),s="number"==typeof r?r/t:NaN;return{originalPrice:i,newPrice:s,priceChangePercent:"number"==typeof r?(s-i)/i*100:NaN}}async function Q(e,t,r){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);if(!(t instanceof RegExp))throw new TypeError("Expected a RegExp for 'regex', but received "+typeof t);if("function"!=typeof r)throw new TypeError("Expected a function for 'asyncFn', but received "+typeof r);const i=[];e.replace(t,(e,...t)=>(i.push(r(e,...t)),e));const s=await Promise.all(i);return e.replace(t,()=>s.shift())}function Z(e){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);return e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase())}function ee(e){if("string"!=typeof e)throw new TypeError("Expected a string for 'str', but received "+typeof e);const t=e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase());return t.charAt(0).toLowerCase()+t.slice(1)}function te({key:e="a",className:t="detect-made-by-ai"}={}){if("undefined"==typeof HTMLElement)throw new Error("[AiMarkerShortcut] Environment does not support the DOM. This function must be run in a browser.");if("string"!=typeof e)throw new TypeError("Expected a string for 'config.key', but received "+typeof e);if("string"!=typeof t)throw new TypeError("Expected a string for 'config.className', but received "+typeof t);const r=function(r){if(r.ctrlKey&&r.altKey&&r.key.toLowerCase()===e){if(r.preventDefault(),!document.body)return void console.warn("[AiMarkerShortcut] <body> element not found. Cannot toggle class. Ensure the DOM is fully loaded when using the shortcut.");document.body.classList.toggle(t)}};return document.addEventListener("keydown",r),r}function re(e,t,r=.6){if("string"!=typeof e)throw new TypeError("Expected a string for 'text', but received "+typeof e);if(!Number.isInteger(t)||t<=0)throw new TypeError(`Expected 'limit' to be a positive integer, but received ${t}`);if("number"!=typeof r||r<0||r>1)throw new TypeError(`Expected 'safeCutZone' to be a number between 0 and 1, but received ${r}`);let i=e.trim();if(i.length>t){const e=i.lastIndexOf(" ",t);return e>0&&e>=t*r?`${i.substring(0,e).trim()}...`:`${i.substring(0,t).trim()}...`}return i}function ie(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Expected an object for 'oldStrings', but received "+(null===e?"null":typeof e));if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("Expected an object for 'newStrings', but received "+(null===t?"null":typeof t));const r={added:{},removed:{},modified:{}};for(const i in e)i in t?e[i]!==t[i]&&(r.modified[i]={old:e[i],new:t[i]}):r.removed[i]=e[i];for(const i in t)i in e||(r.added[i]=t[i]);return r}async function se(e,t){if("string"!=typeof e)throw new TypeError('The "text" parameter must be a string.');const r=(new TextEncoder).encode(e),i=await crypto.subtle.digest(t,r);return Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join("")}class ne{#e;static#t={default:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""},solarized:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""},monokai:{reset:"",key:"",string:"",string_url:"",string_bool:"",string_number:"",number:"",boolean:"",null:"",special:"",func:""}};constructor(e={}){this.#e={...ne.#t.default,...e}}#r(e,t){const r=[];e=(e=(e=e.replace(/(?<!")\b(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\b(?!")/g,`${t.number}$1${t.reset}`)).replace(/"([^"]+)":/g,(e,t)=>{const i=`___KEY${r.length}___`;return r.push({marker:i,key:t}),`${i}:`})).replace(/"(?:\\.|[^"\\])*?"/g,e=>{const r=e.slice(1,-1);return/^(https?|ftp):\/\/[^\s]+$/i.test(r)?`${t.string_url}${e}${t.reset}`:/^(true|false|null)$/.test(r)?`${t.string_bool}${e}${t.reset}`:/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(r)?`${t.string_number}${e}${t.reset}`:`${t.string}${e}${t.reset}`});for(const{marker:i,key:s}of r){const r=new RegExp(i,"g");e=e.replace(r,`${t.key}"${s}"${t.reset}`)}return(e=(e=(e=(e=e.replace(/(?<!")\b(true|false)\b(?!")/g,`${t.boolean}$1${t.reset}`)).replace(/(?<!")\bnull\b(?!")/g,`${t.null}null${t.reset}`)).replace(/\[Circular\]/g,`${t.special}[Circular]${t.reset}`)).replace(/\[undefined\]/g,`${t.special}[undefined]${t.reset}`)).replace(/"function.*?[^\\]"/gs,`${t.func}$&${t.reset}`)}colorize(e,t={}){const r={...this.#e,...t};return this.#r(e,r)}getColors(){return{...this.#e}}updateColors(e){Object.assign(this.#e,e)}resetColors(){this.#e={...ne.#t.default}}loadColorPreset(e){const t=ne.#t[e];if(!t)throw new Error(`Preset "${e}" not found.`);this.#e={...t}}saveColorPreset(e,t){ne.#t[e]={...t}}getAvailablePresets(){return Object.keys(ne.#t)}}const oe=ne,ae=class{#i=[];#s=!1;#n={};#o=new Set;isRunning(){return this.#s}async#a(e){if(e&&"function"==typeof e.task&&"function"==typeof e.resolve&&"function"==typeof e.reject){const{task:t,resolve:r,reject:i,delay:s,id:n}=e;try{if(n&&this.#o.has(n))return i(new Error("The function was canceled on TinyPromiseQueue.")),this.#o.delete(n),this.#s=!1,void this.#l();s&&n&&await new Promise(e=>{const t=setTimeout(()=>{delete this.#n[n],e(null)},s);this.#n[n]=t}),r(await t())}catch(e){i(e)}finally{this.#s=!1,this.#l()}}}async#h(){const e=[];for(;this.#i.length&&"POINT_MARKER"===this.#i[0]?.marker;)e.push(this.#i.shift());if(0===e.length)return this.#s=!1,void this.#l();await Promise.all(e.map(({task:e,resolve:t,reject:r,id:i})=>new Promise(async s=>{if(i&&this.#o.has(i))return this.#o.delete(i),r(new Error("The function was canceled on TinyPromiseQueue.")),void s(!0);await e().then(t).catch(r),s(!0)}))),this.#s=!1,this.#l()}async#l(){if(!this.#s&&0!==this.#i.length)if(this.#s=!0,"string"!=typeof this.#i[0]?.marker||"POINT_MARKER"!==this.#i[0]?.marker){const e=this.#i.shift();this.#a(e)}else this.#h()}getIndexById(e){return this.#i.findIndex(t=>t.id===e)}getQueuedIds(){return this.#i.map((e,t)=>({index:t,id:e.id})).filter(e=>"string"==typeof e.id)}reorderQueue(e,t){if("number"!=typeof e||"number"!=typeof t||e<0||t<0||e>=this.#i.length||t>=this.#i.length)return;const[r]=this.#i.splice(e,1);this.#i.splice(t,0,r)}async enqueuePoint(e,t){if("function"!=typeof e)return Promise.reject(new Error("Task must be a function returning a Promise."));if(void 0!==t&&"string"!=typeof t)throw new Error('The "id" parameter must be a string.');return this.#s?new Promise((r,i)=>{this.#i.push({marker:"POINT_MARKER",task:e,resolve:r,reject:i,id:t}),this.#l()}):e()}enqueue(e,t,r){if("function"!=typeof e)return Promise.reject(new Error("Task must be a function returning a Promise."));if(void 0!==t&&("number"!=typeof t||t<0))return Promise.reject(new Error("Delay must be a positive number or undefined."));if(void 0!==r&&"string"!=typeof r)throw new Error('The "id" parameter must be a string.');return new Promise((i,s)=>{this.#i.push({task:e,resolve:i,reject:s,id:r,delay:t}),this.#l()})}cancelTask(e){if("string"!=typeof e)throw new Error('The "id" parameter must be a string.');let t=!1;e in this.#n&&(clearTimeout(this.#n[e]),delete this.#n[e],t=!0);const r=this.getIndexById(e);if(-1!==r){const[e]=this.#i.splice(r,1);e?.reject?.(new Error("The function was canceled on TinyPromiseQueue.")),t=!0}return t&&this.#o.add(e),t}},le=e=>t=>{if(t)throw new Error(`This ${e} instance has been destroyed and can no longer be used.`)},he=le("TinyRateLimiter"),ue=class{#u=!1;get destroyed(){return this.#u}#c=null;#d=null;#m=null;#p=null;#f=null;#y=null;groupData=new Map;lastSeen=new Map;userToGroup=new Map;groupFlags=new Map;groupTTL=new Map;#g=null;setOnMemoryExceeded(e){if(he(this.#u),"function"!=typeof e)throw new Error("onMemoryExceeded must be a function");this.#g=e}clearOnMemoryExceeded(){he(this.#u),this.#g=null}#w=null;setOnGroupExpired(e){if(he(this.#u),"function"!=typeof e)throw new Error("onGroupExpired must be a function");this.#w=e}clearOnGroupExpired(){he(this.#u),this.#w=null}constructor({maxHits:e,interval:t,cleanupInterval:r,maxIdle:i=3e5,maxMemory:s=1e5}){const n=e=>"number"==typeof e&&Number.isFinite(e)&&e>=1&&Number.isInteger(e),o=n(e),a=n(t),l=n(r),h=n(i);if(!o&&!a)throw new Error("RateLimiter requires at least one valid option: 'maxHits' or 'interval'.");if(void 0!==e&&!o)throw new Error("'maxHits' must be a positive integer if defined.");if(void 0!==t&&!a)throw new Error("'interval' must be a positive integer in milliseconds if defined.");if(void 0!==r&&!l)throw new Error("'cleanupInterval' must be a positive integer in milliseconds if defined.");if(!h)throw new Error("'maxIdle' must be a positive integer in milliseconds.");if("number"==typeof s&&Number.isFinite(s)&&s>0)this.#c=Math.floor(s);else{if(null!=s)throw new Error("maxMemory must be a positive number or null");this.#c=null}this.#m=o?e:null,this.#p=a?t:null,this.#f=l?r:null,this.#y=i,null!==this.#f&&(this.#d=setInterval(()=>this._cleanup(),this.#f))}isGroupId(e){he(this.#u);const t=this.groupFlags.get(e);return"boolean"==typeof t&&t}getUsersInGroup(e){he(this.#u);const t=[];for(const[r,i]of this.userToGroup.entries())i===e&&t.push(r);return t}setGroupTTL(e,t){if(he(this.#u),"number"!=typeof t||!Number.isFinite(t)||t<=0)throw new Error("TTL must be a positive number in milliseconds");this.groupTTL.set(e,t)}getGroupTTL(e){return he(this.#u),this.groupTTL.get(e)??null}deleteGroupTTL(e){he(this.#u),this.groupTTL.delete(e)}assignToGroup(e,t){he(this.#u);const r=this.userToGroup.get(e);if(r&&r!==t)throw new Error(`User ${e} is already assigned to group ${r}`);if(r===t)return;const i=this.groupData.get(e);if(this.isGroupId(e)){for(const[r,i]of this.userToGroup.entries())i===e&&this.userToGroup.set(r,t);this.userToGroup.delete(e)}else this.userToGroup.set(e,t);if(!i)return;const s=this.groupData.get(t);if(s)for(const e of i)s.push(e);else{const e=[];for(const t of i)e.push(t);this.groupData.set(t,e)}this.lastSeen.set(t,Date.now()),this.groupFlags.delete(e),this.groupData.delete(e),this.lastSeen.delete(e),this.groupTTL.delete(e),this.groupFlags.set(t,!0)}getGroupId(e){return he(this.#u),this.userToGroup.get(e)||e}hit(e){he(this.#u);const t=this.getGroupId(e),r=Date.now();this.groupData.has(t)||(this.groupData.set(t,[]),this.groupFlags.set(t,!1));const i=this.groupData.get(t);if(!i)throw new Error(`No data found for groupId: ${t}`);if(i.push(r),this.lastSeen.set(t,r),null!==this.#p){const e=r-this.getInterval();for(;i.length&&i[0]<e;)i.shift()}null!==this.#c&&"number"==typeof this.#c&&i.length>this.#c&&(i.splice(0,i.length-this.#c),"function"==typeof this.#g&&this.#g(t))}isRateLimited(e){he(this.#u);const t=this.getGroupId(e);if(!this.groupData.has(t))return!1;const r=this.groupData.get(t);if(!r)throw new Error(`No data found for groupId: ${t}`);if(null!==this.#p){const e=Date.now()-this.getInterval();let t=0;for(let i=r.length-1;i>=0&&r[i]>e;i--)t++;return null!==this.#m?t>this.getMaxHits():t>0}return null!==this.#m&&r.length>this.getMaxHits()}resetGroup(e){he(this.#u),this.groupFlags.delete(e),this.groupData.delete(e),this.lastSeen.delete(e),this.groupTTL.delete(e)}resetUserGroup(e){he(this.#u),this.userToGroup.delete(e)}setData(e,t){if(he(this.#u),!Array.isArray(t))throw new Error("timestamps must be an array of numbers.");for(const e of t)if("number"!=typeof e||!Number.isFinite(e))throw new Error("All timestamps must be finite numbers.");this.groupData.has(e)||this.groupFlags.set(e,!1),this.groupData.set(e,t),this.lastSeen.set(e,Date.now())}hasData(e){return he(this.#u),this.groupData.has(e)}getData(e){return he(this.#u),this.groupData.get(e)||[]}getMaxIdle(){if(he(this.#u),"number"!=typeof this.#y||!Number.isFinite(this.#y)||this.#y<0)throw new Error("'maxIdle' must be a non-negative finite number.");return this.#y}setMaxIdle(e){if(he(this.#u),"number"!=typeof e||!Number.isFinite(e)||e<0)throw new Error("'maxIdle' must be a non-negative finite number.");this.#y=e}_cleanup(){const e=Date.now();for(const[t,r]of this.lastSeen.entries())e-r>(this.getGroupTTL(t)??this.getMaxIdle())&&(this.groupFlags.delete(t),this.groupData.delete(t),this.lastSeen.delete(t),this.groupTTL.delete(t),"function"==typeof this.#w&&this.#w(t))}getActiveGroups(){return he(this.#u),Array.from(this.groupData.keys())}getAllUserMappings(){return he(this.#u),Object.fromEntries(this.userToGroup)}getInterval(){if(he(this.#u),"number"!=typeof this.#p||!Number.isFinite(this.#p))throw new Error("'interval' is not a valid finite number.");return this.#p}getMaxHits(){if(he(this.#u),"number"!=typeof this.#m||!Number.isFinite(this.#m))throw new Error("'maxHits' is not a valid finite number.");return this.#m}getTotalHits(e){he(this.#u);const t=this.groupData.get(e);return Array.isArray(t)?t.length:0}getLastHit(e){he(this.#u);const t=this.groupData.get(e);return t?.length?t[t.length-1]:null}getTimeSinceLastHit(e){he(this.#u);const t=this.getLastHit(e);return null!==t?Date.now()-t:null}_calculateAverageSpacing(e){if(!Array.isArray(e)||e.length<2)return null;let t=0;for(let r=1;r<e.length;r++)t+=e[r]-e[r-1];return t/(e.length-1)}getAverageHitSpacing(e){return he(this.#u),this._calculateAverageSpacing(this.groupData.get(e))}getMetrics(e){he(this.#u);const t=this.groupData.get(e);if(!Array.isArray(t)||0===t.length)return{totalHits:0,lastHit:null,timeSinceLastHit:null,averageHitSpacing:null};const r=t.length,i=t[r-1];return{totalHits:r,lastHit:i,timeSinceLastHit:Date.now()-i,averageHitSpacing:this._calculateAverageSpacing(t)}}destroy(){this.destroyed||(this.#d&&clearInterval(this.#d),this._cleanup(),this.groupData.clear(),this.lastSeen.clear(),this.userToGroup.clear(),this.groupTTL.clear(),this.groupFlags.clear(),this.#u=!0)}},ce=le("TinyNotifyCenter");class de{static getTemplate(){return'\n<div class="notify-overlay hidden">\n <div class="notify-center" id="notifCenter">\n <div class="header">\n <div>Notifications</div>\n <div class="options">\n <button class="clear-all" type="button">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n viewBox="0 0 24 24"\n width="24"\n height="24"\n fill="currentColor"\n >\n <path\n d="M21.6 2.4a1 1 0 0 0-1.4 0L13 9.6l-1.3-1.3a1 1 0 0 0-1.4 0L3 15.6a1 1 0 0 0 0 1.4l4 4a1 1 0 0 0 1.4 0l7.3-7.3a1 1 0 0 0 0-1.4l-1.3-1.3 7.2-7.2a1 1 0 0 0 0-1.4zM6 17l3.5-3.5 1.5 1.5L7.5 18.5 6 17z"\n />\n </svg>\n </button>\n <button class="close">×</button>\n </div>\n </div>\n <div class="list"></div>\n </div>\n</div>\n\n<button class="notify-bell" aria-label="Open notifications">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n fill="currentColor"\n viewBox="0 0 24 24"\n >\n <path\n d="M12 2C10.3 2 9 3.3 9 5v1.1C6.7 7.2 5 9.4 5 12v5l-1 1v1h16v-1l-1-1v-5c0-2.6-1.7-4.8-4-5.9V5c0-1.7-1.3-3-3-3zm0 20c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2z"\n />\n </svg>\n <span class="badge" id="notifBadge">0</span>\n</button>\n '}static insertTemplate(e="afterbegin"){document.body.insertAdjacentHTML(e,de.getTemplate())}#u=!1;get destroyed(){return this.#u}#b;#v;#E;#T;#S;#x=0;#A=99;#C=300;#I=!1;#k=new WeakMap;#D(e){if(this.#k.delete(e),!(e instanceof HTMLElement))throw new Error("Invalid HTMLElement to clear.");e.classList.add("removing"),setTimeout(()=>{this.markAsRead(e),e.remove()},this.#C)}#M(e){this.#x=Math.max(0,e),this.#E.setAttribute("data-value",String(this.#x)),this.#E.textContent=this.#x>this.#A?`${this.#A}+`:String(this.#x)}constructor(e={}){const{center:t=document.getElementById("notifCenter"),badge:r=document.getElementById("notifBadge"),button:i=document.querySelector(".notify-bell"),overlay:s=document.querySelector(".notify-overlay")}=e;if(!(t instanceof HTMLElement))throw new Error(`NotificationCenter: "center" must be an HTMLElement. Got: ${t}`);if(!(s instanceof HTMLElement))throw new Error(`NotificationCenter: "overlay" must be an HTMLElement. Got: ${s}`);if(!(r instanceof HTMLElement))throw new Error(`NotificationCenter: "badge" must be an HTMLElement. Got: ${r}`);if(!(i instanceof HTMLElement))throw new Error(`NotificationCenter: "button" must be an HTMLElement. Got: ${i}`);const n=t?.querySelector(".clear-all"),o=t?.querySelector(".list")??null;if(!(o instanceof HTMLElement))throw new Error(`NotificationCenter: ".list" inside center must be an HTMLElement. Got: ${o}`);this.#b=t,this.#v=o,this.#E=r,this.#T=i,this.#S=s,this.#T.addEventListener("click",()=>this.toggle()),this.#b.querySelector(".close")?.addEventListener("click",()=>this.close()),n&&n.addEventListener("click",()=>this.clear()),this.#S.addEventListener("click",e=>{e.target===this.#S&&this.close()})}setMarkAllAsReadOnClose(e){if(ce(this.#u),"boolean"!=typeof e)throw new TypeError("Expected boolean for markAllAsReadOnClose, got "+typeof e);this.#I=e}setRemoveDelay(e){if(ce(this.#u),"number"!=typeof e)throw new Error('NotificationCenter: "ms" must be an number.');this.#C=e}getItemMode(e){ce(this.#u);const t=this.getItem(e);return t?this.#k.get(t):null}getItem(e){ce(this.#u);const t=this.#v.children.item(e);if(!(t instanceof HTMLElement))throw new Error(`NotificationCenter: "item" must be an HTMLElement. Got: ${t}`);return t}hasItem(e){return ce(this.#u),e>=0&&e<this.#v.children.length}markAsRead(e){ce(this.#u);const t=e instanceof HTMLElement?e:this.getItem(e);t.classList.contains("unread")&&(t.classList.remove("unread"),this.#M(this.#x-1))}add(e,t="text"){ce(this.#u);const r=document.createElement("div");r.className="item unread";let i=null,s=null,n=null,o=null;if("object"==typeof e&&null!==e?(i=e.title,s=e.message,n=e.avatar,o=e.onClick):s=e,n){const e=document.createElement("div");e.className="avatar",e.style.backgroundImage=`url("${n}")`,r.appendChild(e)}const a=document.createElement("div");if(a.className="content",i){const e=document.createElement("div");e.className="title",e.textContent=i,a.appendChild(e)}const l=document.createElement("div");l.className="message","html"===t?l.innerHTML=s:l.textContent=s,a.appendChild(l),"function"==typeof o&&(r.classList.add("clickable"),r.addEventListener("click",e=>{e.target instanceof HTMLElement&&!e.target.closest(".notify-close")&&o(e)}));const h=document.createElement("button");h.className="notify-close",h.setAttribute("type","button"),h.innerHTML="&times;",h.addEventListener("click",e=>{e.stopPropagation(),this.#D(r)}),r.append(a,h),this.#v.prepend(r),this.#k.set(r,t),this.#M(this.#x+1)}remove(e){ce(this.#u);const t=this.getItem(e);this.#D(t)}clear(){ce(this.#u);let e=!0;for(;e;){e=!1;const t=Array.from(this.#v.children);for(const r of t)r instanceof HTMLElement&&!r.classList.contains("removing")&&(this.#D(r),e=!0)}}open(){ce(this.#u),this.#S.classList.remove("hidden"),this.#b.classList.add("open")}close(){if(ce(this.#u),this.#S.classList.add("hidden"),this.#b.classList.remove("open"),this.#I){const e=this.#v.querySelectorAll(".item.unread");for(const t of e)t instanceof HTMLElement&&this.markAsRead(t)}}toggle(){ce(this.#u),this.#b.classList.contains("open")?this.close():this.open()}recount(){ce(this.#u);const e=this.#v.querySelectorAll(".item.unread").length;this.#M(e)}get count(){return this.#x}destroy(){this.#u||(this.#T?.removeEventListener("click",this.toggle),this.#b?.querySelector(".close")?.removeEventListener("click",this.close),this.#b?.querySelector(".clear-all")?.removeEventListener("click",this.clear),this.#S?.removeEventListener("click",this.close),this.clear(),this.#b?.remove(),this.#S?.remove(),this.#T?.remove(),this.#x=0,this.#k=new WeakMap,this.#u=!0)}}const me=de,pe=le("TinyToastNotify"),fe=class{#L;#N;#_;#R;#j;#P;#u=!1;get destroyed(){return this.#u}constructor(e="top",t="right",r=3e3,i=50,s=300,n=".notify-container"){this.#O(e),this.#$(t),this.#H(r,"baseDuration"),this.#H(i,"extraPerChar"),this.#H(s,"fadeOutDuration"),this.#L=e,this.#N=t,this.#_=r,this.#R=i,this.#j=s;const o=document.querySelector(`${n}.${e}.${t}`);o instanceof HTMLElement?this.#P=o:(this.#P=document.createElement("div"),this.#P.className=`notify-container ${e} ${t}`,document.body.appendChild(this.#P))}getContainer(){if(pe(this.#u),!(this.#P instanceof HTMLElement))throw new Error("Container is not a valid HTMLElement.");return this.#P}#O(e){if(!["top","bottom"].includes(e))throw new Error(`Invalid vertical direction "${e}". Expected "top" or "bottom".`)}#$(e){if(!["left","right","center"].includes(e))throw new Error(`Invalid horizontal position "${e}". Expected "left", "right" or "center".`)}#H(e,t){if("number"!=typeof e||e<0||!Number.isFinite(e))throw new Error(`Invalid value for "${t}": ${e}. Must be a non-negative finite number.`)}getY(){return pe(this.#u),this.#L}setY(e){pe(this.#u),this.#O(e);const t=this.getContainer();t.classList.remove(this.#L),t.classList.add(e),this.#L=e}getX(){return pe(this.#u),this.#N}setX(e){pe(this.#u),this.#$(e);const t=this.getContainer();t.classList.remove(this.#N),t.classList.add(e),this.#N=e}getBaseDuration(){return pe(this.#u),this.#_}setBaseDuration(e){pe(this.#u),this.#H(e,"baseDuration"),this.#_=e}getExtraPerChar(){return pe(this.#u),this.#R}setExtraPerChar(e){pe(this.#u),this.#H(e,"extraPerChar"),this.#R=e}getFadeOutDuration(){return pe(this.#u),this.#j}setFadeOutDuration(e){pe(this.#u),this.#H(e,"fadeOutDuration"),this.#j=e}show(e){pe(this.#u);let t="",r="",i=null,s=!1,n=null;const o=document.createElement("div");if(o.className="notify enter","string"==typeof e)t=e;else{if("object"!=typeof e||null===e||"string"!=typeof e.message)throw new Error("Invalid argument for show(): expected string or { message: string, title?: string, onClick?: function, html?: boolean, avatar?: string }");if(t=e.message,r="string"==typeof e.title?e.title:"",s=!0===e.html,n="string"==typeof e.avatar?e.avatar:null,void 0!==e.onClick){if("function"!=typeof e.onClick)throw new Error("onClick must be a function if defined");i=e.onClick,o.classList.add("clickable")}}const a=document.createElement("button");if(a.innerHTML="&times;",a.className="close",a.setAttribute("aria-label","Close"),a.addEventListener("mouseenter",()=>{a.style.color="var(--notify-close-color-hover)"}),a.addEventListener("mouseleave",()=>{a.style.color="var(--notify-close-color)"}),n){const e=document.createElement("img");e.src=n,e.alt="avatar",e.className="avatar",o.appendChild(e)}if(r){const e=document.createElement("strong");e.textContent=r,e.style.display="block",o.appendChild(e)}if(s){const e=document.createElement("div");e.innerHTML=t,o.appendChild(e)}else o.appendChild(document.createTextNode(t));o.appendChild(a),this.getContainer().appendChild(o);const l=this.#_+t.length*this.#R+this.#j;let h=!1;const u=()=>{h||(h=!0,o.classList.remove("enter","show"),o.classList.add("exit"),setTimeout(()=>o.remove(),this.#j))};"function"==typeof i&&o.addEventListener("click",e=>{e.target!==a&&i(e,u)}),a.addEventListener("click",e=>{e.stopPropagation(),u()}),setTimeout(()=>{o.classList.remove("enter"),o.classList.add("show")},1),setTimeout(()=>u(),l)}destroy(){this.#u||this.#P instanceof HTMLElement&&(this.#P.querySelectorAll(".notify").forEach(e=>e.remove()),this.#P.parentNode&&this.#P.parentNode.removeChild(this.#P),this.#P=null,this.#u=!0)}};function ye(e,t){if(!(e instanceof Blob))return Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'));const r=["readAsArrayBuffer","readAsDataURL","readAsText","readAsBinaryString"];return"string"==typeof t&&r.includes(t)?new Promise((r,i)=>{const s=new FileReader;s.onload=()=>{try{r(s.result)}catch(e){i(e)}},s.onerror=()=>{i(s.error)},s[t](e)}):Promise.reject(new TypeError(`The "method" argument must be one of: ${r.join(", ")}.`))}function ge(e,t=!1){return e instanceof Blob?"string"!=typeof t&&"boolean"!=typeof t?Promise.reject(new TypeError("The isDataUrl parameter must be a boolean or a string.")):new Promise((r,i)=>{ye(e,"readAsDataURL").then(e=>{if("string"!=typeof e)throw new TypeError("Expected file content to be a string.");const i=e.match(/^data:(.+);base64,(.*)$/);if(!i||!i[2])throw new Error("Invalid data URL format or missing Base64 content.");const[,s,n]=i;if(!/^[\w/+]+=*$/.test(n))throw new Error("Base64 content is malformed.");if("boolean"==typeof t)return r(t?e:n);if(!/^[\w-]+\/[\w.+-]+$/.test(t))throw new Error(`Invalid MIME type string: ${t}`);return r(`data:${t};base64,${n}`)}).catch(i)}):Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'))}function we(e){return e instanceof Blob?new Promise((t,r)=>ye(e,"readAsText").then(e=>{if("string"!=typeof e)throw new TypeError("Expected file content to be a string.");const r=e.trim();if(0===r.length)throw new Error("File is empty or contains only whitespace.");const i=JSON.parse(r);if("object"!=typeof i||null===i)throw new Error("Parsed content is not a valid JSON object or array.");t(i)}).catch(r)):Promise.reject(new TypeError('The "file" argument must be an instance of Blob or File.'))}function be(e,t,r=2){if("string"!=typeof e)throw new TypeError('The "filename" argument must be a string.');if("number"!=typeof r||!Number.isInteger(r)||r<0)throw new TypeError('The "spaces" argument must be a non-negative integer.');const i=JSON.stringify(t,null,r),s=new Blob([i],{type:"application/json"}),n=URL.createObjectURL(s),o=document.createElement("a");o.href=n,o.download=e,o.click(),URL.revokeObjectURL(n)}function ve(e,t,r=e=>({headers:e.headers,status:e.status,statusText:e.statusText})){if(!(e instanceof Response))throw new TypeError('The "response" argument must be an instance of Response.');if("function"!=typeof t)throw new TypeError('The "onProgress" argument must be a function.');if(!e.body)return e;const i=e.headers.get("content-length"),s=i?parseInt(i,10):0;let n=0;const o=e.body.getReader(),a=new ReadableStream({async start(e){for(;;){const{done:r,value:i}=await o.read();if(r)break;n+=i.byteLength,t(n,s),e.enqueue(i)}e.close()}});return new Response(a,r(e))}async function Ee(e,t,r){return"string"!=typeof e?Promise.reject(new TypeError('The "url" argument must be a string.')):void 0!==t&&"object"!=typeof t?Promise.reject(new TypeError('The "options" argument must be an object.')):void 0!==r&&"function"!=typeof r?Promise.reject(new TypeError('The "onProgress" option must be a function.')):new Promise((i,s)=>{fetch(e,t??void 0).then(async e=>{const t=r?ve(e,r):e,s=t.headers.get("content-type")||"";if(!s.includes("application/json"))throw new Error(`Unexpected content-type: ${s}`);const n=await t.json();if(!Array.isArray(n)&&!v(n))throw new Error("Received invalid data instead of valid JSON.");return i(n)}).catch(s)})}async function Te(e,t,r,i){return"string"!=typeof e?Promise.reject(new TypeError('The "url" argument must be a string.')):void 0===t||Array.isArray(t)?void 0!==r&&"object"!=typeof r?Promise.reject(new TypeError('The "options" argument must be an object.')):void 0!==i&&"function"!=typeof i?Promise.reject(new TypeError('The "onProgress" option must be a function.')):new Promise((s,n)=>{fetch(e,r??void 0).then(async e=>{const r=i?ve(e,i):e,n=r.headers.get("content-type")||"";if(Array.isArray(t)&&t.length>0&&!t.some(e=>n.includes(e)))throw new Error(`Blocked MIME type: ${n}`);const o=await r.text();return s(o)}).catch(n)}):Promise.reject(new TypeError('The "allowedMimeTypes" argument must be an array of strings.'))}function Se(e={}){if(null===e||"object"!=typeof e)throw new TypeError('The "settings" argument must be an object.');const{element:t=document.body,hiddenClass:r="windowHidden",visibleClass:i="windowVisible",onVisible:s,onHidden:n}=e;if(!(t instanceof Element))throw new TypeError('"element" must be an instance of Element.');if("string"!=typeof r)throw new TypeError('"hiddenClass" must be a string.');if("string"!=typeof i)throw new TypeError('"visibleClass" must be a string.');if(void 0!==s&&"function"!=typeof s)throw new TypeError('"onVisible" must be a function if provided.');if(void 0!==n&&"function"!=typeof n)throw new TypeError('"onHidden" must be a function if provided.');let o="",a="";const l=()=>{t.classList.remove(r),t.classList.remove(i)};let h=null;const u=["visibilitychange","mozvisibilitychange","webkitvisibilitychange","msvisibilitychange"],c=["hidden","mozHidden","webkitHidden","msHidden"];for(let e=0;e<c.length;e++)if(c[e]in document){h=c[e];break}const d=function(e){l();const u=e?.type,c=h&&document[h];["focus","focusin","pageshow"].includes(u)?(t.classList.add(i),s?.({type:u,oldClass:a,oldType:o}),a=i):["blur","focusout","pagehide"].includes(u)||c?(t.classList.add(r),n?.({type:u,oldClass:a,oldType:o}),a=r):(t.classList.add(i),s?.({type:u,oldClass:a,oldType:o}),a=i),o=u};let m=()=>{};if(h){const e=u[c.indexOf(h)];document.addEventListener(e,d),window.addEventListener("focus",d),window.addEventListener("blur",d),m=()=>{document.removeEventListener(e,d),window.removeEventListener("focus",d),window.removeEventListener("blur",d),l()}}else"onfocusin"in document?(document.onfocusin=document.onfocusout=d,m=()=>{document.onfocusin=document.onfocusout=null,l()}):(window.onpageshow=window.onpagehide=window.onfocus=window.onblur=d,m=()=>{window.onpageshow=window.onpagehide=window.onfocus=window.onblur=null,l()});const p=new Event(h&&document[h]?"blur":"focus");return d(p),m}const xe=le("TinyDragDropDetector"),Ae=class{#F;#z;#B;#W;#U;#q;#V;#u=!1;get destroyed(){return this.#u}constructor(e,t){const{hoverClass:r="dnd-hover",onDrop:i,onEnter:s,onLeave:n}=t;if(!(e instanceof HTMLElement))throw new TypeError('The "target" option must be an instance of HTMLElement.');if("string"!=typeof r)throw new TypeError('The "hoverClass" option must be a string.');if("function"!=typeof i)throw new TypeError('The "onDrop" option must be a function.');if("function"!=typeof s)throw new TypeError('The "onEnter" option must be a function.');if("function"!=typeof n)throw new TypeError('The "onLeave" option must be a function.');this.#F=e,this.#z=r,this.#B=i||(()=>{}),this.#W=s,this.#U=n,this.#q=!1,this.#V=!1,this._handleDragEnter=this._handleDragEnter.bind(this),this._handleDragOver=this._handleDragOver.bind(this),this._handleDragLeave=this._handleDragLeave.bind(this),this._handleDrop=this._handleDrop.bind(this),this.#K()}getTarget(){return xe(this.#u),this.#F}getHoverClass(){return xe(this.#u),this.#z}isDragging(){return xe(this.#u),this.#q}bound(){return xe(this.#u),this.#V}#K(){if(this.#V)return;const e=this.getTarget();e.addEventListener("dragenter",this._handleDragEnter),e.addEventListener("dragover",this._handleDragOver),e.addEventListener("dragleave",this._handleDragLeave),e.addEventListener("drop",this._handleDrop),this.#V=!0}#G(){if(!this.#V)return;const e=this.getTarget();e.removeEventListener("dragenter",this._handleDragEnter),e.removeEventListener("dragover",this._handleDragOver),e.removeEventListener("dragleave",this._handleDragLeave),e.removeEventListener("drop",this._handleDrop),this.#V=!1}_handleDragEnter(e){if(e.preventDefault(),!this.#q){const t=this.getTarget();this.#q=!0,t.classList.add(this.#z),this.#W(e)}}_handleDragOver(e){e.preventDefault(),e.dataTransfer?e.dataTransfer.dropEffect="copy":console.warn("[TinyDragDropDetector] [handleDragOver] DragOver event missing dataTransfer.")}_handleDragLeave(e){e.preventDefault();const t=this.getTarget();null!==e.relatedTarget&&t.contains(e.relatedTarget)||(this.#q=!1,t.classList.remove(this.#z),this.#U(e))}_handleDrop(e){if(e.preventDefault(),!e.dataTransfer)return void console.warn("[TinyDragDropDetector] [handleDrop] DragOver event missing dataTransfer.");const t=this.getTarget();this.#q=!1,t.classList.remove(this.#z);const r=e.dataTransfer.files;r.length>0&&this.#B(r,e)}destroy(){this.#u||(this.#G(),this.getTarget().classList.remove(this.#z),this.#u=!0)}};var Ce=r(133);function Ie(e){if(!(0,Ce.existsSync)(e))throw new Error(`File not found: ${e}`);const t=(0,Ce.readFileSync)(e,"utf-8");return JSON.parse(t)}function ke(e,t,r=2){const i=JSON.stringify(t,null,r);(0,Ce.writeFileSync)(e,i,"utf-8")}function De(e){(0,Ce.existsSync)(e)||(0,Ce.mkdirSync)(e,{recursive:!0})}function Me(e){if(!(0,Ce.existsSync)(e))return;const r=(0,Ce.readdirSync)(e);for(const i of r){const r=(0,t().join)(e,i);(0,Ce.lstatSync)(r).isDirectory()?(0,Ce.rmSync)(r,{recursive:!0,force:!0}):(0,Ce.unlinkSync)(r)}}function Le(e){return(0,Ce.existsSync)(e)&&(0,Ce.lstatSync)(e).isFile()}function Ne(e){return(0,Ce.existsSync)(e)&&(0,Ce.lstatSync)(e).isDirectory()}function _e(e){return 0===(0,Ce.readdirSync)(e).length}function Re(e,r,i){De((0,t().dirname)(r)),(0,Ce.copyFileSync)(e,r,i)}function je(e){return!!Le(e)&&((0,Ce.unlinkSync)(e),!0)}function Pe(e,r,i="utf-8"){De((0,t().dirname)(e)),(0,Ce.writeFileSync)(e,r,i)}function Oe(e,r=!1){const i={files:[],dirs:[]};if(!Ne(e))return i;const s=(0,Ce.readdirSync)(e);for(const n of s){const s=(0,t().join)(e,n);if((0,Ce.lstatSync)(s).isDirectory()){if(i.dirs.push(s),r){const e=Oe(s,!0);i.files.push(...e.files),i.dirs.push(...e.dirs)}}else i.files.push(s)}return i}function $e(e,r=!1){const i=[];if(!Ne(e))return i;const s=(0,Ce.readdirSync)(e);for(const n of s){const s=(0,t().join)(e,n);(0,Ce.lstatSync)(s).isDirectory()&&(i.push(s),r&&i.push(...$e(s,!0)))}return i}function He(e){return Le(e)?(0,Ce.statSync)(e).size:0}function Fe(e){let t=0;const r=Oe(e,!0).files;for(const e of r)t+=He(e);return t}function ze(e,t="bak"){Le(e)&&Re(e,`${e}.${t}.${(new Date).toISOString().replace(/[:.]/g,"-")}`)}function Be(e,r="bak"){const i=(0,t().dirname)(e),s=(0,t().basename)(e),n=(0,Ce.readdirSync)(i).filter(e=>e.startsWith(`${s}.${r}.`)).sort().reverse();if(0===n.length)throw new Error(`No backups found for ${e}`);return(0,t().join)(i,n[0])}function We(e,t="bak"){Re(Be(e,t),e)}function Ue(e,r,i=[]){if("string"!=typeof e)throw new TypeError("dirPath must be a string");if("function"!=typeof r)throw new TypeError("renameFn must be a function");if(!Array.isArray(i))throw new TypeError("extensions must be an array of strings");if(!(0,Ce.existsSync)(e)||!(0,Ce.statSync)(e).isDirectory())throw new Error(`Directory not found or invalid: ${e}`);for(const e of i)if("string"!=typeof e||!e.startsWith("."))throw new TypeError(`Invalid extension: ${e}`);const s=Oe(e).files;let n=0;for(const o of s){const s=(0,t().extname)(o);if(i.length&&!i.includes(s))continue;const a=(0,t().basename)(o),l=r(a,n++),h=(0,t().join)(e,l);a!==l&&(0,Ce.renameSync)(o,h)}}function qe(e,r,i,s=[]){Ue(e,e=>{const s=(0,t().extname)(e);return`${(0,t().basename)(e,s).replace(r,i)}${s}`},s)}function Ve(e,{prefix:r="",suffix:i=""},s=[]){Ue(e,e=>{const s=(0,t().extname)(e),n=(0,t().basename)(e,s);return`${r}${n}${i}${s}`},s)}function Ke(e,r="lower",i=[],s=!1){if("string"!=typeof r||!["lower","upper","title"].includes(r))throw new Error(`Invalid mode "${r}". Must be 'lower', 'upper' or 'title'.`);Ue(e,e=>{const i=e=>"lower"===r?e.toLowerCase():"upper"===r?e.toUpperCase():"title"===r?Z(e):e,n=(0,t().extname)(e),o=s?i(n):n;return`${i((0,t().basename)(e,n))}${o}`},i)}function Ge(e,t=3,r=[]){Ue(e,e=>e.replace(/\d+/,e=>e.padStart(t,"0")),r)}t();var Je=r(370);async function Ye(e){if(!(0,Ce.existsSync)(e))return;const r=await(0,Je.readdir)(e),i={},s=[];for(const n of r){const r=(0,t().join)(e,n),o=(0,Je.lstat)(r);o.then(e=>(i[r]=e,e)),s.push(o)}await Promise.all(s);const n=[];for(const e in i)i[e].isDirectory()?n.push((0,Je.rm)(e,{recursive:!0,force:!0})):n.push((0,Je.unlink)(e));await Promise.all(n)}async function Xe(e){return 0===(await(0,Je.readdir)(e)).length}async function Qe(e,r=!1){const i={files:[],dirs:[]};if(!Ne(e))return i;const s=await(0,Je.readdir)(e);for(const n of s){const s=(0,t().join)(e,n);if((await(0,Je.lstat)(s)).isDirectory()){if(i.dirs.push(s),r){const e=await Qe(s,!0);i.files.push(...e.files),i.dirs.push(...e.dirs)}}else i.files.push(s)}return i}async function Ze(e,r=!1){const i=[];if(!Ne(e))return i;const s=await(0,Je.readdir)(e);for(const n of s){const s=(0,t().join)(e,n);(await(0,Je.lstat)(s)).isDirectory()&&(i.push(s),r&&i.push(...await Ze(s,!0)))}return i}async function et(e){return Le(e)?(await(0,Je.stat)(e)).size:0}async function tt(e){let t=0;const{files:r}=await Qe(e,!0),i=[];for(const e of r){const r=et(e);r.then(e=>(t+=e,e)),i.push(r)}return await Promise.all(i),t}const rt=(e,t)=>e.bottom<t.top,it=(e,t)=>e.top>t.bottom,st=(e,t)=>e.right<t.left,nt=(e,t)=>e.left>t.right,ot=(e,t)=>e.bottom<=t.top,at=(e,t)=>e.top>=t.bottom,lt=(e,t)=>e.right<=t.left,ht=(e,t)=>e.left>=t.right,ut=(e,t)=>!(st(e,t)||nt(e,t)||rt(e,t)||it(e,t)),ct=(e,t)=>!(lt(e,t)||ht(e,t)||ot(e,t)||at(e,t)),dt=(e,t)=>st(e,t)?"left":nt(e,t)?"right":rt(e,t)?"top":it(e,t)?"bottom":null,mt=(e,t)=>lt(e,t)?"left":ht(e,t)?"right":ot(e,t)?"top":at(e,t)?"bottom":null,pt=(e,t)=>({overlapLeft:t.right-e.left,overlapRight:e.right-t.left,overlapTop:t.bottom-e.top,overlapBottom:e.bottom-t.top}),ft=({overlapLeft:e=-1,overlapRight:t=-1,overlapTop:r=-1,overlapBottom:i=-1}={})=>({dirX:e<t?"right":"left",dirY:r<i?"bottom":"top"}),yt=e=>({x:e.left+e.width/2,y:e.top+e.height/2});function gt(e,t){const r=e.left+e.width/2,i=e.top+e.height/2;return{x:t.left+t.width/2-r,y:t.top+t.height/2-i}}function wt(e,t){if(!ct(e,t))return{inDir:null,dirX:null,dirY:null,depthX:0,depthY:0};const{overlapLeft:r,overlapRight:i,overlapTop:s,overlapBottom:n}=pt(e,t),{dirX:o,dirY:a}=ft({overlapLeft:r,overlapRight:i,overlapTop:s,overlapBottom:n}),l=Math.min(r,i),h=Math.min(s,n);let u;return u=l<h?o:a,{inDir:u,dirX:o,dirY:a,depthX:l,depthY:h}}function bt(e,t){const r=ct(e,t),i={in:null,x:null,y:null},s={y:null,x:null},n={top:0,bottom:0,left:0,right:0},{overlapLeft:o,overlapRight:a,overlapTop:l,overlapBottom:h}=pt(t,e);n.top=l,n.bottom=h,n.left=o,n.right=a;const u=Object.entries(n).filter(([,e])=>e>0).sort((e,t)=>e[1]-t[1]),{dirX:c,dirY:d}=ft({overlapLeft:a,overlapRight:o,overlapTop:h,overlapBottom:l});return i.y=d,i.x=c,n.bottom<0?s.y="bottom":n.top<0&&(s.y="top"),n.left<0?s.x="left":n.right<0&&(s.x="right"),i.in=r?n.top===n.bottom&&n.bottom===n.left&&n.left===n.right?"center":u.length?u[0][0]:"top":null,{dirs:i,depth:n,isNeg:s}}const vt=le("TinyElementObserver"),Et=class{#u=!1;get destroyed(){return this.#u}#J;get el(){return vt(this.#u),this.#J}#Y={};get settings(){return vt(this.#u),this.#Y}set settings(e){if(vt(this.#u),"object"!=typeof e||null===e)throw new TypeError("settings must be a non-null object.");this.#Y=e}#X=null;get observer(){return vt(this.#u),this.#X}#Q=[];get detectors(){return vt(this.#u),this.#Q.map(e=>[e[0],e[1]])}set detectors(e){if(vt(this.#u),!Array.isArray(e))throw new TypeError("detectors must be an array.");const t=[];for(const[r,i]of e){if("string"!=typeof r)throw new TypeError("Detector name must be a string.");if("function"!=typeof i)throw new TypeError(`Detector handler for "${r}" must be a function.`);t.push([r,i])}this.#Q=t}get isActive(){return vt(this.#u),!!this.#X}get size(){return vt(this.#u),this.#Q.length}constructor(e,{initDetectors:t=[],initCfg:r={}}={}){this.#J=e,t.length&&(this.detectors=t),r&&(this.settings=r)}clear(){vt(this.#u),this.#Q=[]}start(){if(vt(this.#u),!this.#J)throw new Error("Cannot start observation: no target element has been set.");this.#X||(this.#X=new MutationObserver(e=>{e.forEach((e,t,r)=>this.#Q.forEach(i=>i[1](e,t,r)))}),this.#X.observe(this.#J,this.#Y))}stop(){vt(this.#u),this.#X&&(this.#X.disconnect(),this.#X=null)}add(e,t){vt(this.#u),this.#Z(e,t),this.#Q.push([e,t])}insertAtStart(e,t){vt(this.#u),this.#Z(e,t),this.#Q.unshift([e,t])}insertAt(e,t,r,i="after"){if(vt(this.#u),this.#Z(t,r),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for insertDetectorAt.");const s="before"===i?e:e+1;this.#Q.splice(s,0,[t,r])}removeAt(e){if(vt(this.#u),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for removeDetectorAt.");this.#Q.splice(e,1)}removeAround(e,t=0,r=0){if(vt(this.#u),"number"!=typeof e||e<0||e>=this.#Q.length)throw new RangeError("Invalid index for removeDetectorsAround.");const i=Math.max(0,e-t),s=t+1+r;this.#Q.splice(i,s)}isIndexUsed(e){return vt(this.#u),e>=0&&e<this.#Q.length}hasHandler(e){if(vt(this.#u),"function"!=typeof e)throw new TypeError("Handler must be a function.");return this.#Q.some(([t,r])=>r===e)}#Z(e,t){if("string"!=typeof e||!e.trim())throw new TypeError("Detector name must be a non-empty string.");if("function"!=typeof t)throw new TypeError(`Detector handler for "${e}" must be a function.`)}destroy(){this.#u||(this.stop(),this.clear(),this.#u=!0)}},{wE:Tt,D6:St,Kr:xt,iu:At,cq:Ct,lP:It}=s,kt=new WeakMap,Dt=new WeakMap,Mt=new WeakMap,Lt=new WeakMap,Nt={top:new WeakMap,bottom:new WeakMap,left:new WeakMap,right:new WeakMap};class _t{static Utils={...n};static#ee=1;static get version(){return this.#ee}static#te=!1;static get elemDebug(){return _t.#te}static set elemDebug(e){if("boolean"!=typeof e)throw new TypeError("Expected a boolean value for elemDebug");_t.#te=e}static _debugElemError(e,t){if(!_t.#te)return;const r="[TinyHtml Debug] Element validation error";if(console.groupCollapsed(`${r}${t?" — details below":""}`),console.error(r),"undefined"!=typeof Error&&"function"==typeof Error.captureStackTrace){const e=new Error(r);Error.captureStackTrace(e,_t._debugElemError),console.error(e.stack)}else console.trace(r);if(Array.isArray(e)){const t=e.map((e,t)=>({index:t,typeOf:null===e?"null":typeof e,constructor:e?.constructor?.name??(null===e?"null":"primitive"),summary:"undefined"!=typeof Element&&e instanceof Element?`${e.tagName?.toLowerCase?.()??"element"}#${e.id||""}.${String(e.className||"").trim().replace(/\s+/g,".")}`:e&&"object"==typeof e&&"nodeType"in e?`nodeType:${e.nodeType}`:"",value:e}));console.table(t)}else console.warn('[TinyHtml Debug] "elems" is not an array:',e);arguments.length>1&&(console.error("[TinyHtml Debug] Problematic element:",t),t&&"object"==typeof t&&console.dir(t)),console.groupEnd()}static parseStyle(e){const t={};return e.split(";").forEach(e=>{const[r,i]=e.split(":").map(e=>e&&e.trim());r&&i&&(t[r]=i)}),t}static#re="undefined"!=typeof window&&void 0!==window.document?new Et(window.document.documentElement,{initDetectors:[["tinyStyleEvent",e=>{if("attributes"!==e.type||"style"!==e.attributeName||!(e.target instanceof HTMLElement))return;const t=e.oldValue||"",r=e.target.getAttribute("style")||"",i=ie(_t.parseStyle(t),_t.parseStyle(r));(Object.keys(i.added).length||Object.keys(i.removed).length||Object.keys(i.modified).length)&&e.target.dispatchEvent(new CustomEvent("tinyhtml.stylechanged",{detail:i}))}],["tinyClassEvent",e=>{if("attributes"!==e.type||"class"!==e.attributeName||!(e.target instanceof HTMLElement))return;const t=e.oldValue||"",r=e.target.className||"",i=c(t.split(/\s+/).filter(Boolean),r.split(/\s+/).filter(Boolean));(i.added.length||i.removed.length)&&e.target.dispatchEvent(new CustomEvent("tinyhtml.classchanged",{detail:i}))}]],initCfg:{attributeOldValue:!0,attributes:!0,subtree:!0,attributeFilter:["style","class"]}}):void 0;static get tinyObserver(){return _t.#re}static async fetchHtmlFile(e,t={method:"GET"}){const r=await fetch(e,t),i=r.headers.get("Content-Type")||"";if(!r.ok)throw new Error(`Failed to fetch: ${r.status} ${r.statusText}`);if(!i.includes("text/html"))throw new Error(`Invalid content type: ${i} (expected text/html)`);const s=await r.text();return _t.htmlToJson(s)}static async fetchHtmlNodes(e,t){const r=await _t.fetchHtmlFile(e,t);return _t.jsonToNodes(r)}static async fetchHtmlTinyElems(e,t){const r=await _t.fetchHtmlNodes(e,t);return _t.toTinyElm(r)}static templateToJson(e){return _t.htmlToJson([...e.content.childNodes].map(e=>e instanceof Element?e.getHTML():e instanceof Text?e.textContent:"").join(""))}static templateToNodes(e){const t=[];return[...e.content.cloneNode(!0).childNodes].map(e=>{if(!(e instanceof Element||e instanceof Text||e instanceof Comment))throw new Error(`Expected only Element nodes in <template>, but found: ${e.constructor.name}`);e instanceof Comment||t.push(e)}),t}static templateToTinyElems(e){return _t.toTinyElm(_t.templateToNodes(e))}static htmlToJson(e){const t=document.createElement("div");t.innerHTML=e.trim();const r=[],i=e=>{if(e instanceof Comment)return null;if(e instanceof Text){const t=e.textContent?.trim();return t||null}if(!(e instanceof Element))return null;const t=e.tagName.toLowerCase(),r={};for(const t of e.attributes)r[_t.getPropName(t.name)]=t.value;const s=Array.from(e.childNodes).map(i).filter(Boolean);return s.length>0?[t,r,...s]:[t,r]};for(const e of t.childNodes){const t=i(e);t&&r.push(t)}return t.innerHTML="",r}static jsonToNodes(e){const t=e=>{if("string"==typeof e)return document.createTextNode(e);if(!Array.isArray(e))return document.createTextNode("");const[r,i,...s]=e,n=document.createElement(r);for(const[e,t]of Object.entries(i))n.setAttribute(_t.getAttrName(e),t);for(const e of s){const r=t(e);r instanceof Comment||n.appendChild(r)}return n};return e.map(t).filter(e=>!(e instanceof Comment))}static jsonToTinyElems(e){return _t.toTinyElm(_t.jsonToNodes(e))}static createFrom(e,t){if("string"!=typeof e)throw new TypeError('The "tagName" must be a string.');if(void 0!==t&&"object"!=typeof t)throw new TypeError('The "attrs" must be a object.');const r=_t.createElement(e);if("object"==typeof t)for(const e in t)r.setAttr(e,t[e]);return r}static createElement(e,t){if("string"!=typeof e)throw new TypeError("[TinyHtml] createElement(): The tagName must be a string.");if(void 0!==t&&"object"!=typeof t)throw new TypeError("[TinyHtml] createElement(): The ops must be a object.");return new _t(document.createElement(e,t))}static createTextNode(e){if("string"!=typeof e)throw new TypeError("[TinyHtml] createTextNode(): The value must be a string.");return new _t(document.createTextNode(e))}static createElementFromHTML(e){const t=document.createElement("template");if(!(e=e.trim()).startsWith("<"))return _t.createTextNode(e);if(t.innerHTML=e,!(t.content.firstChild instanceof Element))throw new Error("The HTML string must contain a valid HTML element.");return new _t(t.content.firstChild)}static createFromHTML(e){const t=document.createElement("template");e=e.trim(),t.innerHTML=e;const r=Array.from(t.content.childNodes);if(!r.every(e=>e instanceof Element||e instanceof Text))throw new Error("The HTML string must contain a valid HTML element.");return new _t(r)}static createFromHtml(e){return _t.createFromHTML(e)}static query(e,t=document){const r=t.querySelector(e);return r?new _t(r):null}querySelector(e){return _t.query(e,_t._preElem(this,"query"))}static queryAll(e,t=document){return new _t(t.querySelectorAll(e))}querySelectorAll(e){return _t.queryAll(e,_t._preElem(this,"queryAll"))}static getById(e){const t=document.getElementById(e);return t?new _t(t):null}static getByClassName(e,t=document){return new _t(t.getElementsByClassName(e))}getElementsByClassName(e){return _t.getByClassName(e,_t._preElem(this,"getByClassName"))}static getByName(e){return new _t(document.getElementsByName(e))}static getByTagNameNS(e,t="http://www.w3.org/1999/xhtml",r=document){return new _t(r.getElementsByTagNameNS(t,e))}getElementsByTagNameNS(e,t="http://www.w3.org/1999/xhtml"){return _t.getByTagNameNS(e,t,_t._preElem(this,"getByTagNameNS"))}get elements(){return[...this.#J]}forEach(e){const t=this.elements.map((e,t)=>this.extract(t));for(const r in t)e(t[r],Number(r),t);return this}get(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");if(!this.#J[e])throw new Error(`No element found at index ${e}.`);return this.#J[e]}extract(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");if(!this.#J[e])throw new Error(`Cannot extract: no element exists at index ${e}.`);return new _t(this.#J[e])}exists(e){if("number"!=typeof e)throw new TypeError("The index must be a number.");return!!this.#J[e]}_getElement(e,t){if(!(this.#J[t]instanceof Element||this.#J[t]instanceof Window||this.#J[t]instanceof Document||this.#J[t]instanceof Text))throw _t._debugElemError([...this.#J],this.#J[t]),new Error(`[TinyHtml] Invalid Element in ${e}().`);return this.#J[t]}_getElements(e){if(!this.#J.every(e=>e instanceof Element||e instanceof Window||e instanceof Document||e instanceof Text))throw _t._debugElemError([...this.#J]),new Error(`[TinyHtml] Invalid Element in ${e}().`);return[...this.#J]}static _preElemsTemplate(e,t,r,i){const s=e=>{const s=[];return e.map(n=>(n instanceof _t?n._getElements(t):[n]).map(n=>{let o=!1;for(const e of r)if(n instanceof e){o=!0;break}if(!o)throw _t._debugElemError([...e],n),new Error(`[TinyHtml] Invalid element of the list "${i.join(",")}" in ${t}().`);return s.push(n),n})),s};return Array.isArray(e)?s(e):s([e])}_preElemsTemplate(e,t,r){return _t._preElemsTemplate(this,e,t,r)}static _preElemTemplate(e,t,r,i,s=!1){const n=e=>{const n=e[0],o=n instanceof _t?n._getElements(t):[n];if(o.length>1)throw _t._debugElemError([...e]),new Error(`[TinyHtml] Invalid element amount in ${t}() (Received ${o.length}/1).`);let a=!1;for(const e of r)if(o[0]instanceof e){a=!0;break}if(!s||null!==o[0]&&void 0!==o[0]||(o[0]=null,a=!0),!a)throw _t._debugElemError([...e],o[0]),new Error(`[TinyHtml] Invalid element of the list "${i.join(",")}" in ${t}().`);return o[0]};if(!Array.isArray(e))return n([e]);if(e.length>1)throw _t._debugElemError([...e]),new Error(`[TinyHtml] Invalid element amount in ${t}() (Received ${e.length}/1).`);return n(e)}_preElemTemplate(e,t,r,i=!1){return _t._preElemTemplate(this,e,t,r,i)}static _preElems(e,t){return _t._preElemsTemplate(e,t,[Element],["Element"])}_preElems(e){return _t._preElems(this,e)}static _preElem(e,t){return _t._preElemTemplate(e,t,[Element],["Element"])}_preElem(e){return _t._preElem(this,e)}static _preNodeElems(e,t){return _t._preElemsTemplate(e,t,[Node],["Node"])}_preNodeElems(e){return _t._preNodeElems(this,e)}static _preNodeElem(e,t){return _t._preElemTemplate(e,t,[Node],["Node"])}_preNodeElem(e){return _t._preNodeElem(this,e)}static _preNodeElemWithNull(e,t){return _t._preElemTemplate(e,t,[Node],["Node"],!0)}_preNodeElemWithNull(e){return _t._preNodeElemWithNull(this,e)}static _preHtmlElems(e,t){return _t._preElemsTemplate(e,t,[HTMLElement],["HTMLElement"])}_preHtmlElems(e){return _t._preHtmlElems(this,e)}static _preHtmlElem(e,t){return _t._preElemTemplate(e,t,[HTMLElement],["HTMLElement"])}_preHtmlElem(e){return _t._preHtmlElem(this,e)}static _preInputElems(e,t){return _t._preElemsTemplate(e,t,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLOptionElement],["HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement"])}_preInputElems(e){return _t._preInputElems(this,e)}static _preInputElem(e,t){return _t._preElemTemplate(e,t,[HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement,HTMLOptionElement],["HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement"])}_preInputElem(e){return _t._preInputElem(this,e)}static _preEventTargetElems(e,t){return _t._preElemsTemplate(e,t,[EventTarget],["EventTarget"])}_preEventTargetElems(e){return _t._preEventTargetElems(this,e)}static _preEventTargetElem(e,t){return _t._preElemTemplate(e,t,[EventTarget],["EventTarget"])}_preEventTargetElem(e){return _t._preEventTargetElem(this,e)}static _preElemsAndWindow(e,t){return _t._preElemsTemplate(e,t,[Element,Window],["Element","Window"])}_preElemsAndWindow(e){return _t._preElemsAndWindow(this,e)}static _preElemAndWindow(e,t){return _t._preElemTemplate(e,t,[Element,Window],["Element","Window"])}_preElemAndWindow(e){return _t._preElemAndWindow(this,e)}static _preElemsAndWinAndDoc(e,t){return _t._preElemsTemplate(e,t,[Element,Window,Document],["Element","Window","Document"]).map(e=>e instanceof Document?e.documentElement:e)}_preElemsAndWinAndDoc(e){return _t._preElemsAndWinAndDoc(this,e)}static _preElemAndWinAndDoc(e,t){const r=_t._preElemTemplate(e,t,[Element,Window,Document],["Element","Window","Document"]);return r instanceof Document?r.documentElement:r}_preElemAndWinAndDoc(e){return _t._preElemAndWinAndDoc(this,e)}static _preElemsWithDoc(e,t){return _t._preElemsTemplate(e,t,[Element,Document],["Element","Document"])}_preElemsWithDoc(e){return _t._preElemsWithDoc(this,e)}static _preElemWithDoc(e,t){return _t._preElemTemplate(e,t,[Element,Document],["Element","Document"])}_preElemWithDoc(e){return _t._preElemWithDoc(this,e)}static toTinyElm(e){const t=e=>e.map(e=>e instanceof _t?e:new _t(e));return Array.isArray(e)?t(e):t([e])}static fromTinyElm(e){const t=e=>{const t=[];return e.map(e=>(e instanceof _t?e._getElements("fromTinyElm"):[e]).map(e=>t.push(e))),t};return Array.isArray(e)?t(e):t([e])}static winnow(e,t,r,i=!1){if("boolean"!=typeof i)throw new TypeError('The "not" must be a boolean.');if("function"==typeof t)return _t._preElems(e,r).filter((e,r)=>!!t.call(e,r,e)!==i);if(t instanceof Element)return _t._preElems(e,r).filter(e=>e===t!==i);if(Array.isArray(t)||"string"!=typeof t&&null!=t.length)return _t._preElems(e,r).filter(e=>t.includes(e)!==i);let s=t;return i&&(s=`:not(${s})`),_t._preElems(e,r).filter(e=>1===e.nodeType&&e.matches(s))}static filter(e,t,r=!1){return r&&(t=`:not(${t})`),_t._preElems(e,"filter").filter(e=>1===e.nodeType&&e.matches(t))}static filterOnly(e,t){return _t.winnow(e,t,"filterOnly",!1)}static not(e,t){return _t.winnow(e,t,"not",!0)}not(e){return _t.not(this,e)}static find(e,t){const r=[];for(const i of _t._preElems(e,"find"))r.push(...i.querySelectorAll(t));return[...new Set(r)]}find(e){return _t.find(this,e)}static is(e,t){return _t.winnow(e,t,"is",!1).length>0}is(e){return _t.is(this,e)}static has(e,t){const r="string"==typeof t?[...document.querySelectorAll(t)]:_t._preElems(t,"has");return _t._preElems(e,"has").filter(e=>r.some(t=>e&&e.contains(t)))}has(e){return _t.has(this,e)}static closest(e,t,r){const i=[];for(const s of _t._preElems(e,"closest")){let e=s;for(;e&&e!==r;){if(1===e.nodeType&&("string"==typeof t?e.matches(t):e===t)){i.push(e);break}e=e.parentElement}}return[...new Set(i)]}closest(e,t){return _t.closest(this,e,t)}static isSameDom(e,t){return _t._preNodeElem(e,"isSameDom")===_t._preNodeElem(t,"isSameDom")}isSameDom(e){return _t.isSameDom(this,e)}#ie={};get _data(){return{...this.#ie}}set _data(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new Error("value must be a non-null object.");this.#ie=e}static _dataSelector={public:(e,t)=>{const r=_t._preElem(t,e);let i=Dt.get(r);return i||(i={},Dt.set(r,i)),i},private:(e,t)=>{if(!(t instanceof _t))throw new Error(`Element must be a TinyHtml instance to execute ${e}().`);return t.#ie}};static data(e,t,r=!1){const i=_t._dataSelector[r?"private":"public"]("data",e);if(null==t)return{...i};if("string"!=typeof t)throw new TypeError("The key must be a string.");return i.hasOwnProperty(t)?i[t]:void 0}data(e,t){return _t.data(this,e,t)}static setData(e,t,r,i=!1){const s=_t._dataSelector[i?"private":"public"]("setData",e);if("string"!=typeof t)throw new TypeError("The key must be a string.");return void 0!==r?s[t]=r:_t.removeData(e,t),e}setData(e,t,r=!1){return _t.setData(this,e,t,r)}static hasData(e,t,r=!1){if("string"!=typeof t)throw new TypeError("The key must be a string.");const i=_t._dataSelector[r?"private":"public"]("hasData",e);return Object.prototype.hasOwnProperty.call(i,t)}hasData(e,t=!1){return _t.hasData(this,e,t)}static removeData(e,t,r=!1){if("string"!=typeof t)throw new TypeError("The key must be a string.");return delete _t._dataSelector[r?"private":"public"]("removeData",e)[t]}removeData(e,t=!1){return _t.removeData(this,e,t)}static _getSibling(e,t,r){let i=_t._preNodeElemWithNull(e,r);for(;i&&(i=i[t])&&1!==i.nodeType;);return i instanceof Node?i:null}static _getSiblings(e,t){let r=e;const i=[];for(;r;r=r.nextSibling)1===r.nodeType&&r!==t&&i.push(r);return i}static domDir(e,t,r,i="domDir"){if("string"!=typeof t)throw new TypeError('The "direction" must be a string.');let s=_t._preNodeElemWithNull(e,i);const n=[];for(;s&&(s=s[t]);)if(1===s.nodeType){if(r&&("string"==typeof r?s.matches(r):s===r))break;n.push(s)}return n}static parent(e){let t=_t._preNodeElemWithNull(e,"parent");const r=t?t.parentNode:null;return r&&11!==r.nodeType?r:null}parent(){return _t.parent(this)}static parents(e,t){return _t.domDir(e,"parentNode",t,"parents")}parents(e){return _t.parents(this,e)}static next(e){return _t._getSibling(e,"nextSibling","next")}next(){return _t.next(this)}static prev(e){return _t._getSibling(e,"previousSibling","prev")}prev(){return _t.prev(this)}static nextAll(e){return _t.domDir(e,"nextSibling",void 0,"nextAll")}nextAll(){return _t.nextAll(this)}static prevAll(e){return _t.domDir(e,"previousSibling",void 0,"prevAll")}prevAll(){return _t.prevAll(this)}static nextUntil(e,t){return _t.domDir(e,"nextSibling",t,"nextUtil")}nextUntil(e){return _t.nextUntil(this,e)}static prevUntil(e,t){return _t.domDir(e,"previousSibling",t,"prevUtil")}prevUntil(e){return _t.prevUntil(this,e)}static siblings(e){const t=_t._preNodeElemWithNull(e,"siblings");return _t._getSiblings(t&&t.parentNode?t.parentNode.firstChild:null,t)}siblings(){return _t.siblings(this)}static children(e){const t=_t._preNodeElemWithNull(e,"children");return _t._getSiblings(t?t.firstChild:null)}children(){return _t.children(this)}static contents(e){const t=_t._preNodeElemWithNull(e,"contents");return t instanceof HTMLIFrameElement&&null!=t.contentDocument&&Object.getPrototypeOf(t.contentDocument)?[t.contentDocument]:t instanceof HTMLTemplateElement?Array.from((t.content||t).childNodes):t?Array.from(t.childNodes):[]}contents(){return _t.contents(this)}static clone(e,t=!0){if("boolean"!=typeof t)throw new TypeError('The "deep" must be a boolean.');return _t._preNodeElems(e,"clone").map(e=>e.cloneNode(t))}clone(e){return _t.clone(this,e)[0]}static _appendChecker(e,...t){const r=[];for(const i of t)if(null!=i&&!1!==i)if("string"!=typeof i&&"number"!=typeof i)if(i instanceof Node||i instanceof _t)r.push(..._t._preNodeElems(i,e));else if(Array.isArray(i))r.push(..._t._appendChecker(e,...i));else for(const t in i){const s=i[t];r.push(..._t._appendChecker(e,s))}else r.push(i);return r}static append(e,...t){return _t._preElem(e,"append").append(..._t._appendChecker("append",...t)),e}append(...e){return _t.append(this,...e)}static prepend(e,...t){return _t._preElem(e,"prepend").prepend(..._t._appendChecker("prepend",...t)),e}prepend(...e){return _t.prepend(this,...e)}static before(e,...t){return _t._preElem(e,"before").before(..._t._appendChecker("before",...t)),e}before(...e){return _t.before(this,...e)}static after(e,...t){return _t._preElem(e,"after").after(..._t._appendChecker("after",...t)),e}after(...e){return _t.after(this,...e)}static replaceWith(e,...t){return _t._preElem(e,"replaceWith").replaceWith(..._t._appendChecker("replaceWith",...t)),e}replaceWith(...e){return _t.replaceWith(this,...e)}static appendTo(e,t){const r=_t._preNodeElems(e,"appendTo"),i=_t._preNodeElems(t,"appendTo");return i.forEach((e,t)=>{r.forEach(r=>e.appendChild(t===i.length-1?r:r.cloneNode(!0)))}),e}appendTo(e){return _t.appendTo(this,e)}static prependTo(e,t){const r=_t._preElems(e,"prependTo"),i=_t._preElems(t,"prependTo");return i.forEach((e,t)=>{r.slice().reverse().forEach(r=>e.prepend(t===i.length-1?r:r.cloneNode(!0)))}),e}prependTo(e){return _t.prependTo(this,e)}static insertBefore(e,t,r=null){const i=_t._preNodeElem(e,"insertBefore"),s=_t._preNodeElem(t,"insertBefore"),n=_t._preNodeElemWithNull(r,"insertBefore");if(!s.parentNode)throw new Error("The target element has no parent node to insert before.");return s.parentNode.insertBefore(i,n||s),e}insertBefore(e,t){return _t.insertBefore(this,e,t)}static insertAfter(e,t,r=null){const i=_t._preNodeElem(e,"insertAfter"),s=_t._preNodeElem(t,"insertBefore"),n=_t._preNodeElemWithNull(r,"insertBefore");if(!s.parentNode)throw new Error("The target element has no parent node to insert after.");return s.parentNode.insertBefore(i,n||s.nextSibling),e}insertAfter(e,t){return _t.insertAfter(this,e,t)}static replaceAll(e,t){const r=_t._preNodeElems(e,"replaceAll"),i=_t._preNodeElems(t,"replaceAll");return i.forEach((e,t)=>{const s=e.parentNode;r.forEach(r=>{s&&s.replaceChild(t===i.length-1?r:r.cloneNode(!0),e)})}),e}replaceAll(e){return _t.replaceAll(this,e)}#J;get size(){return this.#J.length}static _elCheck(e){for(const t of e)if(!(t instanceof Element||t instanceof Window||t instanceof Document||t instanceof Text))throw new Error("[TinyHtml] Invalid Target in constructor.")}add(e){return new _t([...this.#J,..._t._selector(e)])}static _selector(e){if(e instanceof _t)throw new Error("[TinyHtml] You are trying to put a TinyHtml inside another TinyHtml in constructor.");const t=e=>Array.from(new Set(e)),r="string"!=typeof e?e:document.querySelectorAll(e);if(Array.isArray(r))return _t._elCheck(r),t(r);if(r instanceof NodeList||r instanceof HTMLCollection){const e=[...r];return _t._elCheck(e),t(e)}{const e=[r];return _t._elCheck(e),t(e)}}constructor(e){this.#J=_t._selector(e),this.#se=_t.#ne}static isWindow(e){return null!=e&&e===e.window}static css(e){const t=_t._preElem(e,"css");return window.getComputedStyle(t)}css(){return _t.css(this)}static cssString(e,t){const r=_t._preElem(e,"cssString");if("string"!=typeof t)throw new TypeError("The prop must be a string.");const i=window.getComputedStyle(r)[t];return"string"==typeof i?i:"number"==typeof i?i.toString():null}cssString(e){return _t.cssString(this,e)}static cssList(e,t){const r=_t._preElem(e,"cssList");if(!Array.isArray(t))throw new TypeError("The prop must be an array of strings.");const i=window.getComputedStyle(r),s={};for(const e of t)void 0!==e&&(s[e]=i.getPropertyValue(e));return s}cssList(e){return _t.cssList(this,e)}static cssFloat(e,t){const r=_t._preElem(e,"cssFloat");if("string"!=typeof t)throw new TypeError("The prop must be a string.");const i=window.getComputedStyle(r)[t];return parseFloat(i)||0}cssFloat(e){return _t.cssFloat(this,e)}static cssFloats(e,t){const r=_t._preElem(e,"cssFloats");if(!Array.isArray(t))throw new TypeError("The prop must be an array of strings.");const i=window.getComputedStyle(r),s={};for(const e of t)s[e]=parseFloat(i[e])||0;return s}cssFloats(e){return _t.cssFloats(this,e)}static#oe={alignContent:"align-content",alignItems:"align-items",alignSelf:"align-self",animationDelay:"animation-delay",animationDirection:"animation-direction",animationDuration:"animation-duration",animationFillMode:"animation-fill-mode",animationIterationCount:"animation-iteration-count",animationName:"animation-name",animationPlayState:"animation-play-state",animationTimingFunction:"animation-timing-function",backfaceVisibility:"backface-visibility",backgroundAttachment:"background-attachment",backgroundBlendMode:"background-blend-mode",backgroundClip:"background-clip",backgroundColor:"background-color",backgroundImage:"background-image",backgroundOrigin:"background-origin",backgroundPosition:"background-position",backgroundRepeat:"background-repeat",backgroundSize:"background-size",borderBottom:"border-bottom",borderBottomColor:"border-bottom-color",borderBottomLeftRadius:"border-bottom-left-radius",borderBottomRightRadius:"border-bottom-right-radius",borderBottomStyle:"border-bottom-style",borderBottomWidth:"border-bottom-width",borderCollapse:"border-collapse",borderColor:"border-color",borderImage:"border-image",borderImageOutset:"border-image-outset",borderImageRepeat:"border-image-repeat",borderImageSlice:"border-image-slice",borderImageSource:"border-image-source",borderImageWidth:"border-image-width",borderLeft:"border-left",borderLeftColor:"border-left-color",borderLeftStyle:"border-left-style",borderLeftWidth:"border-left-width",borderRadius:"border-radius",borderRight:"border-right",borderRightColor:"border-right-color",borderRightStyle:"border-right-style",borderRightWidth:"border-right-width",borderSpacing:"border-spacing",borderStyle:"border-style",borderTop:"border-top",borderTopColor:"border-top-color",borderTopLeftRadius:"border-top-left-radius",borderTopRightRadius:"border-top-right-radius",borderTopStyle:"border-top-style",borderTopWidth:"border-top-width",borderWidth:"border-width",boxDecorationBreak:"box-decoration-break",boxShadow:"box-shadow",boxSizing:"box-sizing",breakAfter:"break-after",breakBefore:"break-before",breakInside:"break-inside",captionSide:"caption-side",caretColor:"caret-color",clipPath:"clip-path",columnCount:"column-count",columnFill:"column-fill",columnGap:"column-gap",columnRule:"column-rule",columnRuleColor:"column-rule-color",columnRuleStyle:"column-rule-style",columnRuleWidth:"column-rule-width",columnSpan:"column-span",columnWidth:"column-width",counterIncrement:"counter-increment",counterReset:"counter-reset",emptyCells:"empty-cells",flexBasis:"flex-basis",flexDirection:"flex-direction",flexFlow:"flex-flow",flexGrow:"flex-grow",flexShrink:"flex-shrink",flexWrap:"flex-wrap",fontFamily:"font-family",fontFeatureSettings:"font-feature-settings",fontKerning:"font-kerning",fontLanguageOverride:"font-language-override",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontSynthesis:"font-synthesis",fontVariant:"font-variant",fontVariantAlternates:"font-variant-alternates",fontVariantCaps:"font-variant-caps",fontVariantEastAsian:"font-variant-east-asian",fontVariantLigatures:"font-variant-ligatures",fontVariantNumeric:"font-variant-numeric",fontVariantPosition:"font-variant-position",fontWeight:"font-weight",gridArea:"grid-area",gridAutoColumns:"grid-auto-columns",gridAutoFlow:"grid-auto-flow",gridAutoRows:"grid-auto-rows",gridColumn:"grid-column",gridColumnEnd:"grid-column-end",gridColumnGap:"grid-column-gap",gridColumnStart:"grid-column-start",gridGap:"grid-gap",gridRow:"grid-row",gridRowEnd:"grid-row-end",gridRowGap:"grid-row-gap",gridRowStart:"grid-row-start",gridTemplate:"grid-template",gridTemplateAreas:"grid-template-areas",gridTemplateColumns:"grid-template-columns",gridTemplateRows:"grid-template-rows",imageRendering:"image-rendering",justifyContent:"justify-content",letterSpacing:"letter-spacing",lineBreak:"line-break",lineHeight:"line-height",listStyle:"list-style",listStyleImage:"list-style-image",listStylePosition:"list-style-position",listStyleType:"list-style-type",marginBottom:"margin-bottom",marginLeft:"margin-left",marginRight:"margin-right",marginTop:"margin-top",maskClip:"mask-clip",maskComposite:"mask-composite",maskImage:"mask-image",maskMode:"mask-mode",maskOrigin:"mask-origin",maskPosition:"mask-position",maskRepeat:"mask-repeat",maskSize:"mask-size",maskType:"mask-type",maxHeight:"max-height",maxWidth:"max-width",minHeight:"min-height",minWidth:"min-width",mixBlendMode:"mix-blend-mode",objectFit:"object-fit",objectPosition:"object-position",offsetAnchor:"offset-anchor",offsetDistance:"offset-distance",offsetPath:"offset-path",offsetRotate:"offset-rotate",outlineColor:"outline-color",outlineOffset:"outline-offset",outlineStyle:"outline-style",outlineWidth:"outline-width",overflowAnchor:"overflow-anchor",overflowWrap:"overflow-wrap",overflowX:"overflow-x",overflowY:"overflow-y",paddingBottom:"padding-bottom",paddingLeft:"padding-left",paddingRight:"padding-right",paddingTop:"padding-top",pageBreakAfter:"page-break-after",pageBreakBefore:"page-break-before",pageBreakInside:"page-break-inside",perspectiveOrigin:"perspective-origin",placeContent:"place-content",placeItems:"place-items",placeSelf:"place-self",pointerEvents:"pointer-events",rowGap:"row-gap",scrollBehavior:"scroll-behavior",scrollMargin:"scroll-margin",scrollMarginBlock:"scroll-margin-block",scrollMarginBlockEnd:"scroll-margin-block-end",scrollMarginBlockStart:"scroll-margin-block-start",scrollMarginBottom:"scroll-margin-bottom",scrollMarginInline:"scroll-margin-inline",scrollMarginInlineEnd:"scroll-margin-inline-end",scrollMarginInlineStart:"scroll-margin-inline-start",scrollMarginLeft:"scroll-margin-left",scrollMarginRight:"scroll-margin-right",scrollMarginTop:"scroll-margin-top",scrollPadding:"scroll-padding",scrollPaddingBlock:"scroll-padding-block",scrollPaddingBlockEnd:"scroll-padding-block-end",scrollPaddingBlockStart:"scroll-padding-block-start",scrollPaddingBottom:"scroll-padding-bottom",scrollPaddingInline:"scroll-padding-inline",scrollPaddingInlineEnd:"scroll-padding-inline-end",scrollPaddingInlineStart:"scroll-padding-inline-start",scrollPaddingLeft:"scroll-padding-left",scrollPaddingRight:"scroll-padding-right",scrollPaddingTop:"scroll-padding-top",scrollSnapAlign:"scroll-snap-align",scrollSnapStop:"scroll-snap-stop",scrollSnapType:"scroll-snap-type",shapeImageThreshold:"shape-image-threshold",shapeMargin:"shape-margin",shapeOutside:"shape-outside",tabSize:"tab-size",tableLayout:"table-layout",textAlign:"text-align",textAlignLast:"text-align-last",textCombineUpright:"text-combine-upright",textDecoration:"text-decoration",textDecorationColor:"text-decoration-color",textDecorationLine:"text-decoration-line",textDecorationStyle:"text-decoration-style",textIndent:"text-indent",textJustify:"text-justify",textOrientation:"text-orientation",textOverflow:"text-overflow",textShadow:"text-shadow",textTransform:"text-transform",transformBox:"transform-box",transformOrigin:"transform-origin",transformStyle:"transform-style",transitionDelay:"transition-delay",transitionDuration:"transition-duration",transitionProperty:"transition-property",transitionTimingFunction:"transition-timing-function",unicodeBidi:"unicode-bidi",userSelect:"user-select",verticalAlign:"vertical-align",whiteSpace:"white-space",willChange:"will-change",wordBreak:"word-break",wordSpacing:"word-spacing",wordWrap:"word-wrap",writingMode:"writing-mode",zIndex:"z-index",WebkitTransform:"-webkit-transform",WebkitTransition:"-webkit-transition",WebkitBoxShadow:"-webkit-box-shadow",MozBoxShadow:"-moz-box-shadow",MozTransform:"-moz-transform",MozTransition:"-moz-transition",msTransform:"-ms-transform",msTransition:"-ms-transition"};static cssPropAliases=new Proxy(_t.#oe,{set:(e,t,r)=>(e[t]=r,_t.cssPropRevAliases[r]=t,!0)});static cssPropRevAliases=Object.fromEntries(Object.entries(_t.#oe).map(([e,t])=>[t,e]));static toStyleKc(e){return"string"==typeof _t.cssPropAliases[e]?_t.cssPropAliases[e]:e}static toStyleCc(e){return"string"==typeof _t.cssPropRevAliases[e]?_t.cssPropRevAliases[e]:e}static setStyle(e,t,r=null){return _t._preHtmlElems(e,"setStyle").forEach(e=>{if("object"==typeof t)for(const[r,i]of Object.entries(t))e.style.setProperty(_t.toStyleKc(r),"string"==typeof i?i:"number"==typeof i?`${i}px`:String(i));else e.style.setProperty(_t.toStyleKc(t),r)}),e}setStyle(e,t){return _t.setStyle(this,e,t)}static getStyle(e,t){return _t._preHtmlElem(e,"getStyle").style.getPropertyValue(_t.toStyleKc(t))}getStyle(e){return _t.getStyle(this,e)}static style(e,{camelCase:t=!1,rawAttr:r=!1}={}){if("boolean"!=typeof t)throw new TypeError('"camelCase" must be a boolean. Received: '+typeof t);if("boolean"!=typeof r)throw new TypeError('"rawAttr" must be a boolean. Received: '+typeof r);const i=_t._preHtmlElem(e,"style"),s={};if(r){const e=(i.getAttribute("style")||"").split(";");for(const r of e){const[e,i]=r.split(":");if(!e||!i)continue;const n=e.trim(),o=i.trim();s[t?_t.toStyleCc(n):n]=o}}else{const e=i.style;for(let r=0;r<e.length;r++){const i=e[r],n=e.getPropertyValue(i);s[t?_t.toStyleCc(i):i]=n}}return s}style(e){return _t.style(this,e)}static removeStyle(e,t){return _t._preHtmlElems(e,"removeStyle").forEach(e=>{if(Array.isArray(t))for(const r of t)e.style.removeProperty(_t.toStyleKc(r));else e.style.removeProperty(_t.toStyleKc(t))}),e}removeStyle(e){return _t.removeStyle(this,e)}static toggleStyle(e,t,r,i){return _t._preHtmlElems(e,"toggleStyle").forEach(e=>{const s=_t.getStyle(e,t).trim()===_t.toStyleKc(r)?i:r;_t.setStyle(e,t,s)}),e}toggleStyle(e,t,r){return _t.toggleStyle(this,e,t,r)}static clearStyle(e){return _t._preElems(e,"clearStyle").forEach(e=>e.removeAttribute("style")),e}clearStyle(){return _t.clearStyle(this)}static focus(e){return _t._preHtmlElem(e,"focus").focus(),e}focus(){return _t.focus(this)}static blur(e){return _t._preHtmlElem(e,"blur").blur(),e}blur(){return _t.blur(this)}static select(e){const t=_t._preHtmlElem(e,"select");if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement))throw new Error("Element must be an <input> or <textarea> to use select().");return t.select(),e}select(){return _t.select(this)}static boolCheck(e){return void 0!==e&&("true"===e||"1"===e||!0===e||"on"===e||"number"==typeof e&&e>0)}static setWinScrollTop(e){if("number"!=typeof e)throw new TypeError("The value must be a number.");_t.setScrollTop(window,e)}static setWinScrollLeft(e){if("number"!=typeof e)throw new TypeError("The value must be a number.");_t.setScrollLeft(window,e)}static winScrollTop(){return window.scrollY||document.documentElement.scrollTop}static winScrollLeft(){return window.scrollX||document.documentElement.scrollLeft}static winInnerHeight(){return window.innerHeight||document.documentElement.clientHeight}static winInnerWidth(){return window.innerWidth||document.documentElement.clientWidth}static isPageTop(){return 0===window.scrollY}static isPageBottom(){return window.innerHeight+window.scrollY>=document.body.offsetHeight}static getDimension(e,t,r="content"){const i=_t._preElemAndWinAndDoc(e,"getDimension");if("string"!=typeof t)throw new TypeError("The type must be a string.");if("string"!=typeof r)throw new TypeError("The extra must be a string.");const s="width"===t?"Width":"Height";if(_t.isWindow(i))return"margin"===r?i["inner"+s]:i.document.documentElement["client"+s];const n=i;if(9===n.nodeType){const e=n.documentElement;return Math.max(n.body["scroll"+s],e["scroll"+s],n.body["offset"+s],e["offset"+s],e["client"+s])}let o=n.getBoundingClientRect()[t];function a(e){return"width"===t?_t.cssFloat(n,e+"Left")+_t.cssFloat(n,e+"Right"):_t.cssFloat(n,e+"Top")+_t.cssFloat(n,e+"Bottom")}switch(r){case"content":o-=a("padding"),o-=a("border");break;case"padding":o-=a("border");break;case"border":break;case"margin":o+=a("margin")}return o}getDimension(e,t){return _t.getDimension(this,e,t)}static setHeight(e,t){const r=_t._preHtmlElem(e,"setHeight");if("number"!=typeof t&&"string"!=typeof t)throw new TypeError("The value must be a string or number.");return r.style.height="number"==typeof t?`${t}px`:t,e}setHeight(e){return _t.setHeight(this,e)}set height(e){_t.setHeight(this,e)}static setWidth(e,t){const r=_t._preHtmlElem(e,"setWidth");if("number"!=typeof t&&"string"!=typeof t)throw new TypeError("The value must be a string or number.");return r.style.width="number"==typeof t?`${t}px`:t,e}setWidth(e){return _t.setWidth(this,e)}set width(e){_t.setWidth(this,e)}static height(e){const t=_t._preElemAndWinAndDoc(e,"height");return _t.getDimension(t,"height","content")}get height(){return _t.height(this)}static width(e){const t=_t._preElemAndWinAndDoc(e,"width");return _t.getDimension(t,"width","content")}get width(){return _t.width(this)}static innerHeight(e){const t=_t._preElemAndWinAndDoc(e,"innerHeight");return _t.getDimension(t,"height","padding")}innerHeight(){return _t.innerHeight(this)}static innerWidth(e){const t=_t._preElemAndWinAndDoc(e,"innerWidth");return _t.getDimension(t,"width","padding")}innerWidth(){return _t.innerWidth(this)}static outerHeight(e,t=!1){if("boolean"!=typeof t)throw new TypeError('The "includeMargin" must be a boolean.');const r=_t._preElemAndWinAndDoc(e,"outerHeight");return _t.getDimension(r,"height",t?"margin":"border")}outerHeight(e){return _t.outerHeight(this,e)}static outerWidth(e,t=!1){if("boolean"!=typeof t)throw new TypeError('The "includeMargin" must be a boolean.');const r=_t._preElemAndWinAndDoc(e,"outerWidth");return _t.getDimension(r,"width",t?"margin":"border")}outerWidth(e){return _t.outerWidth(this,e)}#se="";get mainDisplay(){return this.#se}set mainDisplay(e){if("string"!=typeof e)throw new TypeError("mainDisplay must be a string.");this.#se=e}static#ne="block";static get defaultDisplay(){return _t.#ne}static set defaultDisplay(e){if("string"!=typeof e)throw new TypeError("defaultDisplay must be a string.");_t.#ne=e}static getAnimateData(e,t){let r=Mt.get(e);return r||(r={},Mt.set(e,r)),r[t]}static setAnimateData(e,t,r){if(!(e instanceof HTMLElement))throw new TypeError("setAnimateData: el must be an HTMLElement.");if("string"!=typeof t)throw new TypeError("setAnimateData: where must be a string.");if("string"!=typeof r&&"number"!=typeof r)throw new TypeError("setAnimateData: value must be a string or number.");let i=Mt.get(e);i||(i={},Mt.set(e,i)),i[t]=r}static#ae=!0;static get cancelOldStyleFx(){return _t.#ae}static set cancelOldStyleFx(e){if("boolean"!=typeof e)throw new TypeError("Expected a boolean value.");_t.#ae=e}static#le={slow:{duration:600,easing:"ease"},fast:{duration:200,easing:"ease-out"},_default:{duration:400,easing:"linear"}};static get styleFxSpeeds(){const e={};for(const t in _t.#le){const r=_t.#le[t];e[t]="object"==typeof r?{...r}:r}return e}static set styleFxSpeeds(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleFxSpeeds must be an object.");for(const[t,r]of Object.entries(e))if("number"!=typeof r&&"object"!=typeof r)throw new TypeError(`styleFxSpeeds["${t}"] must be a number or KeyframeAnimationOptions.`);_t.#le={};for(const[t,r]of Object.entries(e))_t.setStyleFxSpeed(t,r)}static getStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');const t=_t.#le[e];return"object"==typeof t?{...t}:t}static setStyleFxSpeed(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("number"!=typeof t&&"object"!=typeof t)throw new TypeError("styleFxSpeed must be a number or KeyframeAnimationOptions");_t.#le[e]="object"==typeof t?{...t}:t}static deleteStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#le[e]}static hasStyleFxSpeed(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#le,e)}static#he=["Top","Right","Bottom","Left"];static#ue={slideDown:_t.genStyleFx("show"),slideUp:_t.genStyleFx("hide"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}};static get styleEffects(){return JSON.parse(JSON.stringify(_t.#ue))}static set styleEffects(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleEffects must be an object");for(const t in e)for(const[r,i]of Object.entries(e[t]))if(!("string"==typeof i||Array.isArray(i)&&i.every(e=>"string"==typeof e||"number"==typeof e)))throw new TypeError(`Invalid styleEffect["${r}"]`);_t.#ue={};for(const t in e)_t.setStyleEffect(t,e[t])}static getStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');const t=_t.#ue[e];return t?JSON.parse(JSON.stringify(t)):void 0}static setStyleEffect(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("styleEffect must be an object");const r={};for(const[e,i]of Object.entries(t))if("string"==typeof i)r[e]=i;else{if(!Array.isArray(i)||!i.every(e=>"string"==typeof e||"number"==typeof e))throw new TypeError(`Invalid styleEffect["${e}"]`);r[e]=[...i]}_t.#ue[e]=r}static deleteStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#ue[e]}static hasStyleEffect(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#ue,e)}static#ce={slideDown:"slideUp",slideUp:"slideDown",fadeIn:"fadeOut",fadeOut:"fadeIn",fadeTo:"fadeIn"};static get styleEffectInverse(){return{..._t.#ce}}static set styleEffectInverse(e){if("object"!=typeof e||null===e)throw new TypeError("styleEffectInverse must be an object.");for(const[t,r]of Object.entries(e))if("string"!=typeof r)throw new TypeError(`styleEffectInverse["${t}"] must be a string.`);_t.#ce={};for(const[t,r]of Object.entries(e))_t.setStyleEffectInverse(t,r)}static getStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#ce[e]||null}static setStyleEffectInverse(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("string"!=typeof t)throw new TypeError(`styleEffectInverse["${e}"] must be a string.`);_t.#ce[e]=t}static deleteStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#ce[e]}static hasStyleEffectInverse(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#ce,e)}static#de={slideDown:e=>e.height[0]===e.height[1]&&(!e.width||e.width[0]===e.width[1]),slideUp:e=>e.height[0]===e.height[1]&&(!e.width||e.width[0]===e.width[1]),fadeIn:e=>Number(e.opacity[0])===Number(e.opacity[1]),fadeOut:e=>Number(e.opacity[0])===Number(e.opacity[1])};static get styleEffectsRd(){return{..._t.#de}}static set styleEffectsRd(e){if("object"!=typeof e||null===e)throw new TypeError("styleEffectsRd must be an object.");for(const[t,r]of Object.entries(e))if("function"!=typeof r)throw new TypeError(`styleEffectsRd["${t}"] must be a function.`);_t.#de={};for(const[t,r]of Object.entries(e))_t.setStyleEffectRd(t,r)}static getStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#de[e]||null}static setStyleEffectRd(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("function"!=typeof t)throw new TypeError(`styleEffectsRd["${e}"] must be a function.`);_t.#de[e]=t}static deleteStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#de[e]}static hasStyleEffectRd(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#de,e)}static#me={show:(e,t,r,i)=>{if("height"===r||"width"===r){const s=_t.getAnimateData(e,`orig${r}`)||e.scrollHeight+"px";_t.setAnimateData(e,`orig${r}`,s);const n=i[r];t[r]=[n,s]}else if(r.startsWith("margin")||r.startsWith("padding")){const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=["0px",s]}else if("opacity"===r){const e=i.opacity;t[r]=[e,1]}else{const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[s,i[r]||1]}},hide:(e,t,r,i)=>{if("height"===r||"width"===r){const s=_t.getAnimateData(e,`orig${r}`)||i[r];_t.setAnimateData(e,`orig${r}`,s);const n=i[r];t[r]=[n,0]}else if(r.startsWith("margin")||r.startsWith("padding")){const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[i[r],"0px"]}else if("opacity"===r){const e=i.opacity;t[r]=[e,0]}else{const s=_t.getAnimateData(e,r)||i[r];_t.setAnimateData(e,r,s),t[r]=[s,0]}}};static get styleEffectsProps(){return{..._t.#me}}static set styleEffectsProps(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("styleEffectsProps must be an object");for(const[t,r]of Object.entries(e))if("function"!=typeof r)throw new TypeError(`styleEffectsProps["${t}"] must be a function`);_t.#me={};for(const[t,r]of Object.entries(e))_t.setStyleEffectProp(t,r)}static getStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return _t.#me[e]||null}static setStyleEffectProp(e,t){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');if("function"!=typeof t)throw new TypeError(`styleEffectsProps["${e}"] must be a function`);_t.#me[e]=t}static deleteStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return delete _t.#me[e]}static hasStyleEffectProp(e){if("string"!=typeof e)throw new TypeError('The "name" parameter must be a string.');return Object.prototype.hasOwnProperty.call(_t.#me,e)}static genStyleFx(e,t=!1){if("string"!=typeof e)throw new TypeError("genStyleFx: type must be a string.");if("boolean"!=typeof t)throw new TypeError("genStyleFx: includeWidth must be a boolean.");let r,i=0;const s={height:e},n=t?1:0;for(;i<4;i+=2-n)r=_t.#he[i],s["margin"+r]=e,s["padding"+r]=e;return t&&(s.opacity=e,s.width=e),s}static applyStyleFx(e,t,r,i){if("string"!=typeof t)throw new TypeError("applyStyleFx: id must be a string.");if("object"!=typeof r||null===r)throw new TypeError("applyStyleFx: props must be a non-null object.");if(void 0!==i&&"number"!=typeof i&&"string"!=typeof i&&("object"!=typeof i||null===i))throw new TypeError("applyStyleFx: ops must be a number, string, KeyframeAnimationOptions, or undefined.");const s=new Map;return _t._preHtmlElems(e,"applyStyleFx").forEach(n=>{const o={};for(const[e,t]of Object.entries(r))if("string"==typeof t&&this.#me[t]){const r=getComputedStyle(n);this.#me[t](n,o,e,r)}else{if("object"!=typeof t)throw new TypeError(`applyStyleFx: invalid action for prop "${e}". Must be string or array.`);o[e]=t}if("function"==typeof _t.#de[t]&&_t.#de[t](o))return void s.set(n,null);const a=[],l=o[Object.keys(o)[0]].length;for(let e=0;e<l;e++){const t={};for(const r in o)t[r]=o[r][e];a.push(t)}s.set(n,_t.animate(e,a,i,t)[0])}),s}applyStyleFx(e,t,r){return _t.applyStyleFx(this,e,t,r)}static getCurrentAnimationId(e){if(!(e instanceof HTMLElement))throw new TypeError("Expected an HTMLElement.");return Lt.get(e)?.id??void 0}static animate(e,t,r=_t.#le._default,i=null,s=_t.#ae){const n="string"==typeof r?_t.#le[r]??void 0:"number"!=typeof r?{...r}:r;"object"==typeof n&&void 0===n.fill&&(n.fill="forwards");const o=[];return _t._preHtmlElems(e,"animate").forEach(e=>{if(s){const t=Lt.get(e);t&&t.animation.cancel()}const r=e.animate(t,n);o.push(r),Lt.set(e,{animation:r,id:i??""}),r.addEventListener("finish",()=>{Lt.get(e)?.animation===r&&Lt.delete(e)})}),o}animate(e,t,r,i){return _t.animate(this,e,t,r,i)}static stop(e){const t=[];return _t._preHtmlElems(e,"stop").forEach(e=>{const r=Lt.get(e);r?(r.animation.cancel(),Lt.delete(e),t.push(!0)):t.push(!1)}),t}stop(){return _t.stop(this)}static slideDown(e,t){return _t.applyStyleFx(e,"slideDown",this.#ue.slideDown,t??{duration:500,easing:"ease-out"})}slideDown(e){return _t.slideDown(this,e)}static slideUp(e,t){return _t.applyStyleFx(e,"slideUp",this.#ue.slideUp,t??{duration:500,easing:"ease-out"})}slideUp(e){return _t.slideUp(this,e)}static slideToggle(e,t){const r=_t._preHtmlElem(e,"slideToggle"),i=getComputedStyle(r),s=_t.getCurrentAnimationId(r),n="none"===i.display||0===r.offsetHeight;return("string"==typeof s?"slideUp"===s:n)?_t.slideDown(e,t):_t.slideUp(e,t)}slideToggle(e){return _t.slideToggle(this,e)}static fadeIn(e,t){return _t.applyStyleFx(e,"fadeIn",this.#ue.fadeIn,t)}fadeIn(e){return _t.fadeIn(this,e)}static fadeOut(e,t){return _t.applyStyleFx(e,"fadeOut",this.#ue.fadeOut,t)}fadeOut(e){return _t.fadeOut(this,e)}static fadeToggle(e,t){const r=_t._preHtmlElem(e,"fadeToggle"),i=getComputedStyle(r),s=_t.getCurrentAnimationId(r),n="0"===i.opacity||null===r.offsetParent;return("string"==typeof s?"fadeOut"===s:n)?_t.fadeIn(e,t):_t.fadeOut(e,t)}fadeToggle(e){return _t.fadeToggle(this,e)}static fadeTo(e,t,r,i=_t.#ne){if("number"!=typeof t||isNaN(t)||t<0||t>1)throw new TypeError("fadeTo: opacity must be a number between 0 and 1.");if(void 0!==r&&"number"!=typeof r&&"string"!=typeof r&&("object"!=typeof r||null===r))throw new TypeError("fadeTo: ops must be a number, string, KeyframeAnimationOptions, or undefined.");const s=new Map;return _t._preHtmlElems(e,"fadeTo").forEach(n=>{const o=getComputedStyle(n);if(!(e instanceof Element&&(e.offsetWidth||e.offsetHeight||e.getClientRects().length))){const e=_t.getAnimateData(n,"origdisplay");n.style.display="string"==typeof e?e:i}const a=[o.opacity,t].map(e=>({opacity:e}));s.set(n,_t.animate(n,a,r,"fadeTo")[0])}),s}fadeTo(e,t,r=this.#se){return _t.fadeTo(this,e,t,r)}static offset(e){const t=_t._preElem(e,"offset").getBoundingClientRect(),r=window.scrollY||document.documentElement.scrollTop,i=window.scrollX||document.documentElement.scrollLeft;return{top:t.top+r,left:t.left+i}}offset(){return _t.offset(this)}static position(e){const t=_t._preHtmlElem(e,"position");let r,i,s={top:0,left:0};if("fixed"===window.getComputedStyle(t).position)i=t.getBoundingClientRect();else{i=_t.offset(t),r=t.offsetParent||document.documentElement;const{position:e}=window.getComputedStyle(r);for(;r instanceof HTMLElement&&(r===document.body||r===document.documentElement)&&"static"===e;)r=r.parentNode;if(r instanceof HTMLElement&&r!==t&&1===r.nodeType){const{borderTopWidth:e,borderLeftWidth:t}=_t.cssFloats(r,["borderTopWidth","borderLeftWidth"]);s=_t.offset(r),s.top+=e,s.left+=t}}return{top:i.top-s.top-_t.cssFloat(t,"marginTop"),left:i.left-s.left-_t.cssFloat(t,"marginLeft")}}position(){return _t.position(this)}static offsetParent(e){let t=_t._preHtmlElem(e,"offsetParent").offsetParent;for(;t instanceof HTMLElement&&"static"===window.getComputedStyle(t).position;)t=t.offsetParent;return t instanceof HTMLElement?t:document.documentElement}offsetParent(){return _t.offsetParent(this)}static scrollTop(e){const t=_t._preElemAndWindow(e,"scrollTop");return _t.isWindow(t)?t.pageYOffset:9===t.nodeType?t.defaultView.pageYOffset:t.scrollTop}scrollTop(){return _t.scrollTop(this)}static scrollLeft(e){const t=_t._preElemAndWindow(e,"scrollLeft");return _t.isWindow(t)?t.pageXOffset:9===t.nodeType?t.defaultView.pageXOffset:t.scrollLeft}scrollLeft(){return _t.scrollLeft(this)}static easings={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:(4-2*e)*e-1,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1};static scrollToXY(e,{targetX:t,targetY:r,duration:i,easing:s,onAnimation:n}={}){if(void 0!==t&&"number"!=typeof t)throw new TypeError("`targetX` must be a number if provided.");if(void 0!==r&&"number"!=typeof r)throw new TypeError("`targetY` must be a number if provided.");if(void 0!==i&&"number"!=typeof i)throw new TypeError("`duration` must be a number if provided.");if(void 0!==s&&"string"!=typeof s)throw new TypeError("`easing` must be a string if provided.");if(void 0!==s&&"function"!=typeof _t.easings[s])throw new TypeError(`Unknown easing function: "${s}".`);if(void 0!==n&&"function"!=typeof n)throw new TypeError("`onAnimation` must be a function if provided.");const o=(e,t,r,i)=>{if(e instanceof Window)window.scrollTo(t,r);else if(9===e.nodeType)e.defaultView.scrollTo(t,r);else{const i=e instanceof Window?window.scrollX:e.scrollLeft,s=e instanceof Window?window.scrollY:e.scrollTop;i!==t&&(e.scrollLeft=t),s!==r&&(e.scrollTop=r)}"function"==typeof n&&n({x:t,y:r,isComplete:i>=1,time:i})};return _t._preElemsAndWindow(e,"scrollToXY").forEach(e=>{const n=e instanceof Window?window.scrollX:e.scrollLeft,a=e instanceof Window?window.scrollY:e.scrollTop,l=t??n,h=r??a,u=l-n,c=h-a,d="string"==typeof s&&_t.easings[s]||null;if("number"!=typeof i||"function"!=typeof d)return o(e,l,h,1);const m=performance.now(),p=i??0;requestAnimationFrame(function t(r){if("function"!=typeof d)return;const i=Math.min(1,(r-m)/p),s=d(i);o(e,n+u*s,a+c*s,i),i<1&&requestAnimationFrame(t)})}),e}scrollToXY({targetX:e,targetY:t,duration:r,easing:i,onAnimation:s}={}){return _t.scrollToXY(this,{targetX:e,targetY:t,duration:r,easing:i,onAnimation:s})}static setScrollTop(e,t){if("number"!=typeof t)throw new TypeError("ScrollTop value must be a number.");return _t.scrollToXY(e,{targetY:t})}setScrollTop(e){return _t.setScrollTop(this,e)}static setScrollLeft(e,t){if("number"!=typeof t)throw new TypeError("ScrollLeft value must be a number.");return _t.scrollToXY(e,{targetX:t})}setScrollLeft(e){return _t.setScrollLeft(this,e)}static borderWidth(e){const t=_t._preElem(e,"borderWidth"),{borderLeftWidth:r,borderRightWidth:i,borderTopWidth:s,borderBottomWidth:n}=_t.cssFloats(t,["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}borderWidth(){return _t.borderWidth(this)}static border(e){const t=_t._preElem(e,"border"),{borderLeft:r,borderRight:i,borderTop:s,borderBottom:n}=_t.cssFloats(t,["borderLeft","borderRight","borderTop","borderBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}border(){return _t.border(this)}static margin(e){const t=_t._preElem(e,"margin"),{marginLeft:r,marginRight:i,marginTop:s,marginBottom:n}=_t.cssFloats(t,["marginLeft","marginRight","marginTop","marginBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}margin(){return _t.margin(this)}static padding(e){const t=_t._preElem(e,"padding"),{paddingLeft:r,paddingRight:i,paddingTop:s,paddingBottom:n}=_t.cssFloats(t,["paddingLeft","paddingRight","paddingTop","paddingBottom"]);return{x:r+i,y:s+n,left:r,right:i,top:s,bottom:n}}padding(){return _t.padding(this)}static#pe=!1;static get classCanWhitespace(){return this.#pe}static set classCanWhitespace(e){if("boolean"!=typeof e)throw new TypeError("classCanWhitespace must be a boolean");this.#pe=e}static addClass(e,...t){const r=[];for(const e of t)if(_t.#pe){const t=e.split(" ");for(const e of t)r.push(e)}else r.push(e);return _t._preElems(e,"addClass").forEach(e=>e.classList.add(...r)),e}addClass(...e){return _t.addClass(this,...e)}static removeClass(e,...t){const r=[];for(const e of t)if(_t.#pe){const t=e.split(" ");for(const e of t)r.push(e)}else r.push(e);return _t._preElems(e,"removeClass").forEach(e=>e.classList.remove(...r)),e}removeClass(...e){return _t.removeClass(this,...e)}static replaceClass(e,t,r){if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');if("string"!=typeof r)throw new TypeError('The "newToken" parameter must be a string.');const i=[];return _t._preElems(e,"replaceClass").forEach(e=>i.push(e.classList.replace(t,r))),i}replaceClass(e,t){return _t.replaceClass(this,e,t)[0]}static classItem(e,t){const r=_t._preElem(e,"classItem");if("number"!=typeof t)throw new TypeError('The "index" parameter must be a number.');return r.classList.item(t)}classItem(e){return _t.classItem(this,e)}static toggleClass(e,t,r){if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');if(void 0!==r&&"boolean"!=typeof r)throw new TypeError('The "force" parameter must be a boolean.');const i=[];return _t._preElems(e,"toggleClass").forEach(e=>i.push(e.classList.toggle(t,r))),i}toggleClass(e,t){return _t.toggleClass(this,e,t)[0]}static hasClass(e,t){const r=_t._preElem(e,"hasClass");if("string"!=typeof t)throw new TypeError('The "token" parameter must be a string.');return r.classList.contains(t)}hasClass(e){return _t.hasClass(this,e)}static classLength(e){return _t._preElem(e,"classLength").classList.length}classLength(){return _t.classLength(this)}static classList(e){return _t._preElem(e,"classList").classList.values().toArray()}classList(){return _t.classList(this)}static tagName(e){return _t._preElem(e,"tagName").tagName}tagName(){return _t.tagName(this)}static id(e){return _t._preElem(e,"id").id}get id(){return _t.id(this)}set id(e){_t.setAttr(this,"id",e)}static toBigInt(e){const t=_t._preElem(e,"toBigInt"),r=t.textContent?.trim();let i=null;try{i=BigInt(r??"")}catch{i=null}return i}toBigInt(){return _t.toBigInt(this)}static setBigInt(e,t){if("bigint"!=typeof t)throw new Error("Value is not a valid BigInt.");const r=t.toString();return _t._preElems(e,"setBigInt").forEach(e=>e.textContent=r),e}setBigInt(e){return _t.setBigInt(this,e)}static toDate(e){const t=_t._preElem(e,"toDate"),r=t.textContent?.trim();if(!r)return null;const i=new Date(r);return Number.isNaN(i.getTime())?null:i}toDate(){return _t.toDate(this)}static setDate(e,t){if(!(t instanceof Date)||Number.isNaN(t.getTime()))throw new Error("Value is not a valid Date.");const r=t.toISOString();return _t._preElems(e,"setDate").forEach(e=>e.textContent=r),e}setDate(e){return _t.setDate(this,e)}static toJson(e){const t=_t._preElem(e,"toJson"),r=t.textContent?.trim();if(!r)return null;try{return JSON.parse(r)}catch{return null}}toJson(){return _t.toJson(this)}static setJson(e,t,r,i){const s=JSON.stringify(t,r,i);return _t._preElems(e,"setJson").forEach(e=>e.textContent=s),e}setJson(e,t,r){return _t.setJson(this,e,t,r)}static toNumber(e){const t=_t._preElem(e,"toNumber");return"string"==typeof t.textContent?parseFloat(t.textContent.trim()):null}toNumber(){return _t.toNumber(this)}static setNumber(e,t){if("number"!=typeof t)throw new Error("Value is not a valid number.");const r=t.toString();return _t._preElems(e,"setNumber").forEach(e=>e.textContent=r),e}setNumber(e){return _t.setNumber(this,e)}static toBoolean(e){const t=_t._preElem(e,"toBoolean"),r=t.textContent?.trim();return null==r||"true"!==r&&"false"!==r?null:/^true$/i.test(r)}toBoolean(){return _t.toBoolean(this)}static setBoolean(e,t){if("boolean"!=typeof t)throw new Error("Value is not a valid boolean.");const r=t.toString();return _t._preElems(e,"setBoolean").forEach(e=>e.textContent=r),e}setBoolean(e){return _t.setBoolean(this,e)}static toString(e){const t=_t._preElem(e,"toString");return"string"==typeof t.textContent?t.textContent:null}toString(){return _t.toString(this)}static setString(e,t){if("string"!=typeof t)throw new Error("Value is not a valid string.");return _t._preElems(e,"setString").forEach(e=>e.textContent=t),e}setString(e){return _t.setString(this,e)}static text(e){return _t._preElem(e,"text").textContent}text(){return _t.text(this)}static setText(e,t){const r=null!=t?String(t):"";return _t._preElems(e,"setText").forEach(e=>e.textContent=r),e}setText(e){return _t.setText(this,e)}static empty(e){return _t._preElems(e,"empty").forEach(e=>e.textContent=""),e}empty(){return _t.empty(this)}static html(e,t){return _t._preElem(e,"html").getHTML(t)}html(e){return _t.html(this,e)}static setHtml(e,t){if("string"!=typeof t)throw new Error("Value is not a valid string.");return _t._preElems(e,"setHtml").forEach(e=>e.innerHTML=t),e}setHtml(e){return _t.setHtml(this,e)}static _valHooks={option:{get:e=>{const t=e.getAttribute("value");return null!=t?t:e.textContent}},select:{get:e=>{const t=e.options,r=e.selectedIndex,i="select-one"===e.type,s=i?r+1:t.length,n=[];let o=r<0?s:i?r:0;for(;o<s;o++){const e=t[o],s=e.parentNode;if((e.selected||o===r)&&!e.disabled&&(!s||!s.disabled||"OPTGROUP"!==s.tagName)){const t=_t._valHooks.option.get(e);if(i)return t;n.push(t)}}return n},set:(e,t)=>{const r=e.options,i=Array.isArray(t)?t.map(String):[String(t)];let s=!1;for(let e=0;e<r.length;e++){const t=r[e],n=_t._valHooks.option.get(t);"string"==typeof n&&(t.selected=i.includes(n))&&(s=!0)}return s||(e.selectedIndex=-1),i}},radio:{get:e=>e.checked?"on":"off",set(e,t){if("boolean"==typeof t){const r=e.closest("label");return t&&r&&r.querySelectorAll('input[type="radio"]').forEach(t=>{t instanceof HTMLInputElement&&t!==e&&(t.checked=!1)}),e.checked=t,t}}},checkbox:{get:e=>e.checked?"on":"off",set(e,t){if("boolean"==typeof t)return e.checked=t,t}}};static setVal(e,t){return _t._preInputElems(e,"setVal").forEach(e=>{if(1!==e.nodeType)return;let r="function"==typeof t?t(e,_t.val(e)):t;null==r?r="":"number"==typeof r?r=String(r):Array.isArray(r)&&(r=((e,t)=>{const r=[];for(let i=0;i<e.length;i++)r.push(t(e[i]));return r})(r,e=>null==e?"":String(e)));const i=_t._valHooks[e.type]||_t._valHooks[e.nodeName.toLowerCase()];if(!i||"function"!=typeof i.set||void 0===i.set(e,r,"value")){if("string"!=typeof r&&"boolean"!=typeof r)throw new Error(`Invalid setValue "${typeof r}" value.`);"string"==typeof r&&(e.value=r)}}),e}setVal(e){return _t.setVal(this,e)}static _valTypes={string:e=>e.value,date:e=>e.valueAsDate,number:e=>e.valueAsNumber};static _getValByType(e,t,r){if("string"!=typeof t)throw new TypeError('The "type" must be a string.');if("string"!=typeof r)throw new TypeError('The "where" must be a string.');if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement))throw new Error(`Provided element is not an HTMLInputElement in ${r}().`);if("function"!=typeof _t._valTypes[t])throw new Error(`No handler found for type "${t}" in ${r}().`);return _t._valTypes[t](e)}static _val(e,t,r){const i=_t._preInputElem(e,t),s=_t._valHooks[i.type]||_t._valHooks[i.nodeName.toLowerCase()];if(s&&"function"==typeof s.get){const e=s.get(i,"value",r);if(void 0!==e)return"string"==typeof e?e.replace(/\r/g,""):e}return _t._getValByType(i,r,t)}_val(e,t){return _t._val(this,e,t)}static val(e){return _t._val(e,"val","string")}val(){return _t.val(this)}static valTxt(e){const t=_t._val(e,"valTxt","string");if("string"!=typeof t&&null!==t)throw new Error("Value is not a valid string.");return null==t?"":"string"==typeof t?t.replace(/\r/g,""):t}valTxt(){return _t.valTxt(this)}static _valArr(e,t,r){const i=_t._val(e,t,r);if(!Array.isArray(i))throw new Error(`Value expected an array but got ${typeof i}.`);return i}_valArr(e,t){return _t._valArr(this,e,t)}static valArr(e){return _t._valArr(e,"valArr","string")}valArr(){return _t.valArr(this)}static valNb(e){if(!(_t._preInputElem(e,"valNb")instanceof HTMLInputElement))throw new Error("Element must be an input element.");const t=_t._val(e,"valNb","number");if(Number.isNaN(t))throw new Error("Value is not a valid number.");return t}valNb(){return _t.valNb(this)}static valDate(e){if(!(_t._preInputElem(e,"valDate")instanceof HTMLInputElement))throw new Error("Element must be an input element.");const t=_t._val(e,"valDate","date");if(!(t instanceof Date))throw new Error("Value is not a valid date.");return t}valDate(){return _t.valDate(this)}static valBool(e){const t=_t._preInputElem(e,"valBool");if(!(t instanceof HTMLInputElement))throw new Error("Element must be an input element.");return"on"===_t.val(t)}valBool(){return _t.valBool(this)}static listenForPaste(e,{onFilePaste:t,onTextPaste:r}={}){if(void 0!==t&&"function"!=typeof t)throw new TypeError("onFilePaste must be a function.");if(void 0!==r&&"function"!=typeof r)throw new TypeError("onTextPaste must be a function.");const i=e=>{if(!(e instanceof ClipboardEvent))return;const i=e.clipboardData?.items||[];for(const e of i)if("file"===e.kind){if("function"==typeof t){const r=e.getAsFile();r&&t(e,r)}}else"string"===e.kind&&"function"==typeof r&&e.getAsString(t=>r(e,t))};return _t._preElemsWithDoc(e,"listenForPaste").forEach(e=>_t.on(e,"paste",i)),i}listenForPaste({onFilePaste:e,onTextPaste:t}={}){return _t.listenForPaste(this,{onFilePaste:e,onTextPaste:t})}static hasEventListener(e,t){const r=_t._preEventTargetElem(e,"hasEventListener");if(!kt.has(r))return!1;const i=kt.get(r);return!!(i&&Array.isArray(i[t])&&i[t].length>0)}hasEventListener(e){return _t.hasEventListener(this,e)}static hasExactEventListener(e,t,r){const i=_t._preEventTargetElem(e,"hasExactEventListener");if("function"!=typeof r)throw new TypeError('The "handler" must be a function.');if(!kt.has(i))return!1;const s=kt.get(i);return!(!s||!Array.isArray(s[t]))&&s[t].some(e=>e.handler===r)}hasExactEventListener(e,t){return _t.hasExactEventListener(this,e,t)}static hover(e,t,r,i){return _t.on(e,"mouseenter",t,i),_t.on(e,"mouseleave",r||t,i),e}hover(e,t,r){return _t.hover(this,e,t,r)}static on(e,t,r,i){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"on").forEach(e=>{e.addEventListener(s,r,i),kt.has(e)||kt.set(e,{});const t=kt.get(e);t&&(Array.isArray(t[s])||(t[s]=[]),t[s].push({handler:r,options:i}))})}return e}on(e,t,r){return _t.on(this,e,t,r)}static once(e,t,r,i={}){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"once").forEach(e=>{const t=i=>{_t.off(e,s,t),"function"==typeof r&&r(i)};_t.on(e,s,t,"boolean"==typeof i?i:{...i,once:!0})})}return e}once(e,t,r={}){return _t.once(this,e,t,r)}static off(e,t,r,i){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const s of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof s)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"off").forEach(e=>{e.removeEventListener(s,r,i);const t=kt.get(e);t&&t[s]&&(t[s]=t[s].filter(e=>e.handler!==r),0===t[s].length&&delete t[s])})}return e}off(e,t,r){return _t.off(this,e,t,r)}static offAll(e,t){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const r of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof r)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"offAll").forEach(e=>{const t=kt.get(e);if(t&&t[r]){for(const i of t[r])e.removeEventListener(r,i.handler,i.options);delete t[r]}})}return e}offAll(e){return _t.offAll(this,e)}static offAllTypes(e,t=null){if(null!==t&&"function"!=typeof t)throw new TypeError('The "filterFn" must be a function.');return _t._preEventTargetElems(e,"offAllTypes").forEach(e=>{const r=kt.get(e);if(r){for(const i in r)for(const s of r[i])("function"!=typeof t||t(s.handler,i))&&e.removeEventListener(i,s.handler,s.options);kt.delete(e)}}),e}offAllTypes(e=null){return _t.offAllTypes(this,e)}static trigger(e,t,r={}){if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("The events must be a string or array of strings.");for(const i of Array.isArray(t)?Array.from(new Set(t)):[t]){if("string"!=typeof i)throw new TypeError("The event name must be a string.");_t._preEventTargetElems(e,"trigger").forEach(e=>{const t=r instanceof Event||r instanceof CustomEvent?r:new CustomEvent(i,{bubbles:!0,cancelable:!0,detail:r});e.dispatchEvent(t)})}return e}trigger(e,t={}){return _t.trigger(this,e,t)}static#fe={for:"htmlFor",class:"className"};static propFix=new Proxy(_t.#fe,{set:(e,t,r)=>(e[t]=r,_t.attrFix[r]=t,!0)});static attrFix=Object.fromEntries(Object.entries(_t.#fe).map(([e,t])=>[t,e]));static getPropName(e){return"string"==typeof _t.propFix[e]?_t.propFix[e]:e}static getAttrName(e){return"string"==typeof _t.attrFix[e]?_t.attrFix[e]:e}static attrBigInt(e,t){const r=_t._preElem(e,"attrBigInt").getAttribute(_t.getAttrName(t));if(null==r)return null;try{return BigInt(r)}catch{return null}}attrBigInt(e){return _t.attrBigInt(this,e)}static setAttrBigInt(e,t,r){if("bigint"!=typeof r)throw new Error("Value is not a valid BigInt.");return _t.setAttr(e,t,r.toString())}setAttrBigInt(e,t){return _t.setAttrBigInt(this,e,t)}static attrDate(e,t){const r=_t._preElem(e,"attrDate").getAttribute(_t.getAttrName(t));if(!r)return null;const i=new Date(r);return Number.isNaN(i.getTime())?null:i}attrDate(e){return _t.attrDate(this,e)}static setAttrDate(e,t,r){if(!(r instanceof Date)||Number.isNaN(r.getTime()))throw new Error("Value is not a valid Date.");return _t.setAttr(e,t,r.toISOString())}setAttrDate(e,t){return _t.setAttrDate(this,e,t)}static attrJson(e,t){const r=_t._preElem(e,"attrJson").getAttribute(_t.getAttrName(t));if(!r)return null;try{return JSON.parse(r)}catch{return null}}attrJson(e){return _t.attrJson(this,e)}static setAttrJson(e,t,r,i,s){const n=JSON.stringify(r,i,s);return _t.setAttr(e,t,n)}setAttrJson(e,t,r,i){return _t.setAttrJson(this,e,t,r,i)}static attrNumber(e,t){const r=_t._preElem(e,"attrNumber").getAttribute(_t.getAttrName(t));return null!=r?parseFloat(r):null}attrNumber(e){return _t.attrNumber(this,e)}static setAttrNumber(e,t,r){if("number"!=typeof r)throw new Error("Value is not a valid number.");return _t.setAttr(e,t,r.toString())}setAttrNumber(e,t){return _t.setAttrNumber(this,e,t)}static attrBoolean(e,t){const r=_t._preElem(e,"attrBoolean").getAttribute(_t.getAttrName(t));return null===r||"true"!==r&&"false"!==r?null:/^true$/i.test(r)}attrBoolean(e){return _t.attrBoolean(this,e)}static setAttrBoolean(e,t,r){if("boolean"!=typeof r)throw new Error("Value is not a valid boolean.");return _t.setAttr(e,t,r.toString())}setAttrBoolean(e,t){return _t.setAttrBoolean(this,e,t)}static attrString(e,t){const r=_t._preElem(e,"attrString").getAttribute(_t.getAttrName(t));return"string"==typeof r?r:null}attrString(e){return _t.attrString(this,e)}static setAttrString(e,t,r){if("string"!=typeof r)throw new Error("Value is not a valid string.");return _t.setAttr(e,t,r)}setAttrString(e,t){return _t.setAttrString(this,e,t)}static attr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElem(e,"attr").getAttribute(_t.getAttrName(t))}attr(e){return _t.attr(this,e)}static setAttr(e,t,r=null){const i=_t._preElems(e,"setAttr");if("object"==typeof t&&null!==t)return Object.entries(t).forEach(([e,t])=>i.forEach(r=>{null===t?r.removeAttribute(_t.getAttrName(e)):r.setAttribute(_t.getAttrName(e),String(t))})),e;if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return i.forEach(e=>{null===r?e.removeAttribute(_t.getAttrName(t)):e.setAttribute(_t.getAttrName(t),String(r))}),e}setAttr(e,t){return _t.setAttr(this,e,t)}static removeAttr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElems(e,"removeAttr").forEach(e=>e.removeAttribute(_t.getAttrName(t))),e}removeAttr(e){return _t.removeAttr(this,e)}static hasAttr(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return _t._preElem(e,"hasAttr").hasAttribute(_t.getAttrName(t))}hasAttr(e){return _t.hasAttr(this,e)}static hasProp(e,t){if("string"!=typeof t)throw new TypeError('The "name" must be a string.');return!!_t._preElem(e,"hasProp")[_t.getPropName(t)]}hasProp(e){return _t.hasProp(this,e)}static addProp(e,...t){return _t._preElems(e,"addProp").forEach(e=>{t.forEach(t=>{if("string"!=typeof t)throw new TypeError('Each "name" must be a string.');e[_t.getPropName(t)]=!0})}),e}addProp(...e){return _t.addProp(this,...e)}static removeProp(e,...t){return _t._preElems(e,"removeProp").forEach(e=>{t.forEach(t=>{if("string"!=typeof t)throw new TypeError('Each "name" must be a string.');e[_t.getPropName(t)]=!1})}),e}removeProp(...e){return _t.removeProp(this,...e)}static toggleProp(e,t,r){const i=_t._preElems(e,"toggleProp");if(void 0!==r&&"boolean"!=typeof r)throw new TypeError('The "force" must be a boolean.');return(Array.isArray(t)?t:[t]).forEach(e=>{if("string"!=typeof e)throw new TypeError("Each property name must be a string.");i.forEach(t=>{(void 0===r?!t[_t.getPropName(e)]:r)?_t.addProp(t,e):_t.removeProp(t,e)})}),e}toggleProp(e,t){return _t.toggleProp(this,e,t)}static prop(e,t){if("string"!=typeof t)throw new TypeError('Invalid arguments passed to prop(). Expected string for "name".');return _t._preElem(e,"prop")[t]}prop(e){return _t.prop(this,e)}static setProp(e,t,r){if("string"!=typeof t||""===t.trim())throw new Error("Property name must be a non-empty string.");return _t._preElems(e,"setProp").forEach(e=>{e[t]=r}),e}setProp(e,t){return _t.setProp(this,e,t)}static remove(e){return _t._preElems(e,"remove").forEach(e=>e.remove()),e}remove(){return _t.remove(this)}static index(e,t=null){const r=_t._preElem(e,"index");if(!r)return-1;if(!t)return Array.prototype.indexOf.call(r.parentNode?.children||[],r);if(t){const e="string"==typeof t?document.querySelectorAll(t):_t._preElems(t,"index");return Array.prototype.indexOf.call(e,r)}return-1}index(e){return _t.index(this,e)}static _getCustomRect(e,t){const r={height:0,width:0,x:0,y:0,bottom:0,left:0,right:0,top:0,toJSON:function(){throw new Error("Function not implemented.")}};for(const t in e)"number"==typeof e[t]&&(r[t]=e[t]);if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("extraRect must be a non-null object.");const{height:i=0,width:s=0,top:n=0,bottom:o=0,left:a=0,right:l=0}=t;if("number"!=typeof i)throw new Error("extraRect.height must be a number.");if("number"!=typeof s)throw new Error("extraRect.width must be a number.");if("number"!=typeof n)throw new Error("extraRect.top must be a number.");if("number"!=typeof o)throw new Error("extraRect.bottom must be a number.");if("number"!=typeof a)throw new Error("extraRect.left must be a number.");if("number"!=typeof l)throw new Error("extraRect.right must be a number.");return r.height+=i,r.width+=s,r.top+=n,r.bottom+=o,r.left+=a,r.right+=l,r}static isCollWith(e,t,r={}){const i=_t._getCustomRect(_t._preElem(e,"isCollWith").getBoundingClientRect(),r),s=_t._preElem(t,"isCollWith").getBoundingClientRect();return Tt(i,s)}isCollWith(e,t){return _t.isCollWith(this,e,t)}static isCollPerfWith(e,t,r={}){const i=_t._getCustomRect(_t._preElem(e,"isCollPerfWith").getBoundingClientRect(),r),s=_t._preElem(t,"isCollPerfWith").getBoundingClientRect();return St(i,s)}isCollPerfWith(e,t){return _t.isCollPerfWith(this,e,t)}static _isCollWithLock(e,t,r,i,s){const n=Nt[s];if(e)return n.has(i)||n.set(i,!0),!0;if(n.has(i)){let e=!1;switch(s){case"top":e=xt(t,r);break;case"bottom":e=At(t,r);break;case"left":e=Ct(t,r);break;case"right":e=It(t,r)}return e&&n.delete(i),n.has(i)}return!1}static isCollWithLock(e,t,r,i={}){const s=_t._preElem(e,"isCollWithLock"),n=_t._preElem(t,"isCollWithLock"),o=_t._getCustomRect(s.getBoundingClientRect(),i),a=n.getBoundingClientRect(),l=Tt(o,a);return _t._isCollWithLock(l,o,a,s,r)}isCollWithLock(e,t,r){return _t.isCollWithLock(this,e,t,r)}static isCollPerfWithLock(e,t,r,i={}){const s=_t._preElem(e,"isCollPerfWithLock"),n=_t._preElem(t,"isCollPerfWithLock"),o=_t._getCustomRect(s.getBoundingClientRect(),i),a=n.getBoundingClientRect(),l=St(o,a);return _t._isCollWithLock(l,o,a,s,r)}isCollPerfWithLock(e,t,r){return _t.isCollPerfWithLock(this,e,t,r)}static resetCollLock(e){const t=_t._preElem(e,"resetCollLock");let r=!1;for(const e of["top","bottom","left","right"])Nt[e].has(t)&&(Nt[e].delete(t),r=!0);return r}resetCollLock(){return _t.resetCollLock(this)}static resetCollLockDir(e,t){const r=_t._preElem(e,"resetCollLockDir"),i=Nt[t];return!!i.has(r)&&(i.delete(r),!0)}resetCollLockDir(e){return _t.resetCollLockDir(this,e)}static isInViewport(e){const t=_t._preElem(e,"isInViewport");if(!t.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const r=_t.offset(t).top,i=r+_t.outerHeight(t),s=_t.scrollTop(window),n=s+_t.height(window);return i>s&&r<n}isInViewport(){return _t.isInViewport(this)}static isScrolledIntoView(e){const t=_t._preElem(e,"isScrolledIntoView");if(!t.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const r=_t.scrollTop(window),i=r+_t.height(window),s=_t.offset(t).top;return s+_t.height(t)<=i&&s>=r}isScrolledIntoView(){return _t.isScrolledIntoView(this)}static isInContainer(e,t){const r=_t._preElem(e,"isInContainer"),i=_t._preElem(t,"isInContainer");if(!r.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const s=r.getBoundingClientRect(),n=i.getBoundingClientRect(),o=s.bottom>n.top&&s.top<n.bottom,a=s.right>n.left&&s.left<n.right;return o&&a}isInContainer(e){return _t.isInContainer(this,e)}static isFullyInContainer(e,t){const r=_t._preElem(e,"isScrolledIntoView"),i=_t._preElem(t,"isInContainer");if(!r.checkVisibility({contentVisibilityAuto:!1,opacityProperty:!1,visibilityProperty:!1}))return!1;const s=r.getBoundingClientRect(),n=i.getBoundingClientRect();return s.top>=n.top&&s.bottom<=n.bottom&&s.left>=n.left&&s.right<=n.right}isFullyInContainer(e){return _t.isFullyInContainer(this,e)}static hasScroll(e){const t=_t._preElem(e,"hasScroll");return{v:t.scrollHeight>t.clientHeight,h:t.scrollWidth>t.clientWidth}}hasScroll(){return _t.hasScroll(this)}}const Rt=_t,jt=le("TinyDragger");class Pt{static Utils={...n,TinyHtml:Rt};#ye=!0;#u=!1;#ge=0;#we=0;#be=!0;#ve=!1;#Ee=!1;#Te=!1;#Se=!1;#xe=!1;#Ae=!1;#Ce=null;#Ie=[];#ke=null;#De={start:!1,end:!1,collide:!1,move:!1};#Me=null;#F;#Le="drag-hidden";#Ne="dragging";#_e="drag-active";#Re="jail-drag-active";#je="jail-drag-disabled";#Pe="dragging-collision";#Oe=9999;constructor(e,t={}){if(!(e instanceof HTMLElement))throw new Error("TinyDragger requires a valid target HTMLElement to initialize.");if(this.#F=e,void 0!==t.jail&&!(t.jail instanceof HTMLElement))throw new Error('The "jail" option must be an HTMLElement if provided.');if(void 0!==t.defaultZIndex&&this.setDefaultZIndex(t.defaultZIndex),void 0!==t.vibration&&!1!==t.vibration&&!v(t.vibration))throw new Error('The "vibration" option must be an object or false.');const r=(e,t)=>{if(void 0!==e&&"boolean"!=typeof e)throw new Error(`The "${t}" option must be a boolean.`)},i=(e,t)=>{if(void 0!==e&&"string"!=typeof e)throw new Error(`The "${t}" option must be a string.`)};r(t.mirrorElem,"mirrorElem"),r(t.collisionByMouse,"collisionByMouse"),r(t.lockInsideJail,"lockInsideJail"),r(t.dropInJailOnly,"dropInJailOnly"),r(t.revertOnDrop,"revertOnDrop"),r(t.multiCollision,"multiCollision"),i(t.classDragging,"classDragging"),i(t.classBodyDragging,"classBodyDragging"),i(t.classJailDragging,"classJailDragging"),i(t.classJailDragDisabled,"classJailDragDisabled"),i(t.classDragCollision,"classDragCollision"),i(t.classHidden,"classHidden"),t.jail instanceof HTMLElement&&(this.#Me=t.jail),this.#De=Object.assign({start:!1,end:!1,collide:!1,move:!1},v(t.vibration)?t.vibration:{}),"string"==typeof t.classDragging&&(this.#Ne=t.classDragging),"string"==typeof t.classBodyDragging&&(this.#_e=t.classBodyDragging),"string"==typeof t.classJailDragging&&(this.#Re=t.classJailDragging),"string"==typeof t.classJailDragDisabled&&(this.#je=t.classJailDragDisabled),"string"==typeof t.classHidden&&(this.#Le=t.classHidden),"string"==typeof t.classDragCollision&&(this.#Pe=t.classDragCollision),"boolean"==typeof t.collisionByMouse&&(this.#xe=t.collisionByMouse),"boolean"==typeof t.mirrorElem&&(this.#be=t.mirrorElem),"boolean"==typeof t.revertOnDrop&&(this.#Te=t.revertOnDrop),"boolean"==typeof t.lockInsideJail&&(this.#Ee=t.lockInsideJail),"boolean"==typeof t.dropInJailOnly&&(this.#Ae=t.dropInJailOnly),"boolean"==typeof t.multiCollision&&(this.#ve=t.multiCollision),this._onMouseDown=this.#$e.bind(this),this._onMouseMove=this.#He.bind(this),this._onMouseUp=this.#Fe.bind(this),this._onTouchStart=e=>this.#$e(e.touches[0]),this._onTouchMove=e=>this.#He(e.touches[0]),this._onTouchEnd=e=>this.#Fe(e.changedTouches[0]),this.#F.addEventListener("mousedown",this._onMouseDown),this.#F.addEventListener("touchstart",this._onTouchStart,{passive:!1})}enable(){jt(this.#u),this.#Me&&this.#Me.classList.add(this.#je),this.#ye=!0}disable(){jt(this.#u),this.#Me&&this.#Me.classList.remove(this.#je),this.#ye=!1}addCollidable(e){if(jt(this.#u),!(e instanceof HTMLElement))throw new Error("addCollidable expects an HTMLElement as argument.");this.#Ie.includes(e)||this.#Ie.push(e)}removeCollidable(e){if(jt(this.#u),!(e instanceof HTMLElement))throw new Error("removeCollidable expects an HTMLElement as argument.");this.#Ie=this.#Ie.filter(t=>t!==e)}setVibrationPattern({startPattern:e=!1,endPattern:t=!1,collidePattern:r=!1,movePattern:i=!1}={}){jt(this.#u);const s=e=>!1===e||Array.isArray(e)&&e.every(e=>"number"==typeof e);if(!s(e))throw new Error('Invalid "startPattern": must be false or an array of numbers.');if(!s(t))throw new Error('Invalid "endPattern": must be false or an array of numbers.');if(!s(r))throw new Error('Invalid "collidePattern": must be false or an array of numbers.');if(!s(i))throw new Error('Invalid "movePattern": must be false or an array of numbers.');this.#De={start:e,end:t,collide:r,move:i}}disableVibration(){jt(this.#u),this.#De={start:!1,end:!1,collide:!1,move:!1}}getOffset(e){if(jt(this.#u),!(e instanceof MouseEvent||e instanceof Touch)||"number"!=typeof e.clientX||"number"!=typeof e.clientY)throw new Error("getOffset expects an event with valid clientX and clientY coordinates.");const t=this.#F.getBoundingClientRect(),{left:r,top:i}=Rt.borderWidth(this.#F);return{x:e.clientX-t.left+r,y:e.clientY-t.top+i}}#$e(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#ye||!this.#F.parentElement)return;if(this.#be){const e=this.#F.cloneNode(!0);if(!(e instanceof HTMLElement))throw new Error("[TinyDragger] INVALID DRAG ELEMENT!");this.#ke=e}else this.#ke=this.#F;this.#Se=!0;const t=this.#F.getBoundingClientRect();Object.assign(this.#ke.style,{position:"absolute",pointerEvents:"none",left:`${this.#F.offsetLeft}px`,top:`${this.#F.offsetTop}px`,width:`${t.width}px`,height:`${t.height}px`,zIndex:this.#Oe}),this.#be&&(this.#F.classList.add(this.#Le),this.#F.parentElement.appendChild(this.#ke));const{x:r,y:i}=this.getOffset(e);this.#we=r,this.#ge=i,this.#ke.classList.add(this.#Ne),document.body.classList.add(this.#_e),this.#Me&&this.#Me.classList.add(this.#Re),document.addEventListener("mousemove",this._onMouseMove),document.addEventListener("mouseup",this._onMouseUp),document.addEventListener("touchmove",this._onTouchMove,{passive:!1}),document.addEventListener("touchend",this._onTouchEnd),navigator.vibrate&&Array.isArray(this.#De.start)&&navigator.vibrate(this.#De.start),this.checkDragCollision(e),this.#ze("drag")}#Be=[];#We(e){e&&(e.classList.add(this.#Pe),this.#Be.push(e))}#Ue(){for(;this.#Be.length>0;){const e=this.#Be.shift();e&&e.classList.remove(this.#Pe)}this.#Ce&&this.#Ce.classList.remove(this.#Pe)}checkDragCollision(e){jt(this.#u);const{collidedElements:t}=this.execCollision(e),r=t[0]||null;this.#Ce&&!t.includes(this.#Ce)&&this.#Ue(),t.forEach(e=>this.#We(e)),this.#Ie.forEach(e=>{t.includes(e)||e.classList.remove(this.#Pe)}),navigator.vibrate&&Array.isArray(this.#De.collide)&&t.length>0&&navigator.vibrate(this.#De.collide),this.#Ce=r}#He(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#Se||!this.#ye||!this.#ke)return;const t=(this.#ke.offsetParent||document.body).getBoundingClientRect();let r=e.clientX-t.left-this.#we,i=e.clientY-t.top-this.#ge;if(this.#Ee&&this.#Me){const e=this.#Me.getBoundingClientRect(),s=this.#ke.getBoundingClientRect(),n=e.left-t.left,o=e.top-t.top,{x:a,y:l}=Rt.borderWidth(this.#Me),h=n+e.width-s.width-l,u=o+e.height-s.height-a;r=Math.max(n,Math.min(r,h)),i=Math.max(o,Math.min(i,u))}this.#ke.style.position="absolute",this.#ke.style.left=`${r}px`,this.#ke.style.top=`${i}px`,navigator.vibrate&&Array.isArray(this.#De.move)&&navigator.vibrate(this.#De.move),this.checkDragCollision(e),this.#ze("dragging")}execCollision(e){if(jt(this.#u),this.#u||!this.#ke)return{inJail:!1,collidedElements:[]};let t=[],r=!0;const i=this.#Me?.getBoundingClientRect();if(this.#xe){const s=e.clientX,n=e.clientY;this.#Ae&&this.#Me&&i&&(r=s>=i.left&&s<=i.right&&n>=i.top&&n<=i.bottom),t=r?this.#ve?this.getAllCollidedElements(s,n):[this.getCollidedElement(s,n)].filter(Boolean):[]}else{const e=this.#ke.getBoundingClientRect();this.#Ae&&this.#Me&&i&&(r=e.left>=i.left&&e.right<=i.right&&e.top>=i.top&&e.bottom<=i.bottom),t=r?this.#ve?this.getAllCollidedElementsByRect(e):[this.getCollidedElementByRect(e)].filter(Boolean):[]}return{inJail:r,collidedElements:t}}#Fe(e){if(e instanceof MouseEvent&&e.preventDefault(),this.#u||!this.#Se)return;if(this.#Se=!1,!this.#ke)return;this.#F.classList.remove(this.#Ne),document.body.classList.remove(this.#_e),this.#Me&&this.#Me.classList.remove(this.#Re),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),document.removeEventListener("touchmove",this._onTouchMove),document.removeEventListener("touchend",this._onTouchEnd);const{collidedElements:t}=this.execCollision(e);navigator.vibrate&&Array.isArray(this.#De.end)&&navigator.vibrate(this.#De.end);const r=this.#ke.style.left,i=this.#ke.style.top;this.#ke&&(this.#be?this.#ke.remove():Object.assign(this.#ke.style,{position:"",pointerEvents:"",left:"",top:"",width:"",height:"",zIndex:""}),this.#ke=null),this.#Ce&&this.#Ue(),this.#Ce=null,this.#be&&this.#F.classList.remove(this.#Le),this.#Te||(this.#F.style.left=r,this.#F.style.top=i);const s=new CustomEvent("drop",{detail:{targets:t,first:t[0]||null}});this.#F.dispatchEvent(s)}#qe(e,t){const r=e.getBoundingClientRect();return!(t.right<r.left||t.left>r.right||t.bottom<r.top||t.top>r.bottom)}getAllCollidedElementsByRect(e){if(jt(this.#u),!(e instanceof DOMRect)||"number"!=typeof e.left||"number"!=typeof e.right||"number"!=typeof e.top||"number"!=typeof e.bottom)throw new Error("getCollidedElementByRect expects a valid DOMRect object.");return this.#Ie.filter(t=>this.#qe(t,e))}getCollidedElementByRect(e){if(jt(this.#u),!(e instanceof DOMRect)||"number"!=typeof e.left||"number"!=typeof e.right||"number"!=typeof e.top||"number"!=typeof e.bottom)throw new Error("getCollidedElementByRect expects a valid DOMRect object.");return this.#Ie.find(t=>this.#qe(t,e))||null}#Ve(e,t,r){const i=e.getBoundingClientRect();return t>=i.left&&t<=i.right&&r>=i.top&&r<=i.bottom}getAllCollidedElements(e,t){if(jt(this.#u),"number"!=typeof e||"number"!=typeof t)throw new Error("getCollidedElement expects numeric x and y coordinates.");return this.#Ie.filter(r=>this.#Ve(r,e,t))}getCollidedElement(e,t){if(jt(this.#u),"number"!=typeof e||"number"!=typeof t)throw new Error("getCollidedElement expects numeric x and y coordinates.");return this.#Ie.find(r=>this.#Ve(r,e,t))||null}#ze(e){const t=new CustomEvent(e);this.#F.dispatchEvent(t)}getDragging(){return jt(this.#u),this.#Se}getLockInsideJail(){return jt(this.#u),this.#Ee}setLockInsideJail(e){if(jt(this.#u),"boolean"!=typeof e)throw new Error("lockInsideJail must be a boolean.");this.#Ee=e}getRevertOnDrop(){return jt(this.#u),this.#Te}setRevertOnDrop(e){if(jt(this.#u),"boolean"!=typeof e)throw new Error("revertOnDrop must be a boolean.");this.#Te=e}getCollisionByMouse(){return jt(this.#u),this.#xe}setCollisionByMouse(e){if(jt(this.#u),"boolean"!=typeof e)throw new Error("collisionByMouse must be a boolean.");this.#xe=e}getDropInJailOnly(){return jt(this.#u),this.#Ae}setDropInJailOnly(e){if(jt(this.#u),"boolean"!=typeof e)throw new Error("dropInJailOnly must be a boolean.");this.#Ae=e}getDefaultZIndex(){return jt(this.#u),this.#Oe}setDefaultZIndex(e){if(jt(this.#u),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("Z-index must be a finite number.");this.#Oe=e}isMirrorEnabled(){return jt(this.#u),this.#be}setMirrorEnabled(e){if(jt(this.#u),"boolean"!=typeof e)throw new TypeError("Mirror setting must be a boolean.");this.#be=e}getTarget(){return jt(this.#u),this.#F}getJail(){return jt(this.#u),this.#Me}getDragProxy(){return jt(this.#u),this.#ke}getLastCollision(){return jt(this.#u),this.#Ce}getCollidables(){return jt(this.#u),[...this.#Ie]}getDragHiddenClass(){return jt(this.#u),this.#Le}getClassDragging(){return jt(this.#u),this.#Ne}getClassBodyDragging(){return jt(this.#u),this.#_e}getClassJailDragging(){return jt(this.#u),this.#Re}getClassJailDragDisabled(){return jt(this.#u),this.#je}getClassDragCollision(){return jt(this.#u),this.#Pe}getVibrations(){return jt(this.#u),{...this.#De}}getStartVibration(){return jt(this.#u),this.#De.start}getEndVibration(){return jt(this.#u),this.#De.end}getCollideVibration(){return jt(this.#u),this.#De.collide}getMoveVibration(){return jt(this.#u),this.#De.move}isEnabled(){return jt(this.#u),this.#ye}destroy(){this.#u||(this.disable(),this.#F.removeEventListener("mousedown",this._onMouseDown),this.#F.removeEventListener("touchstart",this._onTouchStart),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),document.removeEventListener("touchmove",this._onTouchMove),document.removeEventListener("touchend",this._onTouchEnd),this.#Ce&&this.#Ue(),this.#ke&&(this.#be?this.#ke.remove():Object.assign(this.#ke.style,{position:"",pointerEvents:"",left:"",top:"",width:"",height:"",zIndex:""}),this.#ke=null),this.#Ie=[],this.#Se=!1,this.#Ce=null,this.#be&&this.#F.classList.remove(this.#Le),this.#F.classList.remove(this.#Ne),document.body.classList.remove(this.#_e),this.#Me&&this.#Me.classList.remove(this.#Re,this.#je),this.#u=!0)}}const Ot=Pt,$t=class{#Ke=[];#Ge=!1;#Je=!1;#Ye=[];#Xe(){this.#Ge&&Promise.all(this.#Ye).then(()=>{this.#Je=!0,this.#Qe(!1)}).catch(e=>{console.error("[TinyDomReadyManager] Promise rejected:",e)})}#Qe(e){this.#Ke.filter(t=>t.domOnly===e).sort((e,t)=>t.priority-e.priority).forEach(e=>this.#Ze(e)),this.#Ke=this.#Ke.filter(t=>!(t.once&&(!e||t.domOnly)))}#Ze(e){if("function"==typeof e.filter)try{if(!e.filter())return}catch(e){return void console.warn("[TinyDomReadyManager] Filter error:",e)}try{e.fn()}catch(e){console.error("[TinyDomReadyManager] Handler error:",e)}}_markDomReady(){this.#Ge=!0,this.#Qe(!0),this.#Xe()}init(){if(this.#Ge)throw new Error("[TinyDomReadyManager] init() has already been called.");"interactive"===document.readyState||"complete"===document.readyState?this._markDomReady():document.addEventListener("DOMContentLoaded",()=>this._markDomReady())}addPromise(e){if(!(e instanceof Promise))throw new TypeError("[TinyDomReadyManager] promise must be a valid Promise.");this.#Je||(this.#Ye.push(e),this.#Ge&&this.#Xe())}onReady(e,{once:t=!0,priority:r=0,filter:i=null,domOnly:s=!1}={}){if("function"!=typeof e)throw new TypeError("[TinyDomReadyManager] fn must be a function.");const n={fn:e,once:t,priority:r,filter:i,domOnly:s};if(s&&this.#Ge)return this.#Ze(n),void(t||this.#Ke.push(n));!s&&this.#Je?this.#Ze(n):this.#Ke.push(n)}isReady(){return this.#Je}isDomReady(){return this.#Ge}},Ht=class{#et=!1;#tt=!1;#rt=null;#it=100;#st=null;#nt;constructor({audio:e=null,defaultIcon:t=null,bodyLimit:r=100,defaultOnClick:i=function(e){e.preventDefault(),window.focus&&window.focus(),this.close()}}={}){if(!(e instanceof HTMLAudioElement)&&"string"!=typeof e&&null!==e)throw new TypeError("audio must be an instance of HTMLAudioElement or null.");if(null!==t&&"string"!=typeof t)throw new TypeError("defaultIcon must be a string or null.");if(!Number.isFinite(r)||r<0)throw new TypeError("bodyLimit must be a non-negative number.");if("function"!=typeof i)throw new TypeError("defaultOnClick must be a function.");this.#rt="string"!=typeof e?e:new Audio(e),this.#st=t,this.#it=r,this.#nt=i}requestPerm(){const e=this;return new Promise((t,r)=>{e.isCompatible()?"default"===Notification.permission?Notification.requestPermission().then(r=>{this.#tt=!0,e.#et="granted"===r,t(e.#et)}).catch(r):(this.#tt=!0,e.#et="granted"===Notification.permission,t(e.#et)):(this.#tt=!0,e.#et=!1,t(!1))})}isCompatible(){return"Notification"in window}send(e,t={}){if(!this.#tt)throw new Error("You must call requestPerm() before sending a notification.");if("string"!=typeof e)throw new TypeError("title must be a string.");if("object"!=typeof t||null===t)throw new TypeError("config must be a non-null object.");if(!this.#et)return null;const{icon:r=this.#st||void 0,vibrate:i=[200,100,200]}=t,s={...t};"string"==typeof r&&(s.icon=r),Array.isArray(i)&&(s.vibrate=i),"string"==typeof s.body&&(s.body=re(s.body,this.#it));const n=new Notification(e,s);return n.addEventListener("show",()=>{this.#rt instanceof HTMLAudioElement&&(this.#rt.currentTime=0,this.#rt.play().catch(e=>console.error(e)))}),"function"==typeof this.#nt&&n.addEventListener("click",this.#nt),n}wasPermissionRequested(){return this.#tt}isAllowed(){return this.#et}getAudio(){return this.#rt}setAudio(e){if(!(e instanceof HTMLAudioElement)&&"string"!=typeof e&&null!==e)throw new TypeError("sound must be an instance of HTMLAudioElement or null.");this.#rt="string"!=typeof e?e:new Audio(e)}getBodyLimit(){return this.#it}setBodyLimit(e){if(!Number.isFinite(e)||e<0)throw new TypeError("bodyLimit must be a non-negative number.");this.#it=e}getDefaultAvatar(){return this.#st}setDefaultAvatar(e){if("string"!=typeof e&&null!==e)throw new TypeError("defaultIcon must be a string or null.");this.#st=e}getDefaultOnClick(){return this.#nt}setDefaultOnClick(e){if("function"!=typeof e)throw new TypeError("defaultOnClick must be a function.");this.#nt=e}};function Ft(e,t){if(!E(e))throw new TypeError("The first argument must be a non-null object.");if("function"!=typeof t)throw new TypeError("The second argument must be a function.");const r=Object.entries(e).filter(t);return Object.fromEntries(r)}function zt(e,t){if(void 0!==t.obj&&"function"!=typeof t.obj)throw new TypeError("filter.obj must be a function if provided.");if(void 0!==t.value&&"function"!=typeof t.value)throw new TypeError("filter.value must be a function if provided.");if(void 0!==t.array&&"function"!=typeof t.array)throw new TypeError("filter.array must be a function if provided.");let r;r=e instanceof Map?new Map:e instanceof Set?new Set:{};const i=(s=e)instanceof Map?Array.from(s.entries()):s instanceof Set?Array.from(s.values()).map(e=>[void 0,e]):Object.entries(s);var s;const n=(e,r)=>{const i=[];for(let s=0;s<e.length;s++){const o=e[s];if(Array.isArray(o))i.push(n(o,r));else if(E(o)){const r=zt(o,t);(void 0===t.obj||t.obj(r,s,e))&&i.push(r)}else(void 0===t.value||t.value([r,o],s,e))&&i.push(o)}return i};for(let e=0;e<i.length;e++){const[s,o]=i[e];if(Array.isArray(o)){const a=n(o,s);(void 0===t.array||t.array([s,a],e,i))&&(r instanceof Map||r instanceof Set?r instanceof Map?r.set(s,a):r.add(a):r[s]=a)}else if(E(o)){const n=zt(o,t);(void 0===t.obj||t.obj(n,e,i))&&(r instanceof Map?r.set(s,n):r instanceof Set?r.add(n):r[s]=n)}else(void 0===t.value||t.value([s,o],e,i))&&(r instanceof Map?r.set(s,o):r instanceof Set?r.add(o):r[s]=o)}return r}function Bt(e,t,r){if(!Array.isArray(t))throw new TypeError("The second argument must be an array.");if(void 0!==r&&!Array.isArray(r))throw new TypeError("The third argument must be an array.");return Ft(e,([e,i])=>t.length>0?t.some(t=>{if(Array.isArray(t)){const[r,s]=t,n=e===r,o="function"==typeof s?s(i):i===s;return n&&o}const s=e===t,n=void 0===r||r.some(e=>"function"==typeof e?e(i):e===i);return s&&n}):void 0!==r&&r.some(e=>"function"==typeof e?e(i):e===i))}const Wt=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("string"!=typeof e)throw new TypeError(`Expected "${t}" to be a string, but received ${typeof e}.`)},Ut=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("function"!=typeof e)throw new TypeError(`Expected "${t}" to be a function, but received ${typeof e}.`)},qt=(e,t)=>{if("string"!=typeof t)throw new TypeError('Expected "name" to be a string.');if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError(`Expected "${t}" to be a plain object, but received ${null===e?"null":Array.isArray(e)?"array":typeof e}.`)},Vt=(e,t=!1)=>!t&&void 0===e,Kt=(e,t=!1)=>Vt(e,t)||"string"==typeof e||!t&&null===e,Gt=(e,t=!1)=>Vt(e,t)||"number"==typeof e||!t&&null===e,Jt=(e,t=!1)=>Vt(e,t)||"boolean"==typeof e||!t&&null===e,Yt=(e,t)=>!!Vt(e)||(Ut(t,"valueValidator"),Array.isArray(e)&&e.every(t)),Xt=new Map;class Qt extends Error{constructor(e,t,r){if(Wt(e,"message"),Wt(t,"url"),"string"!=typeof r)throw new TypeError(`Expected "stage" to be a string, but received ${typeof r}.`);super(e),this.name="MediaLoadingError",this.url=t,this.stage=r}}const Zt=async e=>{Wt(e,"str");const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-1",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("").substring(0,8)},er=(e,t="image/jpeg")=>{if(!(e instanceof Uint8Array)&&"string"!=typeof e)throw new TypeError(`Expected "data" to be an instance of Uint8Array or a string, but received ${typeof e}.`);Wt(t,"format");const r=e=>{const t=URL.createObjectURL(e),r=Xt.get(t);return Xt.set(t,"number"==typeof r?r+1:1),t};if(e instanceof Uint8Array)return r(new Blob([e],{type:t}));if("string"==typeof e&&e.startsWith("data:")){const i=e.split(",")[1],s=atob(i),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return r(new Blob([n],{type:t}))}return"string"==typeof e?e:""},tr=async e=>{if(Wt(e,"url"),!e.startsWith("blob:"))return e;try{const t=await fetch(e),r=await t.blob();return await new Promise((e,t)=>{const i=new FileReader;i.onloadend=()=>e(String(i.result)),i.onerror=t,i.readAsDataURL(r)})}catch(t){return console.warn(`[TinyAudioUtils] Failed to convert Blob URL to Base64 on export: ${e}`,t),e}},rr=e=>{qt(e,"content"),e&&Array.isArray(e.picture)&&e.picture.forEach(e=>{if("string"==typeof e.data&&e.data.startsWith("blob:")){const t=Xt.get(e.data)??0;t>1?Xt.set(e.data,t-1):Xt.delete(e.data),t<=1&&URL.revokeObjectURL(e.data)}})},ir=(e,t=!1)=>{if(v(e)){if(4!==b(e)){if(t)return!1;throw new TypeError("Invalid fetch data: Object must be an MediaContentFetchData.")}sr(e.common),qt(e.native,"_fetchData.native"),qt(e.format,"_fetchData.format"),qt(e.quality,"_fetchData.quality");for(const r in e.native){const i=e.native[r];if(!Yt(i,e=>"string"==typeof e.id)){if(t)return!1;throw new TypeError(`Invalid native data: "${r}" must be an array of native fetch data.`)}}}return!0},sr=e=>{if(qt(e,"common"),ir(e._fetchData),!Kt(e.title))throw new TypeError('Invalid metadata: "title" must be a string or null.');if(!Kt(e.album))throw new TypeError('Invalid metadata: "album" must be a string or null.');if(!Kt(e.albumartist))throw new TypeError('Invalid metadata: "albumartist" must be a a string or null.');if(!Kt(e.artist))throw new TypeError('Invalid metadata: "artist" must be a string or null.');if(!Jt(e.compilation))throw new TypeError('Invalid metadata: "compilation" must be a boolean or null.');if(!Jt(e.podcast))throw new TypeError('Invalid metadata: "podcast" must be a boolean or null.');if(!Jt(e.gapless))throw new TypeError('Invalid metadata: "gapless" must be a boolean or null.');if(!Jt(e.showMovement))throw new TypeError('Invalid metadata: "showMovement" must be a boolean or null.');if(!Gt(e.averageLevel))throw new TypeError('Invalid metadata: "averageLevel" must be a number or null.');if(!Gt(e.peakLevel))throw new TypeError('Invalid metadata: "peakLevel" must be a number or null.');if(!Gt(e.hdVideo))throw new TypeError('Invalid metadata: "hdVideo" must be a number or null.');if(!Gt(e.stik))throw new TypeError('Invalid metadata: "stik" must be a number or null.');if(!Gt(e.playCounter))throw new TypeError('Invalid metadata: "playCounter" must be a number or null.');if(!Gt(e.tvSeason))throw new TypeError('Invalid metadata: "tvSeason" must be a number or null.');if(!Gt(e.tvEpisode))throw new TypeError('Invalid metadata: "tvEpisode" must be a number or null.');if(!Gt(e.year))throw new TypeError('Invalid metadata: "year" must be a number or null.');if(!Gt(e.bpm))throw new TypeError('Invalid metadata: "bpm" must be a number or null.');if(!Gt(e.originalyear))throw new TypeError('Invalid metadata: "originalyear" must be a number or null.');if(!Gt(e.movementTotal))throw new TypeError('Invalid metadata: "movementTotal" must be a number or null.');if(!Kt(e.date))throw new TypeError('Invalid metadata: "date" must be a string or null.');if(!Kt(e.originaldate))throw new TypeError('Invalid metadata: "originaldate" must be a string or null.');if(!Kt(e.releasedate))throw new TypeError('Invalid metadata: "releasedate" must be a string or null.');if(!Kt(e.albumsort))throw new TypeError('Invalid metadata: "albumsort" must be a string or null.');if(!Kt(e.titlesort))throw new TypeError('Invalid metadata: "titlesort" must be a string or null.');if(!Kt(e.work))throw new TypeError('Invalid metadata: "work" must be a string or null.');if(!Kt(e.artistsort))throw new TypeError('Invalid metadata: "artistsort" must be a string or null.');if(!Kt(e.albumartistsort))throw new TypeError('Invalid metadata: "albumartistsort" must be a string or null.');if(!Kt(e.composersort))throw new TypeError('Invalid metadata: "composersort" must be a string or null.');if(!Kt(e.grouping))throw new TypeError('Invalid metadata: "grouping" must be a string or null.');if(!Kt(e.longDescription))throw new TypeError('Invalid metadata: "longDescription" must be a string or null.');if(!Kt(e.totaltracks))throw new TypeError('Invalid metadata: "totaltracks" must be a string or null.');if(!Kt(e.totaldiscs))throw new TypeError('Invalid metadata: "totaldiscs" must be a string or null.');if(!Kt(e.mood))throw new TypeError('Invalid metadata: "mood" must be a string or null.');if(!Kt(e.media))throw new TypeError('Invalid metadata: "media" must be a string or null.');if(!Kt(e.tvShow))throw new TypeError('Invalid metadata: "tvShow" must be a string or null.');if(!Kt(e.tvShowSort))throw new TypeError('Invalid metadata: "tvShowSort" must be a string or null.');if(!Kt(e.tvEpisodeId))throw new TypeError('Invalid metadata: "tvEpisodeId" must be a string or null.');if(!Kt(e.tvNetwork))throw new TypeError('Invalid metadata: "tvNetwork" must be a string or null.');if(!Kt(e.podcasturl))throw new TypeError('Invalid metadata: "podcasturl" must be a string or null.');if(!Kt(e.releasestatus))throw new TypeError('Invalid metadata: "releasestatus" must be a string or null.');if(!Kt(e.releasecountry))throw new TypeError('Invalid metadata: "releasecountry" must be a string or null.');if(!Kt(e.script))throw new TypeError('Invalid metadata: "script" must be a string or null.');if(!Kt(e.language))throw new TypeError('Invalid metadata: "language" must be a string or null.');if(!Kt(e.copyright))throw new TypeError('Invalid metadata: "copyright" must be a string or null.');if(!Kt(e.license))throw new TypeError('Invalid metadata: "license" must be a string or null.');if(!Kt(e.encodedby))throw new TypeError('Invalid metadata: "encodedby" must be a string or null.');if(!Kt(e.encodersettings))throw new TypeError('Invalid metadata: "encodersettings" must be a string or null.');if(!Kt(e.barcode))throw new TypeError('Invalid metadata: "barcode" must be a string or null.');if(!Kt(e.asin))throw new TypeError('Invalid metadata: "asin" must be a string or null.');if(!Kt(e.website))throw new TypeError('Invalid metadata: "website" must be a string or null.');if(!Kt(e.originalalbum))throw new TypeError('Invalid metadata: "originalalbum" must be a string or null.');if(!Kt(e.originalartist))throw new TypeError('Invalid metadata: "originalartist" must be a string or null.');if(!Kt(e.key))throw new TypeError('Invalid metadata: "key" must be a string or null.');if(!Kt(e.movement))throw new TypeError('Invalid metadata: "movement" must be a string or null.');if(!Kt(e.podcastId))throw new TypeError('Invalid metadata: "podcastId" must be a string or null.');if(!Yt(e.albumartists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "albumartists" must be an array of strings.');if(!Yt(e.genre,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "genre" must be an array of strings.');if(!Yt(e.label,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "label" must be an array of strings.');if(!Yt(e.composer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "composer" must be an array of strings.');if(!Yt(e.artists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "artists" must be an array of strings.');if(!Yt(e.lyricist,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "lyricist" must be an array of strings.');if(!Yt(e.writer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "writer" must be an array of strings.');if(!Yt(e.conductor,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "conductor" must be an array of strings.');if(!Yt(e.remixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "remixer" must be an array of strings.');if(!Yt(e.arranger,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "arranger" must be an array of strings.');if(!Yt(e.engineer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "engineer" must be an array of strings.');if(!Yt(e.publisher,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "publisher" must be an array of strings.');if(!Yt(e.producer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "producer" must be an array of strings.');if(!Yt(e.djmixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "djmixer" must be an array of strings.');if(!Yt(e.mixer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "mixer" must be an array of strings.');if(!Yt(e.technician,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "technician" must be an array of strings.');if(!Yt(e.subtitle,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "subtitle" must be an array of strings.');if(!Yt(e.description,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "description" must be an array of strings.');if(!Yt(e.discsubtitle,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "discsubtitle" must be an array of strings.');if(!Yt(e.releasetype,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "releasetype" must be an array of strings.');if(!Yt(e.isrc,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "isrc" must be an array of strings.');if(!Yt(e.performer_instrument,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "performer_instrument" must be an array of strings.');if(!Yt(e.notes,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "notes" must be an array of strings.');if(!Yt(e.category,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "category" must be an array of strings.');if(!Yt(e.keywords,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "keywords" must be an array of strings.');if(!Yt(e.catalognumber,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "catalognumber" must be an array of strings.');if(!Yt(e.picture,e=>e&&"object"==typeof e&&(void 0===e.description||"string"==typeof e.description)&&(void 0===e.name||"string"==typeof e.name)&&(void 0===e.type||"string"==typeof e.type)&&"string"==typeof e.format&&(e.data instanceof Uint8Array||"string"==typeof e.data)))throw new TypeError('Invalid metadata: "picture" must be an array of pictures.');if(!Yt(e.comment,e=>null!==e&&"object"==typeof e&&Kt(e.descriptor)&&Kt(e.language)&&Kt(e.text)))throw new TypeError('Invalid metadata: "comment" must be an array of valid IComment objects.');if(!Yt(e.lyrics,e=>null!==e&&"object"==typeof e&&Kt(e.text)&&Kt(e.descriptor)&&Kt(e.language)&&(!Array.isArray(e)||Yt(e.syncText,e=>null!==e&&"object"==typeof e&&Kt(e.text)&&Gt(e.timestamp)))&&(e=>void 0===e||null!==e&&"object"==typeof e&&Gt(e.notSynchronized)&&Gt(e.mpegFrameNumber)&&Gt(e.milliseconds))(e.timeStampFormat)&&(e=>void 0===e||null!==e&&"object"==typeof e&&Gt(e.other)&&Gt(e.lyrics)&&Gt(e.text)&&Gt(e.movement_part)&&Gt(e.events)&&Gt(e.chord)&&Gt(e.trivia_pop))(e.contentType)))throw new TypeError('Invalid metadata: "lyrics" must be an array of valid ILyricsTag objects.');if(!Yt(e.rating,e=>null!==e&&"object"==typeof e&&Kt(e.source)&&Gt(e.rating)))throw new TypeError('Invalid metadata: "rating" must be an array of valid IRating objects.');const t=(e,t)=>{if(!Vt(t)&&null!==t){if("object"!=typeof t)throw new TypeError(`Invalid metadata: "${e}" must be an object or null.`);if("number"!=typeof t.no&&null!==t.no)throw new TypeError(`Invalid metadata: "${e}.no" must be a number or null.`);if("number"!=typeof t.of&&null!==t.of)throw new TypeError(`Invalid metadata: "${e}.of" must be a number or null.`)}};t("disk",e.disk),t("track",e.track),t("movementIndex",e.movementIndex)},nr=async(e,t,r=!0)=>{Wt(e,"url"),Ut(t,"parseFile");const i=await fetch(e);if(!i.ok)throw new Error(`Failed to fetch audio file: ${i.status} ${i.statusText}`);const s=await i.blob(),n=await t(s);if(!n||"object"!=typeof n.common)throw new TypeError('Invalid metadata: "common" property is missing.');void 0!==typeof n.common["performer:instrument"]&&(n.common.performer_instrument=n.common["performer:instrument"]),ir(n);const o=n.common;sr(o);const a=o?.picture?.map(e=>({...e,data:r?er(e.data,e.format):e.data}))??[];n.common={...n.common,picture:a.map(e=>({...e,data:""}))},r&&Object.keys(n.native).forEach(e=>{n.native[e]=n.native[e].map(e=>{if(e.value&&"object"==typeof e.value&&e.value.data instanceof Uint8Array){const t=o?.picture?.findIndex(t=>t.data===e.value.data&&t.format===e.value.format&&t.description===e.value.description&&t.name===e.value.name)??-1;if(a[t])return{...e,value:{...e.value,data:""}}}return e})});const l=zt({title:o?.title,album:o?.album,albumartist:o?.albumartist,albumartists:o?.albumartists,genre:o?.genre,label:o?.label,composer:o?.composer,year:o?.year,artist:o?.artist,artists:o?.artists,disk:o?.disk?{no:o.disk.no,of:o.disk.of}:void 0,track:o?.track?{no:o.track.no,of:o.track.of}:void 0,movementIndex:o?.movementIndex?{no:o.movementIndex.no,of:o.movementIndex.of}:void 0,picture:a,date:o?.date,originaldate:o?.originaldate,originalyear:o?.originalyear,releasedate:o?.releasedate,comment:o?.comment,lyrics:o?.lyrics,albumsort:o?.albumsort,titlesort:o?.titlesort,work:o?.work,artistsort:o?.artistsort,albumartistsort:o?.albumartistsort,composersort:o?.composersort,lyricist:o?.lyricist,writer:o?.writer,conductor:o?.conductor,remixer:o?.remixer,arranger:o?.arranger,engineer:o?.engineer,publisher:o?.publisher,producer:o?.producer,djmixer:o?.djmixer,mixer:o?.mixer,technician:o?.technician,grouping:o?.grouping,subtitle:o?.subtitle,description:o?.description,longDescription:o?.longDescription,discsubtitle:o?.discsubtitle,totaltracks:o?.totaltracks,totaldiscs:o?.totaldiscs,movementTotal:o?.movementTotal,compilation:o?.compilation,rating:o?.rating,bpm:o?.bpm,mood:o?.mood,media:o?.media,catalognumber:o?.catalognumber,tvShow:o?.tvShow,tvShowSort:o?.tvShowSort,tvSeason:o?.tvSeason,tvEpisode:o?.tvEpisode,tvEpisodeId:o?.tvEpisodeId,tvNetwork:o?.tvNetwork,podcast:o?.podcast,podcasturl:o?.podcasturl,releasestatus:o?.releasestatus,releasetype:o?.releasetype,releasecountry:o?.releasecountry,script:o?.script,language:o?.language,copyright:o?.copyright,license:o?.license,encodedby:o?.encodedby,encodersettings:o?.encodersettings,gapless:o?.gapless,barcode:o?.barcode,isrc:o?.isrc,asin:o?.asin,website:o?.website,performer_instrument:o?.performer_instrument,averageLevel:o?.averageLevel,peakLevel:o?.peakLevel,notes:o?.notes,originalalbum:o?.originalalbum,originalartist:o?.originalartist,key:o?.key,category:o?.category,hdVideo:o?.hdVideo,keywords:o?.keywords,movement:o?.movement,podcastId:o?.podcastId,showMovement:o?.showMovement,stik:o?.stik,playCounter:o?.playCounter},{value:([e,t])=>null!=t,obj:e=>b(e)>0,array:([e,t])=>t.length>0});return l._fetchData=n,l},or=async(e,t={},r={},i=e=>{if(!(e instanceof Blob))throw new TypeError('Expected "data" to be a Blob.');return new Promise((e,t)=>t(new TypeError("parseFile library not found.")))},s={},n=!0,o="null")=>{if("string"!=typeof e&&!(e instanceof HTMLMediaElement))throw new TypeError("Source must be a string or an HTMLMediaElement.");if(qt(t,"defaultMetadata"),qt(r,"metadata"),Ut(i,"parseFile"),qt(s,"callbacks"),s.onProgress&&"function"!=typeof s.onProgress)throw new TypeError("callbacks.onProgress must be a function.");if(s.onError&&"function"!=typeof s.onError)throw new TypeError("callbacks.onError must be a function.");if("string"!=typeof o&&"function"!=typeof o)throw new TypeError("unknownArtist must be a string or a function returning a string.");let a,l="";const h=(t,r)=>{if(Wt(t,"stage"),void 0!==r&&!(r instanceof Event))throw new TypeError('Expected "event" to be an Event or undefined.');s.onProgress&&s.onProgress({event:r,status:"loading",stage:t,url:l||(e instanceof HTMLMediaElement?e.src:"unknown")})},u=(t,r)=>{if(!(t instanceof Error))throw new TypeError('Expected "error" to be an Error.');Wt(r,"stage"),s.onError&&s.onError({error:t instanceof Error?t:new Error(String(t)),url:l||(e instanceof HTMLMediaElement?e.src:"unknown"),stage:r})};try{h("INITIALIZING"),"string"==typeof e?(l=e,a=new Audio(l)):(a=e,l=a.src);try{await new Promise((e,t)=>{const r=e=>h("DOWNLOADING",e),i=()=>{n(),e(void 0)},s=e=>{n(),t(new Error(`HTMLMediaElement failed to load: ${e.message||"Unknown error"}`))},n=()=>{a.removeEventListener("progress",r),a.removeEventListener("loadedmetadata",i),a.removeEventListener("error",s)};a.addEventListener("progress",r),a.addEventListener("loadedmetadata",i),a.addEventListener("error",s),a.readyState>=1&&(n(),e(void 0))}),h("METADATA_LOADED")}catch(e){throw new Qt(e instanceof Error?e.message:"UNKNOWN ERROR",l,"METADATA")}const c={id:r.id||await Zt(l),duration:Math.floor(1e3*a.duration),url:l,weight:r.weight??1};let d={};h("EXTRACTING_ID3");try{d=await nr(l,i,n)}catch(e){u(e instanceof Error?e:new Error("Unknown Error"),"ID3"),console.warn(`[TinyAudioUtils] ID3 extraction failed for ${l}. Falling back to filename.`)}const m=e=>{Wt(e,"url");try{return(e.split(/[?#]/)[0].split("/").pop()??"").replace(/\.[^/.]+$/,"")||"Unknown Track"}catch{return"Unknown Track"}},p=e=>{const t={...e};return v(t._fetchData)&&(v(d._fetchData)&&(t._fetchData={...d._fetchData}),v(e._fetchData)&&(void 0!==e._fetchData.common&&(t._fetchData.common=e._fetchData.common),void 0!==e._fetchData.native&&(t._fetchData.native=e._fetchData.native),void 0!==e._fetchData.format&&(t._fetchData.format=e._fetchData.format),void 0!==e._fetchData.quality&&(t._fetchData.quality=e._fetchData.quality))),t},f={...c,...p(t),...d,...p(r),title:d.title||r.title||m(l),artist:d.artist||r.artist||("string"==typeof o?o:String(o()))};return s.onProgress&&s.onProgress({status:"success",stage:"COMPLETE",url:l}),f}catch(e){if(e instanceof Qt)throw e;const t=new Qt(e instanceof Error?e.message:"UNKNOWN ERROR",l,"INITIALIZING");throw u(t,"INITIALIZING"),t}},ar=le("TinyAfterScrollWatcher"),lr=class{#ot;get scrollTarget(){return ar(this.#u),this.#ot}#at=null;#lt=[];get afterScrollQueueSize(){return ar(this.#u),this.#lt.length}#ht=100;#ut=new Set;#ct=new Set;#u=!1;get destroyed(){return this.#u}constructor(e,t=100){if(!(e instanceof Element||e instanceof Window))throw new TypeError("scrollTarget must be an Element or the Window object.");this.#ot=e,this._checkTimer=this._checkTimer.bind(this),this.#ot.addEventListener("scroll",this._checkTimer),this.#ht=t}_checkTimer=()=>{this.#at&&clearTimeout(this.#at),this.#at=setTimeout(()=>{this.#at=null,this.#dt()},this.#ht)};get inactivityTime(){return ar(this.#u),this.#ht}set inactivityTime(e){if(ar(this.#u),"number"!=typeof e||e<=0||!Number.isFinite(e))throw new Error("inactivityTime must be a positive number in milliseconds.");this.#ht=e}#dt(){if(!this.#u){for(const e of this.#ct)"function"==typeof e&&e();for(;this.#lt.length;){const e=this.#lt.pop();"function"==typeof e&&e()}}}doAfterScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.lastScrollTime=Date.now(),this.#lt.push(e)}onStop(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ct.add(e)}offStop(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ct.delete(e)}onScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ot.addEventListener("scroll",e),this.#ut.add(e)}offScroll(e){if(ar(this.#u),"function"!=typeof e)throw new TypeError("Argument must be a function.");this.#ut.has(e)&&(this.#ot.removeEventListener("scroll",e),this.#ut.delete(e))}destroy(){if(!this.#u){this.#ot.removeEventListener("scroll",this._checkTimer);for(const e of this.#ut)this.#ot.removeEventListener("scroll",e);this.#ut.clear(),this.#ct.clear(),this.#u=!0}}},hr=le("UltraRandomMsgGen"),ur=["lorem","ipsum","dolor","sit","amet","consectetur","adipiscing","elit","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua"],cr=["😂","🌈","🤖","💥","🐸","🍕","🦄","🧠","🧬","🚀","🫠","💫","🍩","👾","🎉","🥴","🐙","🧃","🪐","🎈","🧸","👻","🥳","🍭","💖","😺","🌮","🪅","🎮","🥓","🍮","🍬","🍓","🍒","🥝","🥑","🍄","🌊","☁️","🌟","🌙","🧚","🐾","🐥","🐼","🐨","🐳","✨","🧁","🌸","🍃","💎","🎐","🎀","🫧","☄️","🛸","🔮"],dr=["pudding","bean","snuggle","bloop","jelly","unicorn","floof","giggle","bubble","muffin","puff","pickle","goblin","waffle","sprinkle","cupcake","fizzle","marshmallow","duckling","sock","cloud","teacup","nugget","gnome","hug","moonbean","crayon","jiggle","glitter","carrot","goober"],mr=["wiggles","bounces","flies","splats","scoots","giggles","wigglesnacks","twirls","boops","pops","sings","hugs","floats","glows","flaps","mlems","dances","puddles","nomnoms","wigglejumps","sniffs","tumbles","slides","chirps","burps","sparkles","waddles","rambles","blinks","mews"],pr=["fluffy","silly","yummy","squishy","wobbly","magical","tiny","sleepy","wiggly","bubbly","glittery","fuzzy","jiggly","sparkly","giggly","crunchy","goofy","soft","mushy","sweet","loopy","floaty","bonkers","chewy","ticklish","dreamy","pastel","cozy","teensy","grumbly"],fr=["Boop!","Wiggle achieved.","Oops, {noun} everywhere!","Tiny {adj} {noun}, big {adj} {noun}.","Snuggle initiated with a {adj} {noun}.","{adj} vibes only, powered by {noun}.","No {noun}, no {noun}.","Bounce first, {verb} later.","Mlem. {verb}. {noun}.","{noun} go brrr and {verb}.","Why not? {noun} did. Then {noun} followed.","A {adj} {noun} just {verb} near the {adj} window.","That {adj} {noun} stole my {noun}!","Look, a {adj} {noun} trying to {verb} again!","Every {noun} deserves a {adj} nap.","The {adj} {noun} is my {adj} spirit animal.","Someone call the {noun}, it’s {verb}ing and {verb}ing again!","Don’t touch the {adj} {noun}. It {verb}s loudly.","{noun} forgot how {noun}s work and just {verb}ed.","There once was a {adj} {noun} who loved to {verb} with a {adj} {noun} all day.","Apparently, {noun}s are banned from {verb}ing and {verb}ing in the {noun} library.","That {adj} noise? Just a {noun} learning to {verb} on a {adj} {noun}.","I saw a {adj} {noun} {verb} so hard, it became a {adj} muffin.","The {adj} {noun} met a {adj} pickle and everything {verb}ed.","{noun}s are like {noun}: {adj}, unpredictable, and wiggly.","Don’t judge a {adj} {noun} by its ability to {verb}, or by its {adj} hat.","All I wanted was peace, but a {adj} {noun} with a {adj} {noun} had other plans.","One {adj} morning, a {adj} {noun} decided it was finally time to {verb}, but halfway through, it tripped on a {noun} and turned into a {adj} marshmallow.","I tried to be {adj} today, but then a {noun} {verb}ed across my {noun} and typed “asdfgh{noun}” repeatedly.","If you think you’ve seen everything, wait until a {adj} {noun} {verb}s on a {noun} wearing {adj} socks with tiny {noun}s.","No one ever believed the stories about the ancient {adj} {noun} who could {verb} with such {adj} grace that entire {noun}s turned pink out of embarrassment.","A curious {adj} {noun} wandered into a {noun} shop, not knowing that its destiny involved twelve {adj} {noun}s, one rubber {noun}, and a suspiciously quiet {adj} llama.","In a land where every {adj} {noun} was made of pudding and the sky was {adj} whipped cream, one brave {adj} {noun} set out to discover the legendary Spoon of {noun}s, facing obstacles like bouncing {noun}s, sassy {noun}s, and the Great Wobble of the {noun}.","Once upon a {adj} time, long before the {noun}s learned to {verb}, there existed a tiny {adj} {noun} who dreamed of swimming in a pool made entirely of {adj} glitter pudding while {verb}ing off-key lullabies to passing {noun}s with monocles.","The Council of {noun}s gathered in {adj} secret when the sacred {adj} {noun} started to {verb} uncontrollably, threatening the entire {adj} dessert-based civilization with spontaneous {noun} jiggles and uncontainable {noun} fits across the {noun}.","Hey... do you ever wonder if {noun}s dream of {noun}s?","Okay but hear me out: what if the {adj} {noun} could actually {verb} backwards?","Can we talk about the {noun} that just {verb}ed and vanished?","So I was talking to a {noun}, and it told me to stop being {adj}. Rude.","Not to alarm you, but there’s a {adj} {noun} behind you doing the {verb}.","Why does this {noun} keep staring at me like I owe it pudding?","Is this a safe space to admit I accidentally {verb}ed a {noun}?","I just walked into the room and someone shouted “{adj} {noun}!” — what did I miss?","Wait... we were supposed to bring a {noun}? No one told me!","Okay but what if the {adj} {noun} has feelings too?","Be honest, do I look like a {noun} that forgot how to {verb}?",'If I say "oops", do I still have to explain why the {noun} is glowing?',"I don’t know what’s going on but I brought snacks and a confused {noun}.","Do you think pudding knows it’s pudding? Just a thought.","Is this about the time I {verb}ed the {adj} {noun} by accident? Because I can explain.","Wait, are we talking about {noun}s or am I on the wrong chat again?",'What is this group even about? I just saw "pudding" and joined.',"Hi! I have no idea what’s happening but I’m here and I brought a {noun}.","I blinked and now there’s a {adj} {noun} in charge of everything.","Can someone please explain why the {noun} is floating and chanting?","Okay who gave the {noun} access to glitter and emotional support pickles?","I came for a calm discussion and now there’s a {adj} battle between {noun}s.","Not sure if I’m early, late, or inside a {noun} dream.","I was gone for 3 minutes and now someone’s riding a {noun} into the pudding realm.","This isn’t the pudding appreciation group, is it? ...oh no.","So... who summoned the {adj} {noun} this time? Be honest.","I came here for vibes and stayed for the {noun}s.","Does anyone else hear faint giggling or is that just the {adj} {noun} again?","I feel like I missed step one, two, and also three of this conversation.","All I asked was “what’s up?” and now I’m emotionally attached to a {noun}.",'Me: "I’ll be normal today." Also me: *{verb}s into a meeting riding a {adj} {noun}*','"It’s just pudding," they said. "It can’t hurt you," they said. They were wrong.',"I said one nice thing to a {noun} and now it follows me everywhere.","Can we take a moment to appreciate how the {adj} {noun} is just vibing?","Who put a tiny hat on the {noun}? Because that’s adorable.","My life has been different ever since the {noun} started {verb}ing.","Raise your hand if you’ve ever been personally attacked by a {adj} {noun}.",'"Don’t be weird," they said. So I became a {noun} instead.',"Do {noun}s have feelings? Asking for a {adj} friend.","I trusted the {noun} and all I got was a glitter-covered sock.","Plot twist: the {adj} {noun} was inside us all along.","In the glow of the {adj} moon, the {noun} began to {verb}.","A sprinkle of {adj} dust made the {noun} {verb} through the air.","The {noun} whispered a {adj} secret that made everyone {verb}.","Everything felt {adj} and {adj}, especially when the {noun} {verb}ed.","The {noun} is {verb}ing! The {noun} is {verb}ing! AAAAA!","Glitch in the {noun}: the {adj} {noun} just {verb}ed out of existence.","The {adj} {noun} {verb} and {verb} all over the {adj} {noun}!","Oops! {noun}s {verb}ed into the {adj} {noun} while {verb}ing crazily.","{adj}, {adj}, and more {adj} {noun}s just {verb}ed by!","Why does the {adj} {noun} keep {verb}ing and {verb}ing without stopping?","Look! A {adj} {noun}, a {adj} {noun}, and a {noun} all {verb}ing together!","Sometimes, the {noun} just {verb}s, then {verb}s again, and never stops being {adj}.","{noun}, {noun}, and {noun} — all {verb}ing and {verb}ing in a {adj} {noun}.","I saw a {adj} {noun} {verb}, then another {noun} {verb}ing with a {adj} {noun}.","The {noun} {verb}s {verb} while the {adj} {noun} {verb}s and the {noun} just {verb}s.","Can a {adj} {noun} {verb} {verb} without a {adj} {noun} watching?","Whoa! The {adj} {noun} just {verb}ed... and then {verb}ed again!","Hey... did you see that {adj} {noun} {verb} over there?","Umm, the {noun} is {verb}ing but also {verb}ing and {verb}ing!","Lol! {noun}s {verb} so {adj}ly, it’s impossible not to giggle.",'"Hey! What’s up?" asked the {adj} {noun}, who {verb}ed loudly.','"I’m just a {adj} {noun} trying to {verb}, you know?"','"Did you see the {adj} {noun} that just {verb}ed in the pudding?"','"No way! The {noun} {verb}s better than me!"','"Wait, the {adj} {noun} said it would {verb}, but it {verb}ed instead!"',"Once upon a {adj} {noun}, a group of {adj} {noun}s {verb}ed through the {adj} forest, singing {adj} songs and eating {noun}s made of pudding.","The legend tells of a {adj} {noun} who could {verb} faster than any {noun} ever seen, leaving trails of {adj} sparkles behind.","Every day, the {adj} {noun} would {verb} around the {adj} meadow, trying to convince the {noun}s to join the grand pudding party.","No one knows why the {adj} {noun} suddenly {verb}ed and then {verb}ed again, but everyone agrees it was the cutest thing they ever saw.","In the kingdom of {adj} {noun}s, only the bravest {noun} dared to {verb} the giant pudding monster, armed with nothing but {adj} smiles and jellybeans.","{adj} {noun} {verb} {verb} {verb} {noun} {verb} {adj} {noun} {verb} {noun}!","{noun} {noun} {verb} {adj} {noun} and then {verb} {verb} the {adj} {noun}.","{verb} the {adj} {noun}, then {verb} the {noun} while {verb}ing {adj}ly.","Can the {adj} {noun} {verb} and {verb} the {adj} {noun} at the same time?","{noun} {verb} {noun} {verb}, but the {adj} {noun} {verb}s better.","Boop! The {adj} {noun} just {verb}ed in the pudding.","Bloop bloop, the {noun} is {verb}ing all over again!","Mlem mlem, a {adj} {noun} {verb}s quietly in the corner.","Splat! {noun} {verb}ed right on the {adj} {noun}.","Yum! A {adj} {noun} just {verb}ed in my mouth.","Do {noun}s really {verb} when nobody’s watching?","Why does the {adj} {noun} always {verb} at midnight?","Can a {noun} be too {adj} to {verb} properly?","Is it normal for a {adj} {noun} to {verb} three times in a row?","Who taught the {noun} to {verb} like that?","Wait, did the {adj} {noun} just {verb} itself?","I can’t believe the {noun} {verb}ed into a {adj} {noun}!","Suddenly, a {adj} {noun} appeared and started to {verb} wildly.","That {noun} was {verb}ing so {adj}ly it broke the pudding meter.","Everyone’s talking about the {adj} {noun} that {verb}ed out of nowhere."];class yr{static#mt=ur;static#pt=cr;static#ft=dr;static#yt=mr;static#gt=pr;static#wt=fr;static#bt(e,t){if(!Array.isArray(e))throw new TypeError(`${t} must be an array of strings`);if(!e.every(e=>"string"==typeof e))throw new TypeError(`${t} must contain only strings`);if(0===e.length)throw new Error(`${t} cannot be empty`)}static get defaultWords(){return[...this.#mt]}static set defaultWords(e){this.#bt(e,"defaultWords"),this.#mt=[...e]}static get defaultEmojis(){return[...this.#pt]}static set defaultEmojis(e){this.#bt(e,"defaultEmojis"),this.#pt=[...e]}static get defaultNouns(){return[...this.#ft]}static set defaultNouns(e){this.#bt(e,"defaultNouns"),this.#ft=[...e]}static get defaultVerbs(){return[...this.#yt]}static set defaultVerbs(e){this.#bt(e,"defaultVerbs"),this.#yt=[...e]}static get defaultAdjectives(){return[...this.#gt]}static set defaultAdjectives(e){this.#bt(e,"defaultAdjectives"),this.#gt=[...e]}static get defaultTemplates(){return[...this.#wt]}static set defaultTemplates(e){this.#bt(e,"defaultTemplates"),this.#wt=[...e]}#u=!1;get destroyed(){return this.#u}#vt={minLength:10,maxLength:300,readable:!0,useEmojis:!0,includeNumbers:!0,includeSymbols:!0,allowWeirdSpacing:!1,emojiSet:[],wordSet:[],mode:"mixed",grammar:{templates:[],nouns:[],verbs:[],adjectives:[]},repeatWords:!0,emojiPlacement:"inline",line:{minLength:20,maxLength:120,emojiChance:.3}};get config(){return hr(this.#u),structuredClone(this.#vt)}#Et="!@#$%^&*()-_=+[]{}|;:,.<>?/\\~".split("");get symbols(){return hr(this.#u),structuredClone(this.#Et)}constructor(e={}){const{minLength:t,maxLength:r,readable:i,useEmojis:s,includeNumbers:n,includeSymbols:o,allowWeirdSpacing:a,emojiSet:l,wordSet:h,mode:u,grammar:c,repeatWords:d,emojiPlacement:m,paragraphs:p,line:f}=e;if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.minLength must be an integer >= 1");if(void 0!==r&&(!Number.isInteger(r)||r<1))throw new TypeError("config.maxLength must be an integer >= 1");if(void 0!==t&&void 0!==r&&t>r)throw new RangeError("config.minLength cannot be greater than config.maxLength");if(void 0!==i&&"boolean"!=typeof i)throw new TypeError("config.readable must be a boolean");if(void 0!==s&&"boolean"!=typeof s)throw new TypeError("config.useEmojis must be a boolean");if(void 0!==n&&"boolean"!=typeof n)throw new TypeError("config.includeNumbers must be a boolean");if(void 0!==o&&"boolean"!=typeof o)throw new TypeError("config.includeSymbols must be a boolean");if(void 0!==a&&"boolean"!=typeof a)throw new TypeError("config.allowWeirdSpacing must be a boolean");if(void 0!==l&&!Array.isArray(l))throw new TypeError("config.emojiSet must be an array of strings");if(void 0!==h&&!Array.isArray(h))throw new TypeError("config.wordSet must be an array of strings");if(void 0!==u&&!["mixed","readable","chaotic","natural"].includes(u))throw new RangeError('config.mode must be one of: "mixed", "readable", "chaotic", "natural');if(void 0!==c){if("object"!=typeof c||null===c)throw new TypeError("config.grammar must be an object");const{templates:e,nouns:t,verbs:r,adjectives:i}=c;if(void 0!==e&&!Array.isArray(e))throw new TypeError("config.grammar.templates must be an array of strings");if(void 0!==t&&!Array.isArray(t))throw new TypeError("config.grammar.nouns must be an array of strings");if(void 0!==r&&!Array.isArray(r))throw new TypeError("config.grammar.verbs must be an array of strings");if(void 0!==i&&!Array.isArray(i))throw new TypeError("config.grammar.adjectives must be an array of strings")}if(void 0!==d&&"boolean"!=typeof d)throw new TypeError("config.repeatWords must be a boolean");if(void 0!==m&&!["inline","end","none"].includes(m))throw new RangeError('config.emojiPlacement must be one of: "inline", "end", "none"');if(void 0!==p){if("object"!=typeof p)throw new TypeError("config.paragraphs must be an object or null");const{min:e,max:t}=p;if(void 0!==e&&(!Number.isInteger(e)||e<1))throw new TypeError("config.paragraphs.min must be an integer >= 1");if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.paragraphs.max must be an integer >= 1");if(void 0!==e&&void 0!==t&&e>t)throw new RangeError("config.paragraphs.min cannot be greater than config.paragraphs.max")}if(void 0!==f){if("object"!=typeof f||null===f)throw new TypeError("config.line must be an object");const{minLength:e,maxLength:t,emojiChance:r}=f;if(void 0!==e&&(!Number.isInteger(e)||e<1))throw new TypeError("config.line.minLength must be an integer >= 1");if(void 0!==t&&(!Number.isInteger(t)||t<1))throw new TypeError("config.line.maxLength must be an integer >= 1");if(void 0!==e&&void 0!==t&&e>t)throw new RangeError("config.line.minLength cannot be greater than config.line.maxLength");if(void 0!==r&&("number"!=typeof r||r<0||r>1))throw new RangeError("config.line.emojiChance must be a number between 0 and 1")}this.#vt.emojiSet=[...yr.#pt],this.#vt.wordSet=[...yr.#mt],this.#vt.grammar.templates=[...yr.#wt],this.#vt.grammar.nouns=[...yr.#ft],this.#vt.grammar.verbs=[...yr.#yt],this.#vt.grammar.adjectives=[...yr.#gt],Object.assign(this.#vt,e)}configure(e={}){return hr(this.#u),Object.assign(this.#vt,e),this}setGrammarTemplates(...e){return hr(this.#u),this.#vt.grammar.templates=e.flat(),this}addGrammarTemplates(...e){return hr(this.#u),this.#vt.grammar.templates.push(...e.flat()),this}setGrammarNouns(...e){return hr(this.#u),this.#vt.grammar.nouns=e.flat(),this}addGrammarNouns(...e){return hr(this.#u),this.#vt.grammar.nouns.push(...e.flat()),this}setGrammarVerbs(...e){return hr(this.#u),this.#vt.grammar.verbs=e.flat(),this}addGrammarVerbs(...e){return hr(this.#u),this.#vt.grammar.verbs.push(...e.flat()),this}setGrammarAdjectives(...e){return hr(this.#u),this.#vt.grammar.adjectives=e.flat(),this}addGrammarAdjectives(...e){return hr(this.#u),this.#vt.grammar.adjectives.push(...e.flat()),this}removeGrammarTemplates(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.templates=this.#vt.grammar.templates.filter(e=>!t.has(e)),this}removeGrammarNouns(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.nouns=this.#vt.grammar.nouns.filter(e=>!t.has(e)),this}removeGrammarVerbs(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.verbs=this.#vt.grammar.verbs.filter(e=>!t.has(e)),this}removeGrammarAdjectives(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.grammar.adjectives=this.#vt.grammar.adjectives.filter(e=>!t.has(e)),this}setWords(...e){return hr(this.#u),this.#vt.wordSet=e.flat(),this}addWords(...e){return hr(this.#u),this.#vt.wordSet.push(...e.flat()),this}removeWords(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.wordSet=this.#vt.wordSet.filter(e=>!t.has(e)),this}setEmojis(...e){return hr(this.#u),this.#vt.emojiSet=e.flat(),this}addEmojis(...e){return hr(this.#u),this.#vt.emojiSet.push(...e.flat()),this}removeEmojis(...e){hr(this.#u);const t=new Set(e.flat());return this.#vt.emojiSet=this.#vt.emojiSet.filter(e=>!t.has(e)),this}_getRandomItem(e){return e[Math.floor(Math.random()*e.length)]}_generateChunk(){const{wordSet:e,emojiSet:t,includeNumbers:r,includeSymbols:i,useEmojis:s,readable:n,mode:o,emojiPlacement:a}=this.#vt;if("natural"===o)return this._generateNaturalSentence();const l=[];return(n||"readable"===o||"mixed"===o)&&l.push(this._getRandomItem(e)),"chaotic"!==o&&"mixed"!==o||l.push(Math.random().toString(36).slice(2)),r&&l.push(Math.floor(99999*Math.random()).toString()),i&&l.push(this._getRandomItem(this.#Et)),"inline"===a&&s&&t.length&&l.push(this._getRandomItem(t)),this._getRandomItem(l)}_generateNaturalSentence(){const{templates:e,nouns:t,verbs:r,adjectives:i}=this.#vt.grammar;return this._getRandomItem(e).replace(/{noun}/g,()=>this._getRandomItem(t)).replace(/{verb}/g,()=>this._getRandomItem(r)).replace(/{adj}/g,()=>this._getRandomItem(i))}_generateLine(e,t){const{allowWeirdSpacing:r,repeatWords:i,readable:s,emojiSet:n,useEmojis:o,emojiPlacement:a,line:l}=this.#vt,h=[];for(t??=new Set;h.join(" ").length<e;){let e=this._generateChunk();!i&&t.has(e)||(t.add(e),r&&(Math.random()<.1&&(e="\n"+e),Math.random()<.1&&(e=" "+e),Math.random()<.05&&(e=e.toUpperCase())),h.push(e))}let u=h.join(s?" ":"");return"end"===a&&o&&n.length&&Math.random()<(l?.emojiChance||0)&&(u+=" "+this._getRandomItem(n)),u}_generateParagraphLines(e){const{line:t}=this.#vt,r=[],i=new Set;let s=0;for(;s<e;){const n=Math.floor(Math.random()*(t.maxLength-t.minLength+1)+t.minLength),o=Math.min(n,e-s);r.push(this._generateLine(o,i)),s+=o}return r}generate(){hr(this.#u);const{minLength:e,maxLength:t,paragraphs:r}=this.#vt,i=Math.floor(Math.random()*(t-e+1))+e;if(r&&"object"==typeof r){const e=Math.floor(Math.random()*(r.max-r.min+1))+r.min,t=Math.floor(i/e),s=[];for(let r=0;r<e;r++){const e=this._generateParagraphLines(t);s.push(e.join("\n"))}return s.join("\n\n")}return this._generateParagraphLines(i).join("\n")}destroy(){this.destroyed||(this.#Et=[],this.#vt.emojiSet=[],this.#vt.wordSet=[],this.#vt.grammar.templates=[],this.#vt.grammar.nouns=[],this.#vt.grammar.verbs=[],this.#vt.grammar.adjectives=[],this.#u=!0)}}const gr=yr;e();const wr=le("TinySmartScroller"),br=e().EventEmitter;class vr extends br{static Utils={...n,TinyHtml:Rt};#Tt=new WeakMap;#St=new WeakMap;#xt=new WeakMap;#At=new WeakMap;#Ct=new WeakMap;#It=new WeakMap;#kt=null;#Dt=null;#Mt=new Set(["IMG","IFRAME","VIDEO"]);#Lt=null;#Nt=!1;#_t=!1;#Rt=!1;#jt=!1;#Pt=!1;#Ot=!1;#$t=!1;#Ht=!1;#Ft="";#zt=!1;#u=!1;#Bt=!1;#Wt=!1;#Ut=!1;#qt=!1;#Vt=0;#Kt=0;#Gt=0;#Jt=0;#Yt=0;#Xt;#Qt;#F;#Zt=new Set;constructor(e,{extraScrollBoundary:t=0,autoScrollBottom:r=!0,observeMutations:i=!0,preserveScrollOnLayoutShift:s=!0,debounceTime:n=100,querySelector:o=null,attributeFilter:a=["class","style","src","data-*","height","width"]}={}){if(super(),!(e instanceof Element||e===window))throw new TypeError("TinySmartScroller: 'target' must be a DOM Element or 'window', but got "+typeof e);if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`TinySmartScroller: 'extraScrollBoundary' must be a valid number, received ${t}`);if("boolean"!=typeof r)throw new TypeError("TinySmartScroller: 'autoScrollBottom' must be a boolean, received "+typeof r);if("boolean"!=typeof i)throw new TypeError("TinySmartScroller: 'observeMutations' must be a boolean, received "+typeof i);if("boolean"!=typeof s)throw new TypeError("TinySmartScroller: 'preserveScrollOnLayoutShift' must be a boolean, received "+typeof s);if("number"!=typeof n||n<0||Number.isNaN(n))throw new TypeError(`TinySmartScroller: 'debounceTime' must be a non-negative number, received ${n}`);if(null!==o&&"string"!=typeof o)throw new TypeError("TinySmartScroller: 'querySelector' must be a string or null, received "+typeof o);if(!(null===a||Array.isArray(a)||a instanceof Set))throw new TypeError("TinySmartScroller: 'attributeFilter' must be an array, Set, or null. Got "+typeof a);let l;this.#F=e,this.#Qt=e instanceof Window?document.documentElement:e,this.#zt=e instanceof Window,this.#Wt=r,this.#Ut=i,this.#qt=s,this.#Vt=n,this.#Yt=t,this.#Ft=o||"",this.#Xt=new Set(a||void 0),this.#Lt=()=>{this._scrollDataUpdater(),clearTimeout(l),l=setTimeout(()=>this._onScroll(),this.#Vt)},(this.#zt?window:this.#Qt).addEventListener("scroll",this.#Lt,{passive:!0}),this.#Ut&&(this._observeMutations(),this._observeResizes(this.#Qt.children)),this._scrollDataUpdater()}getSimpleOnHeight(e=[]){if(wr(this.#u),!Array.isArray(e))throw new TypeError("getSimpleOnHeight(filter): filter must be an array of tag names");return(t,r,i)=>{if(e.length>0&&!e.includes(t.tagName)||i.now!==i.old)return;const s=r.old;return{height:r.now.height-s.height,width:0}}}addSimpleOnHeight(e){if(wr(this.#u),!Array.isArray(e))throw new TypeError("addSimpleOnHeight(filter): filter must be an array of tag names");const t=this.getSimpleOnHeight(e);return this.onSize(t),t}getLoadTags(){return wr(this.#u),Array.from(this.#Mt)}addLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("addLoadTag(tag): tag must be a string");this.#Mt.add(e.toUpperCase())}removeLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("removeLoadTag(tag): tag must be a string");this.#Mt.delete(e.toUpperCase())}hasLoadTag(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("hasLoadTag(tag): tag must be a string");return this.#Mt.has(e.toUpperCase())}resetLoadTags(e=!1){if(wr(this.#u),"boolean"!=typeof e)throw new TypeError("resetLoadTags(addDefault): addDefault must be a boolean");this.#Mt.clear(),e&&(this.#Mt.add("IMG"),this.#Mt.add("IFRAME"),this.#Mt.add("VIDEO"))}getAttributeFilters(){return wr(this.#u),Array.from(this.#Xt)}addAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("addAttributeFilter(attr): attr must be a string");this.#Xt.add(e)}removeAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("removeAttributeFilter(attr): attr must be a string");this.#Xt.delete(e)}hasAttributeFilter(e){if(wr(this.#u),"string"!=typeof e)throw new TypeError("hasAttributeFilter(attr): attr must be a string");return this.#Xt.has(e)}resetAttributeFilters(e=!1){if(wr(this.#u),"boolean"!=typeof e)throw new TypeError("resetAttributeFilters(addDefault): addDefault must be a boolean");this.#Xt.clear(),e&&["class","style","src","data-*","height","width"].forEach(e=>this.#Xt.add(e))}onSize(e){if(wr(this.#u),"function"!=typeof e)throw new TypeError("onSize(handler): handler must be a function");this.#Zt.add(e)}offSize(e){if(wr(this.#u),"function"!=typeof e)throw new TypeError("offSize(handler): handler must be a function");this.#Zt.delete(e)}_scrollDataUpdater(){const e=new Map;return this.#Qt.querySelectorAll(this.#Ft||"*").forEach(t=>{const r=this.#xt.get(t)??!1;this.#At.set(t,r);const i=Rt.isInContainer(this.#Qt,t);this.#xt.set(t,i),e.set(t,{oldIsVisible:r,isVisible:i})}),e}_onScroll(){if(this.#u)return;const e=this._scrollDataUpdater(),t=this.#Qt,r=t.scrollTop,i=t.scrollHeight,s=t.clientHeight,n={scrollTop:r,scrollHeight:i,clientHeight:s};let o=null,a=null;const l=0===r,h=r+s>=i-1,u=r<=0+this.#Yt,c=r+s>=i-1-this.#Yt;l&&h?o="all":l?o="top":h&&(o="bottom"),u&&c?a="all":u?a="top":c&&(a="bottom"),this.#_t=this.#Ot??!1,this.#Nt=this.#Pt??!1,this.#Rt=this.#$t??!1,this.#jt=this.#Ht??!1,this.#Ot=l,this.#Pt=h,this.#$t=u,this.#Ht=c,this.#Bt=!(this.#Wt&&this.#Pt),this.#Jt=i-r-s,this.emit("onScrollBoundary",{status:o,...n,scrollCache:e}),this.emit("onExtraScrollBoundary",{status:a,...n,scrollCache:e}),this.#Bt?this.emit("onScrollPause",{...n,scrollCache:e}):this.emit("onAutoScroll",{...n,scrollCache:e})}_fixScroll(e=[]){if(this.#u)return;if(!Array.isArray(e))throw new TypeError("_fixScroll: targets must be an array of Elements");const t=this.#Qt.scrollHeight,r=this.#Qt.scrollTop,i=this.#Qt.scrollHeight-this.#Qt.scrollTop-this.#Qt.clientHeight,s=this.#Qt.scrollHeight-t,n=()=>{const t={height:0,width:0};for(const r of e){const e=this.#Tt.get(r)||{height:0,width:0},i=this.#St.get(r)||{height:0,width:0};this.#Zt.forEach(s=>{const n=s(r,{old:e,now:i},{old:this.#Gt,now:this.#Kt});if(this.#xt.get(r)||this.#Ct.get(r)){if(void 0!==n&&"object"!=typeof n)throw new Error("_fixScroll: size filter must return an object or undefined");if(void 0===n)return;t.height=n.height,t.width=n.width}})}if("number"!=typeof t.height&&t.height<0)throw new Error("_fixScroll: invalid scrollSize.height value");if("number"!=typeof t.width&&t.width<0)throw new Error("_fixScroll: invalid scrollSize.width value");if(0!==t.height||0!==t.width)for(const t of e)this.#Ct.set(t,this.#xt.get(t)??!1),this.#It.set(t,this.#At.get(t)??!1);return t};if(this.#Gt>0&&Rt.hasScroll(this.#Qt).v&&this.#Wt&&this.#qt&&!this.#Pt&&!this.#Ot){const e=n();this.#Qt.scrollTop=r+s+e.height,e.width>0&&(this.#Qt.scrollLeft=this.#Qt.scrollLeft+e.width)}else!this.#Bt&&this.#Wt?(n(),this.scrollToBottom()):this.#Wt||this.#Pt||(n(),this.#Qt.scrollTop=this.#Qt.scrollHeight-this.#Qt.clientHeight-i)}_observeMutations(){this.#Dt=new MutationObserver(e=>{this.#u||(this._scrollDataUpdater(),this.#Gt=this.#Kt,this.#Kt=this.#Qt.childElementCount,e.forEach(e=>{e.addedNodes.forEach(e=>{if(e instanceof Element&&1===e.nodeType&&(this._observeResizes([e]),this._listenLoadEvents(e),this.#Ft)){const t=e.querySelectorAll(this.#Ft);this._observeResizes(t),this._listenLoadEvents(t)}})}),this._fixScroll())}),this.#Dt.observe(this.#Qt,{childList:!0,subtree:!0,attributes:!0,attributeFilter:this.#Xt.size>0?Array.from(this.#Xt):void 0})}_observeResizes(e){this.#kt||(this.#kt=new ResizeObserver(e=>{if(this.#u)return;this._scrollDataUpdater();const t=[];for(const r of e){const e=r.target,i=this.#St.get(e);i&&this.#Tt.set(e,i);const{width:s,height:n}=r.contentRect;this.#St.set(e,{width:s,height:n}),t.push(e)}this._fixScroll(t)})),Array.from(e).forEach(e=>{if(!this.#kt)throw new Error("_observeResizes: ResizeObserver instance is not initialized");this.#kt.observe(e)})}_listenLoadEvents(e){this.#u||(e instanceof NodeList?Array.from(e):[e]).forEach(e=>{this.#Mt.has(e.tagName)&&(e.complete||e.addEventListener("load",()=>{this._scrollDataUpdater(),!this.#Bt&&this.#Wt&&this.scrollToBottom()}))})}get target(){return this.#F}get targetElement(){return this.#Qt}getOldSize(e){return wr(this.#u),this.#Tt.get(e)??null}getNewSize(e){return wr(this.#u),this.#St.get(e)??null}wasVisible(e){return wr(this.#u),this.#At.get(e)??!1}isVisible(e){return wr(this.#u),this.#xt.get(e)??!1}wasTimedVisible(e){return wr(this.#u),this.#It.get(e)??!1}isTimedVisible(e){return wr(this.#u),this.#Ct.get(e)??!1}setExtraScrollBoundary(e){if(wr(this.#u),"number"!=typeof e||Number.isNaN(e))throw new TypeError("setExtraScrollBoundary(value): value must be a valid number");this.#Yt=e}getExtraScrollBoundary(){return wr(this.#u),this.#Yt}getLastKnownScrollBottomOffset(){return wr(this.#u),this.#Jt}scrollToBottom(){wr(this.#u),this.#Qt.scrollTop=this.#Qt.scrollHeight}scrollToTop(){wr(this.#u),this.#Qt.scrollTop=0}isAtCustomBottom(){return wr(this.#u),this.#Ht}isAtCustomTop(){return wr(this.#u),this.#$t}isAtBottom(){return wr(this.#u),this.#Pt}isAtTop(){return wr(this.#u),this.#Ot}isPastAtBottom(){return wr(this.#u),this.#Nt}isPastAtTop(){return wr(this.#u),this.#_t}isPastAtCustomTop(){return wr(this.#u),this.#Rt}isPastAtCustomBottom(){return wr(this.#u),this.#jt}isScrollPaused(){return wr(this.#u),this.#Bt}isWindow(){return wr(this.#u),this.#zt}isDestroyed(){return this.#u}getAutoScrollBottom(){return wr(this.#u),this.#Wt}getObserveMutations(){return wr(this.#u),this.#Ut}getPreserveScrollOnLayoutShift(){return wr(this.#u),this.#qt}getDebounceTime(){return wr(this.#u),this.#Vt}getElemAmount(){return wr(this.#u),this.#Kt}getPrevElemAmount(){return wr(this.#u),this.#Gt}getQuerySelector(){return wr(this.#u),this.#Ft}destroy(){if(this.#u)return;this.#Dt&&(this.#Dt.disconnect(),this.#Dt=null),this.#kt&&(this.#kt.disconnect(),this.#kt=null);const e=this.#zt?window:this.#Qt;this.#Lt&&e.removeEventListener("scroll",this.#Lt),this.#Tt=new WeakMap,this.#St=new WeakMap,this.#xt=new WeakMap,this.#At=new WeakMap,this.#Ct=new WeakMap,this.#It=new WeakMap,this.removeAllListeners(),this.#Zt.clear(),this.#Mt.clear(),this.#u=!0}}const Er=vr,Tr=class{#J;#er;#tr;constructor(e,{openTag:t="[",closeTag:r="]"}={}){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement))throw new TypeError("Element must be an input or textarea.");if("string"!=typeof t)throw new TypeError("openTag must be a string.");if("string"!=typeof r)throw new TypeError("closeTag must be a string.");this.#J=e,this.#er=t,this.#tr=r}getOpenTag(){return this.#er}getCloseTag(){return this.#tr}setOpenTag(e){if("string"!=typeof e)throw new TypeError("Open tag must be a string.");this.#er=e}setCloseTag(e){if("string"!=typeof e)throw new TypeError("Close tag must be a string.");this.#tr=e}ensureFocus(){return document.activeElement!==this.#J&&this.#J.focus(),this}focus(){return this.#J.focus(),this}getSelectionRange(){return{start:this.#J.selectionStart??NaN,end:this.#J.selectionEnd??NaN}}setSelectionRange(e,t,r=!0){if("number"!=typeof e||"number"!=typeof t)throw new TypeError("start and end must be numbers.");if("boolean"!=typeof r)throw new TypeError("preserveScroll must be a boolean.");const i=this.#J.scrollTop,s=this.#J.scrollLeft;return this.#J.setSelectionRange(e,t),r&&(this.#J.scrollTop=i,this.#J.scrollLeft=s),this}getValue(){return this.#J.value}setValue(e){if("string"!=typeof e)throw new TypeError("Value must be a string.");return this.#J.value=e,this}getSelectedText(){const{start:e,end:t}=this.getSelectionRange();return this.#J.value.slice(e,t)}insertText(e,{newCursor:t="end",autoSpacing:r=!1,autoSpaceLeft:i=r,autoSpaceRight:s=r}={}){if("string"!=typeof e)throw new TypeError("Text must be a string.");if(!["start","end","preserve"].includes(t))throw new TypeError("newCursor must be one of 'start', 'end', or 'preserve'.");if("boolean"!=typeof r)throw new TypeError("autoSpacing must be a boolean.");if("boolean"!=typeof i)throw new TypeError("autoSpaceLeft must be a boolean.");if("boolean"!=typeof s)throw new TypeError("autoSpaceRight must be a boolean.");const{start:n,end:o}=this.getSelectionRange(),a=this.#J.value,l=a[n-1]||"",h=a[o]||"",u=`${i&&l&&!/\s/.test(l)?" ":""}${e}${s&&h&&!/\s/.test(h)?" ":""}`,c=a.slice(0,n)+u+a.slice(o);this.setValue(c);let d=n;return"end"===t?d=n+u.length:"preserve"===t&&(d=n),this.setSelectionRange(d,d),this}deleteSelection(){return this.insertText(""),this}transformSelection(e){if("function"!=typeof e)throw new TypeError("transformer must be a function.");const{start:t}=this.getSelectionRange(),r=e(this.getSelectedText());return this.insertText(r),this.setSelectionRange(t,t+r.length),this}surroundSelection(e,t){if("string"!=typeof e||"string"!=typeof t)throw new TypeError("prefix and suffix must be strings.");const r=this.getSelectedText();return this.insertText(`${e}${r}${t}`),this}moveCaret(e){if("number"!=typeof e)throw new TypeError("offset must be a number.");const{start:t}=this.getSelectionRange(),r=Math.max(0,t+e);return this.setSelectionRange(r,r),this}selectAll(){return this.setSelectionRange(0,this.#J.value.length),this}expandSelection(e,t){if("number"!=typeof e||"number"!=typeof t)throw new TypeError("before and after must be numbers.");const{start:r,end:i}=this.getSelectionRange(),s=Math.max(0,r-e),n=Math.min(this.#J.value.length,i+t);return this.setSelectionRange(s,n),this}replaceAll(e,t){if(!(e instanceof RegExp))throw new TypeError("regex must be a RegExp.");if("function"!=typeof t)throw new TypeError("replacer must be a function.");const r=this.#J.value.replace(e,t);return this.setValue(r),this}replaceInSelection(e,t){if(!(e instanceof RegExp))throw new TypeError("regex must be a RegExp.");if("function"!=typeof t)throw new TypeError("replacer must be a function.");const{start:r,end:i}=this.getSelectionRange(),s=this.#J.value,n=s.slice(r,i).replace(e,t),o=s.slice(0,r)+n+s.slice(i);return this.setValue(o),this.setSelectionRange(r,r+n.length),this}toggleCode(e){if("string"!=typeof e)throw new TypeError("codeName must be a string.");const t=this.getSelectedText();if(t.startsWith(e)&&t.endsWith(e)){const r=t.slice(e.length,t.length-e.length);this.insertText(r)}else this.insertText(`${e}${t}${e}`);return this}_insertAttr(e){let t="";if(Array.isArray(e)){if(!e.every(e=>"string"==typeof e))throw new TypeError("All entries in attributes array must be strings.");t=e.map(e=>`${e}`).join(" ")}else{if("object"!=typeof e||null===e)throw new TypeError("attributes must be an object or an array of strings.");t=Object.entries(e).map(([e,t])=>{if("string"!=typeof t)throw new TypeError("All entries in attributes object must be strings.");return`${e}${t.length>0?`="${t}"`:""}`}).join(" ")}return t}wrapWithTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this._insertAttr(t),i=r?`${this.#er}${e} ${r}${this.#tr}`:`${this.#er}${e}${this.#tr}`,s=`${this.#er}/${e}${this.#tr}`;return this.surroundSelection(i,s),this}insertTag(e,t="",r={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");if("string"!=typeof t)throw new TypeError("content must be a string.");const i=this._insertAttr(r),s=i?`${this.#er}${e} ${i}${this.#tr}`:`${this.#er}${e}${this.#tr}`,n=`${this.#er}/${e}${this.#tr}`;return this.insertText(`${s}${t}${n}`),this}insertSelfClosingTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this._insertAttr(t),i=r?`${this.#er}${e} ${r}${this.#tr}`:`${this.#er}${e}${this.#tr}`;return this.insertText(i),this}toggleTag(e,t={}){if("string"!=typeof e)throw new TypeError("tagName must be a string.");const r=this.getSelectedText(),i=new RegExp(`^\\[${e}(\\s+[^\\]]*)?\\]`),s=new RegExp(`\\[/${e}\\]$`),n=i.test(r),o=s.test(r);if(n&&o){const e=r.replace(i,"").replace(s,"");this.insertText(e)}else{const i=this._insertAttr(t),s=i?`${this.#er}${e} ${i}${this.#tr}`:`${this.#er}${e}${this.#tr}`,n=`${this.#er}/${e}${this.#tr}`;this.insertText(`${s}${r}${n}`)}return this}},Sr=class{#rr=!1;#ir=!1;#sr=null;#nr=null;constructor(){void 0!==navigator.clipboard&&null!==navigator.clipboard&&(this.#ir=!0,this.#sr=e=>navigator.clipboard.writeText(e),this.#nr=e=>navigator.clipboard.write([new ClipboardItem({[e.type]:e})])),this.#rr=void 0!==document.execCommand&&null!==document.execCommand}setCopyText(e){if("function"!=typeof e)throw new TypeError("setCopyText expected a function that returns Promise<void>.");this.#sr=e}setCopyBlob(e){if("function"!=typeof e)throw new TypeError("setCopyBlob expected a function that returns Promise<void>.");this.#nr=e}copyText(e){if("string"!=typeof e)throw new TypeError("copyText expected a string.");if(this.#sr)return this.#sr(e);if(this.#rr){const t=document.body,r=document.createElement("input");return r.style.position="fixed",r.style.opacity="0",r.value=e,t.append(r),r.select(),r.setSelectionRange(0,99999),document.execCommand("Copy"),r.remove(),new Promise(e=>e(void 0))}throw new Error("Clipboard API not found!")}copyBlob(e){if(!(e instanceof Blob))throw new TypeError("copyBlob expected a Blob instance.");return new Promise((t,r)=>{if(this.#nr)return this.#nr(e).then(t).catch(r);throw new Error("Clipboard API not found!")})}_handleBlob(e,t){return t.getType(e)}_handleText(e,t){return this._handleBlob(e,t).then(e=>e.text())}_readData(e=0,t=null,r=null,i=!1){return new Promise((s,n)=>{this._read(e).then(o=>{if(!o)return s(null);const a=[];let l=!0;const h=async(e,s)=>{if(l)if(null!==t&&"custom"!==t||"string"!=typeof r||!(!i&&e.startsWith(r)||i&&e===r))if(null!==t&&"text"!==t||"text/plain"!==e){if(null===t){l=!1;const t=await this._handleBlob(e,s);t&&a.push(t)}}else{l=!1;const t=await this._handleText(e,s);t&&a.push(t)}else{l=!1;const t=await this._handleBlob(e,s);t&&a.push(t)}},u=[],c=e=>{if(!(e instanceof ClipboardItem))throw new Error("Expected ClipboardItem when reading data.");for(const t in e.types)u.push(h(e.types[t],e))};if("number"==typeof e&&!Number.isNaN(e)&&Number.isFinite(e)&&e>-1)c(o),Promise.all(u).then(()=>{a[0]?s(a[0]):s(null)}).catch(n);else if(Array.isArray(o)){for(const e in o)c(o[e]);Promise.all(u).then(()=>s(a)).catch(n)}}).catch(n)})}async readText(e=0){const t=await this._readData(e,"text");if("string"!=typeof t)throw new Error("Failed to read text: expected string result.");return t}async readCustom(e=null,t=!1,r=0){const i=await this._readData(r,"custom",e,t);if(!(i instanceof Blob))throw new Error("Failed to read custom data: expected Blob.");return i}async readAllTexts(){const e=await this._readData(null,"text");if(!Array.isArray(e))throw new Error("Expected array of strings when reading all texts.");if(!e.every(e=>"string"==typeof e))throw new Error("Some values returned were not strings.");return e}async readAllCustom(e=null,t=!1){const r=await this._readData(null,"custom",e,t);if(!Array.isArray(r))throw new Error("Expected array of blobs when reading all custom items.");if(!r.every(e=>e instanceof Blob))throw new Error("Some values returned were not Blob instances.");return r}async readAllData(e=null,t=null){const r=await this._readData(null,e,t);if(!Array.isArray(r))throw new Error("Expected array result when reading all data.");return r}_read(e){return new Promise((t,r)=>{this.#ir||r(new Error("Clipboard API not found!")),navigator.clipboard.read().then(r=>{if("number"==typeof e){if(Number.isNaN(e)||!Number.isFinite(e)||e<0)throw new Error(`Invalid index value: ${e}`);r[e]?t(r[e]):t(null)}t(r)}).catch(r)})}async readIndex(e){const t=await this._read(e);if(null!==t&&!(t instanceof ClipboardItem))throw new Error(`Value at index ${e} is not a ClipboardItem.`);return t}async readAll(){const e=await this._read(null);if(!Array.isArray(e))throw new Error("Expected array result from clipboard read.");for(const t of e)if(!(t instanceof ClipboardItem))throw new Error("Invalid item type found in clipboard result.");return e}isExecCommandAvailable(){return this.#rr}isNavigatorClipboardAvailable(){return this.#ir}getCopyTextFunc(){return this.#sr}getCopyBlobFunc(){return this.#nr}};class xr{static _rca(e,t,r){let i=127,s=128;void 0===e&&(e=24),void 0===t&&(t="rgb"),!0===r&&(i=55,s=200);const n=2*Math.PI/e,o=[];for(let r=0;r<e;++r){const e=Math.sin(n*r+2)*i+s,a=Math.sin(n*r+0)*i+s,l=Math.sin(n*r+4)*i+s;switch(t){case"hex":o.push({hex:this.rgbToHex(Math.round(e),Math.round(a),Math.round(l))});break;case"rgb":o.push({r:e,g:a,b:l});break;case"hsl":const[t,r,i]=this.rgbaToHsl(Math.round(e),Math.round(a),Math.round(l));o.push({h:t,s:r,l:i})}}return o}static rcaRgb(e,t){return xr._rca(e,"rgb",t)}static rcaHsl(e,t){return xr._rca(e,"hsl",t)}static rcaHex(e,t){return xr._rca(e,"hex",t)}static randomColor(){return`#${Math.floor(16777216*Math.random()).toString(16).padStart(6,"0")}`}static parseInput(e,t){if("string"==typeof e){if((e=e.trim().toLowerCase()).startsWith("#"))return this.hexToRgba(e);if(e.startsWith("rgb"))return this.rgbStringToRgbaArray(e);if(e.startsWith("hsl"))return this.hslStringToRgbaArray(e)}if("number"==typeof e)return this.intToRgba(e);if(Array.isArray(e)&&(3===e.length||4===e.length)&&e.every(e=>"number"==typeof e)){if(t){const[t,r,i,s]=e;if(t<=360&&r<=100&&i<=100)return this.hslToRgba(t,r,i,s)}return[...e,1].slice(0,4)}throw new Error("Unsupported color format.")}static hslToInt(e,t,r){const[i,s,n]=xr.hslToRgba(e,t,r);return xr.rgbToInt(i,s,n)}static hslToHex(e,t,r){const[i,s,n]=xr.hslToRgba(e,t,r);return xr.rgbToHex(i,s,n)}static hslStringToRgbaArray(e){const t=e.match(/[\d.]+/g)?.map(Number);if(!t||t.length<3)return[0,0,0,1];const[r,i,s,n=1]=t;return this.hslToRgba(r,i,s,n)}static hslToRgba(e,t,r,i=1){r/=100;const s=t=>(t+e/30)%12,n=(t/=100)*Math.min(r,1-r),o=e=>r-n*Math.max(-1,Math.min(s(e)-3,Math.min(9-s(e),1)));return[Math.round(255*o(0)),Math.round(255*o(8)),Math.round(255*o(4)),i]}static hslToRgb(e,t,r,i=1){return xr.hslToRgba(e,t,r,i).slice(0,3)}static hexToInt(e){return parseInt(e.replace(/^#/,""),16)}static hexToHsl(e){const[t,r,i,s]=xr.hexToRgba(e);return xr.rgbaToHsl(t,r,i,s)}static hexToHsla(e){const[t,r,i,s]=xr.hexToRgba(e);return xr.rgbaToHsla(t,r,i,s)}static hexToRgba(e){3===(e=e.replace(/^#/,"")).length&&(e=e.split("").map(e=>e+e).join(""));const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t,1]}static hexToRgb(e){return this.hexToRgba(e).slice(0,3)}static rgbToHex(e,t,r){return"#"+[e,t,r].map(e=>e.toString(16).padStart(2,"0")).join("")}static rgbToInt(e,t,r){return e<<16|t<<8|r}static rgbaToHsla(e,t,r,i=1){e/=255,t/=255,r/=255;const s=Math.max(e,t,r),n=Math.min(e,t,r);let o=0,a=0,l=(s+n)/2;const h=s-n;if(0!==h){switch(a=h/(1-Math.abs(2*l-1)),s){case e:o=(t-r)/h+(t<r?6:0);break;case t:o=(r-e)/h+2;break;case r:o=(e-t)/h+4}o*=60}return[Math.round(o),Math.round(100*a),Math.round(100*l),i]}static rgbaToHsl(e,t,r,i){return this.rgbaToHsla(e,t,r,i).slice(0,3)}static rgbStringToRgbaArray(e){const t=e.match(/[\d.]+/g)?.map(Number);return t?[...t,1].slice(0,4):[]}static intToHsl(e){const[t,r,i,s]=xr.intToRgba(e);return xr.rgbaToHsl(t,r,i,s)}static intToHsla(e){const[t,r,i,s]=xr.intToRgba(e);return xr.rgbaToHsla(t,r,i,s)}static intToHex(e){return"#"+e.toString(16).padStart(6,"0")}static intToRgba(e){return[e>>16&255,e>>8&255,255&e,1]}#or="#000000";#ar=[0,0,0,0];#lr;constructor(e=null,t=!1){this.#lr=t,null!=e&&this.setColor(e)}setColor(e){this.#or=e;const t=this.#lr&&Array.isArray(e)&&e[0]<=360&&e[1]<=100&&e[2]<=100;this.#ar=xr.parseInput(e,t)}toHslaArray(){const[e,t,r,i]=this.#ar;return xr.rgbaToHsla(e,t,r,i)}toHslString(){const[e,t,r]=this.#ar,[i,s,n]=xr.rgbaToHsl(e,t,r);return`hsl(${i}, ${s}%, ${n}%)`}toHslaString(){const[e,t,r,i]=this.#ar,[s,n,o,a]=xr.rgbaToHsla(e,t,r,i);return`hsla(${s}, ${n}%, ${o}%, ${a??1})`}toRgbaArray(){return[...this.#ar]}toRgbString(){const[e,t,r]=this.#ar;return`rgb(${e}, ${t}, ${r})`}toRgbaString(){const[e,t,r,i]=this.#ar;return`rgba(${e}, ${t}, ${r}, ${i??1})`}toHex(){const[e,t,r]=this.#ar;return xr.rgbToHex(e,t,r)}toInt(){const[e,t,r]=this.#ar;return xr.rgbToInt(e,t,r)}getOriginal(){return this.#or}}const Ar=xr,Cr=(e,t=100)=>{if("function"!=typeof e)throw new TypeError("Expected 'getValue' to be a function.");if(!Number.isFinite(t)||t<=0)throw new TypeError("Expected 'checkInterval' to be a positive number.");return new Promise(r=>{const i=setInterval(()=>{e()&&(clearInterval(i),r())},t)})},Ir=(e,t=!0)=>{if("function"!=typeof e)throw new TypeError('The argument "baseFunction" must be a function.');let r=null;const i={ended:!1,failed:!1,loading:!1};return{callback:async(...s)=>(null!==r||(i.loading=!0,r=(async()=>{try{const n=await e(...s);return i.ended=!0,i.failed=!1,i.loading=!1,t&&(r=null),n}catch(e){throw i.ended=!0,i.failed=!0,i.loading=!1,t&&(r=null),e}})()),r),getActivePromise:()=>r,resetActivePromise:()=>{i.ended=!1,i.failed=!1,i.loading=!1,r=null},isEnded:()=>i.ended,isFailed:()=>i.failed,isLoading:()=>i.loading}},kr=le("TinyTimeout"),Dr=class{#hr=!1;#ur;#cr;#dr=null;#mr=new Map;constructor({cooldownWatcherTime:e=5e3,allowAutoConfigChange:t=!1}={}){if(!Number.isFinite(e)||e<=0)throw new TypeError("Expected 'cooldownWatcherTime' to be a positive number.");if("boolean"!=typeof t)throw new TypeError("Expected 'allowAutoConfigChange' to be a boolean.");this.#cr=e,this.#ur=t,this.setCooldownWatcherTime(e)}isDestroyed(){return this.#hr}getAllowAutoConfigChange(){return kr(this.#hr),this.#ur}getCooldownWatcherTime(){return kr(this.#hr),this.#cr}setAllowAutoConfigChange(e){if(kr(this.#hr),"boolean"!=typeof e)throw new TypeError("Expected 'value' to be a boolean.");this.#ur=e}setCooldownWatcherTime(e){if(kr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if(!Number.isFinite(e)||e<=0)throw new TypeError("Expected 'value' to be a positive number.");this.#cr=e,this.#dr&&clearInterval(this.#dr),this.#dr=setInterval(()=>{this.#mr.forEach(e=>{e.now>0&&e.now--})},this.#cr)}set(e,t,r,i=null){if(kr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if("string"!=typeof e||""===e.trim())throw new TypeError("Expected 'id' to be a non-empty string.");if("function"!=typeof t)throw new TypeError("Expected 'callback' to be a function.");if(!Number.isFinite(r)||r<0)throw new TypeError("Expected 'value' to be a non-negative number.");if(null!==i&&(!Number.isFinite(i)||i<0))throw new TypeError("Expected 'limit' to be null or a non-negative number.");let s=this.#mr.get(e);(!s||this.#ur&&r!==s.value)&&(s={value:r,now:0},this.#mr.set(e,s));const n=s.value*s.now;return s.now++,setTimeout(t,"number"==typeof i?Math.min(n,i):n)}waitForTrue(e,t=100){if(kr(this.#hr),this.#hr)throw new Error("TinyTimeout has been destroyed.");if("function"!=typeof e)throw new TypeError("Expected 'getValue' to be a function.");if(null!==t&&(!Number.isFinite(t)||t<=0))throw new TypeError("Expected 'checkInterval' to be null or a positive number.");return Cr(e,t??this.#cr)}destroy(){this.#hr||(this.#dr&&clearInterval(this.#dr),this.#dr=null,this.#mr.clear(),this.#hr=!0)}},Mr=le("TinyLocalStorage"),Lr=new Map,Nr=new Map,_r=new Set(["string","boolean","object","array",String,Boolean,Number,Object,Array,BigInt,Symbol]),Rr=e().EventEmitter;class jr extends Rr{static hasJsonType(e){return Lr.has(e)&&Nr.has(e)||_r.has(e)}static registerJsonType(e,t,r,i=!1){if(_r.has(e))throw new Error(`Cannot register type "${e}" because it is frozen.`);Lr.set(e,t),Nr.set(e,r),i&&_r.add(e)}static deleteJsonType(e){if(_r.has(e))throw new Error(`Cannot remove type "${e}" because it is frozen.`);let t=!1;return Lr.delete(e)&&(t=!0),Nr.delete(e)&&(t=!0),t}static encodeSpecialJson(e){if(void 0===e)return{__undefined__:!0};if(null===e)return{__null__:!0};for(const[t,r]of Lr.entries())if("string"!=typeof t&&e instanceof t||typeof e===t)return r(e,jr.encodeSpecialJson);if(Array.isArray(e))return e.map(jr.encodeSpecialJson);if(v(e)){const t={};for(const r in e)t[r]=jr.encodeSpecialJson(e[r]);return t}return e}static decodeSpecialJson(e){const t=v(e);if(t){if(e.__undefined__)return;if(e.__null__)return null}if(Array.isArray(e))return e.map(jr.decodeSpecialJson);if(t){for(const[t,r]of Nr.entries())if(r.check&&r.check(e))return r.decode(e,jr.decodeSpecialJson);const t={};for(const r in e)t[r]=jr.decodeSpecialJson(e[r]);return t}return e}#u=!1;get destroyed(){return this.#u}#pr=window.localStorage;#fr=null;#ee=0;#yr=e=>this.emit("storage",e);constructor(e){if(super(),void 0!==e&&"string"!=typeof e)throw new TypeError("TinyLocalStorage: dbName must be a string if provided.");"string"==typeof e&&(this.#fr=`LSDB::${e}`),window.addEventListener("storage",this.#yr)}#gr(e){if("string"==typeof e&&e.startsWith("LSDB::"))throw new Error(`TinyLocalStorage: Key "${e}" may conflict with reserved dbKeys.`)}updateStorageVersion(e,t){if(Mr(this.#u),"string"!=typeof this.#fr)throw new Error("TinyLocalStorage: Database key is not initialized. Set a valid dbName in the constructor.");if("number"!=typeof e||Number.isNaN(e)||e<1)throw new TypeError("TinyLocalStorage: version must be a positive number.");if("function"!=typeof t)throw new TypeError("TinyLocalStorage: onUpgrade must be a function.");const r=parseInt(localStorage.getItem(this.#fr),10)||0;if("number"!=typeof r||Number.isNaN(r)||r<0)throw new TypeError("TinyLocalStorage: saved version in localStorage is not a valid number.");if(e<r)throw new Error(`TinyLocalStorage: Cannot downgrade database version from ${r} to ${e}.`);e>r&&(t(r,e),localStorage.setItem(this.#fr,String(e)),this.#ee=e)}getDbKey(){return Mr(this.#u),this.#fr}getVersion(){return Mr(this.#u),this.#ee}setLocalStorage(e){if(Mr(this.#u),!(e instanceof Storage))throw new TypeError("Argument must be a valid instance of Storage.");this.#pr=e}localStorageExists(){return Mr(this.#u),this.#pr instanceof Storage}#wr(e,t){if("string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return jr.encodeSpecialJson(t)}setJson(e,t){if(Mr(this.#u),this.#gr(e),!(v(t)||Array.isArray(t)||t instanceof Map||t instanceof Set))throw new TypeError("The storage value is not a valid JSON-compatible structure.");const r=this.#wr(e,t);return this.emit("setJson",e,t),this.#pr.setItem(e,JSON.stringify(r))}#br(e,t){if("string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");const r=this.#pr.getItem(e),i={obj:()=>({}),array:()=>[],map:()=>new Map,set:()=>new Set},s="function"==typeof i[t]?i[t]():null;let n;try{n=JSON.parse(r)}catch{return s}return{decoded:jr.decodeSpecialJson(n),fallback:s}}getJson(e,t){Mr(this.#u);const{decoded:r,fallback:i}=this.#br(e,t);return r instanceof Map||r instanceof Set||Array.isArray(r)||v(r)?r:i}setDate(e,t){if(Mr(this.#u),this.#gr(e),!(t instanceof Date))throw new TypeError("Value must be a Date.");const r=this.#wr(e,t);return this.emit("setDate",e,t),this.#pr.setItem(e,JSON.stringify(r))}getDate(e){Mr(this.#u);const t=this.#br(e).decoded;return t instanceof Date?t:null}setRegExp(e,t){if(Mr(this.#u),this.#gr(e),!(t instanceof RegExp))throw new TypeError("Value must be a RegExp.");const r=this.#wr(e,t);return this.emit("setRegExp",e,t),this.#pr.setItem(e,JSON.stringify(r))}getRegExp(e){Mr(this.#u);const t=this.#br(e).decoded;return t instanceof RegExp?t:null}setBigInt(e,t){if(Mr(this.#u),this.#gr(e),"bigint"!=typeof t)throw new TypeError("Value must be a BigInt.");const r=this.#wr(e,t);return this.emit("setBigInt",e,t),this.#pr.setItem(e,JSON.stringify(r))}getBigInt(e){Mr(this.#u);const t=this.#br(e).decoded;return"bigint"==typeof t?t:null}setSymbol(e,t){if(Mr(this.#u),this.#gr(e),"symbol"!=typeof t)throw new TypeError("Value must be a Symbol.");const r=this.#wr(e,t);return this.emit("setSymbol",e,t),this.#pr.setItem(e,JSON.stringify(r))}getSymbol(e){Mr(this.#u);const t=this.#br(e).decoded;return"symbol"==typeof t?t:null}getValue(e){return Mr(this.#u),this.#br(e).decoded??null}setItem(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.emit("setItem",e,t),this.#pr.setItem(e,t)}getItem(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.#pr.getItem(e)}setString(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("string"!=typeof t)throw new TypeError("Value must be a string.");return this.emit("setString",e,t),this.#pr.setItem(e,JSON.stringify({__string__:!0,value:t}))}getString(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");let t=this.#pr.getItem(e);try{if(t=JSON.parse(t),!v(t)||!t.__string__||"string"!=typeof t.value)return null;t=t.value}catch{t=null}return"string"==typeof t?t:null}setNumber(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("number"!=typeof t)throw new TypeError("Value must be a number.");return this.emit("setNumber",e,t),this.#pr.setItem(e,String(t))}getNumber(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");let t=this.#pr.getItem(e);return"number"==typeof t||"string"==typeof t&&t.length>0&&(t=parseFloat(t),!Number.isNaN(t))?t:null}setBool(e,t){if(Mr(this.#u),this.#gr(e),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");if("boolean"!=typeof t)throw new TypeError("Value must be a boolean.");return this.emit("setBool",e,t),this.#pr.setItem(e,String(t))}getBool(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");const t=this.#pr.getItem(e);if("boolean"==typeof t)return t;if("string"==typeof t){if("true"===t)return!0;if("false"===t)return!1}return null}removeItem(e){if(Mr(this.#u),"string"!=typeof e||!e.length)throw new TypeError("Key must be a non-empty string.");return this.emit("removeItem",e),this.#pr.removeItem(e)}clearLocalStorage(){return Mr(this.#u),this.#pr.clear()}destroy(){this.#u||(window.removeEventListener("storage",this.#yr),this.removeAllListeners(),this.#u=!0)}}jr.registerJsonType(Map,(e,t)=>({__map__:!0,data:Array.from(e.entries()).map(([e,r])=>[e,t(r)])}),{check:e=>e.__map__,decode:(e,t)=>new Map(e.data.map(([e,r])=>[e,t(r)]))},!0),jr.registerJsonType(Set,(e,t)=>({__set__:!0,data:Array.from(e).map(t)}),{check:e=>e.__set__,decode:(e,t)=>new Set(e.data.map(t))},!0),jr.registerJsonType(Date,e=>({__date__:!0,value:e.toISOString()}),{check:e=>e.__date__,decode:e=>new Date(e.value)},!0),jr.registerJsonType(RegExp,e=>({__regexp__:!0,source:e.source,flags:e.flags}),{check:e=>e.__regexp__,decode:e=>new RegExp(e.source,e.flags)},!0),jr.registerJsonType("number",e=>({__number__:!0,value:e.toString()}),{check:e=>e.__number__,decode:e=>Number(e.value)},!0),jr.registerJsonType("bigint",e=>({__bigint__:!0,value:e.toString()}),{check:e=>e.__bigint__,decode:e=>BigInt(e.value)},!0),jr.registerJsonType("symbol",e=>({__symbol__:!0,key:Symbol.keyFor(e)??e.description??null}),{check:e=>e.__symbol__,decode:e=>{const t=e.key;return null!=t?Symbol.for(t):Symbol()}},!0);const Pr=jr,Or=le("TinyIframeEvents"),$r=new WeakMap,Hr=e().EventEmitter,Fr=class extends Hr{#vr;get targetWindow(){return Or(this.#hr),this.#vr}#Er;get targetIframeElement(){return Or(this.#hr),this.#Er}#Tr;get targetOrigin(){return Or(this.#hr),this.#Tr}#Sr;get selfType(){return Or(this.#hr),this.#Sr}#hr=!1;#xr=!1;get ready(){return Or(this.#hr),this.#xr}onReady(e){Or(this.#hr),this.#xr?e():this.once(this.#Ar,e)}#Cr=null;#Ir=[];#kr;#Dr;#Ar;#Mr=null;constructor({targetIframe:e,targetOrigin:t=window.location.origin,secretEventName:r="__tinyIframeEvent__",handshakeEventName:i="__tinyIframeHandshake__",readyEventName:s="__tinyIframeReady__"}={}){if(super(),!(void 0===e||e instanceof HTMLIFrameElement&&e.contentWindow))throw new TypeError('[TinyIframeEvents] Invalid "targetIframe": expected HTMLIFrameElement, received '+typeof e);if("string"!=typeof t)throw new TypeError('[TinyIframeEvents] Invalid "targetOrigin": expected string, received '+typeof t);if(this.#Er=e,this.#vr=e?.contentWindow??window.parent,this.#Tr=t,this.#Sr=e?"parent":"iframe",this.#kr=r,this.#Dr=i,this.#Ar=s,$r.has(this.#vr))throw new Error("Duplicate window reference.");this._boundWindowMessage=this.#Lr.bind(this),this._boundPortMessage=this.#Nr.bind(this),this.#_r(),$r.set(this.#vr,this)}get secretEventName(){return Or(this.#hr),this.#kr}set secretEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: secretEventName must be a string.");this.#kr=e}get handshakeEventName(){return Or(this.#hr),this.#Dr}set handshakeEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: handshakeEventName must be a string.");this.#Dr=e}get readyEventName(){return Or(this.#hr),this.#Ar}set readyEventName(e){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("TinyIframeEvents: readyEventName must be a string.");this.#Ar=e}#_r(){"parent"===this.#Sr?(this.#Mr=()=>{if(this.#hr)return;this.#Cr&&this.#Cr.close();const e=new MessageChannel;this.#Cr=e.port1,this.#Cr.onmessage=this._boundPortMessage,this.#xr=!1,this.#vr.postMessage({type:this.#Dr},this.#Tr,[e.port2])},this.#Er&&(this.#Er.addEventListener("load",this.#Mr),this.#Mr())):window.addEventListener("message",this._boundWindowMessage,!1)}#Lr(e){const t=e.data,r=e.ports;v(t)&&t.type===this.#Dr&&0!==r.length&&(this.#Cr=r[0],this.#Cr.onmessage=this._boundPortMessage,window.removeEventListener("message",this._boundWindowMessage),this.#Cr.postMessage({type:`${this.#Dr}_ACK`}),this.#Rr())}#Nr(e){const t=e.data;if(v(t)&&t.type===`${this.#Dr}_ACK`)return void this.#Rr();if(!v(t)||!t[this.#kr])return;const r=t.eventName,i=t.payload,s=t.direction;"string"!=typeof r||"iframe"===this.#Sr&&"iframe"!==s||"parent"===this.#Sr&&"parent"!==s||this.emit(`win:${r}`,i,e)}#Rr(){this.#xr||(this.#xr=!0,this.#jr(),this.emit(this.#Ar))}#jr(){for(;this.#Ir.length>0;){const e=this.#Ir.shift();e&&this.#Cr&&this.#Cr.postMessage(e)}}winEmit(e,t){if(Or(this.#hr),"string"!=typeof e)throw new TypeError("Event name must be a string.");if(this.#hr)throw new Error("Cannot emit: instance has been destroyed.");const r={[this.#kr]:!0,eventName:e,payload:t,direction:"parent"===this.#Sr?"iframe":"parent"};this.#xr&&this.#Cr?this.#Cr.postMessage(r):this.#Ir.push(r)}isDestroyed(){return this.#hr}destroy(){this.#hr||(this.#xr=!1,window.removeEventListener("message",this._boundWindowMessage),this.#Er&&this.#Mr&&this.#Er.removeEventListener("load",this.#Mr),this.#Cr&&(this.#Cr.close(),this.#Cr=null),this.removeAllListeners(),this.#Ir=[],$r.delete(this.#vr),this.#hr=!0)}},zr=le("TinyNewWinEvents"),Br=new WeakMap,Wr=e().EventEmitter,Ur=class extends Wr{#Pr;#Tr;#Ir=[];#xr=!1;#Or=!1;#$r=null;#Ar="__TNE_READY__";#Hr="__TNE_ROUTE__";#u=!1;get destroyed(){return this.#u}get readyEventName(){return zr(this.#u),this.#Ar}set readyEventName(e){if(zr(this.#u),"string"!=typeof e)throw new TypeError("TinyNewWinEvents: readyEventName must be a string.");this.#Ar=e}get routeEventName(){return zr(this.#u),this.#Hr}set routeEventName(e){if(zr(this.#u),"string"!=typeof e)throw new TypeError("TinyNewWinEvents: routeEventName must be a string.");this.#Hr=e}constructor({targetOrigin:e,url:t,name:r,features:i}={}){if(super(),"string"==typeof r&&"_blank"===r)throw new Error('TinyNewWinEvents: The window name "_blank" is not supported. Please use a custom name to allow tracking.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('TinyNewWinEvents: The "targetOrigin" option must be a string.');if(void 0!==t&&"string"!=typeof t)throw new TypeError('TinyNewWinEvents: The "url" option must be a string.');if(void 0!==i&&"string"!=typeof i)throw new TypeError('TinyNewWinEvents: The "features" option must be a string if provided.');if(void 0===t?this.#Pr=window.opener:(this.#Pr="string"==typeof t?window.open(t,r,i):t,this.#Or=!0),!this.#Pr||Br.has(this.#Pr))throw new Error("Invalid or duplicate window reference.");this.#Tr=e??window.location.origin,this._handleMessage=this.#Fr.bind(this),window.addEventListener("message",this._handleMessage,!1),this.#Or||(this.#zr(this.#Ar,null),this.#Br())}getWin(){return zr(this.#u),this.#Pr}#Fr(e){if(!e.source||this.#Pr&&e.source!==this.#Pr)return;const{type:t,route:r,payload:i}=e.data||{};if(t===this.#Ar)return this.#xr=!0,this.#jr(),this.#Br(),void(this.#Or&&this.#zr(this.#Ar,null));t===this.#Hr&&this.emit(`win:${r}`,i,e)}#jr(){for(;this.#Ir.length;){const e=this.#Ir.shift();if(e){const{route:t,payload:r}=e;this.winEmit(t,r)}}}#zr(e,t,r=""){this.#Pr&&this.#Pr.closed||this.#Pr?.postMessage({type:e,route:r,payload:t},this.#Tr)}close(){if(zr(this.#u),!this.#Or)throw new Error("Only host can close the window.");this.#Pr&&!this.#Pr.closed&&this.#Pr.close()}winEmit(e,t){if(zr(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");if(this.isDestroyed())throw new Error("Cannot emit: instance has been destroyed.");this.#xr?this.#zr(this.#Hr,t,e):this.#Ir.push({route:e,payload:t})}isConnected(){return zr(this.#u),!(!this.#xr||!this.#Pr||this.#Pr.closed)}#Br(){this.#Pr&&!this.#$r&&(this.#$r=setInterval(()=>{this.#Pr?.closed&&(this.emit("WINDOW_REF_CLOSED"),this.destroy())},500),Br.set(this.#Pr,this.#$r))}onClose(e){zr(this.#u),this.on("WINDOW_REF_CLOSED",e)}offClose(e){zr(this.#u),this.off("WINDOW_REF_CLOSED",e)}isDestroyed(){return!this.#Pr}destroy(){this.#Pr&&(this.#$r&&(clearInterval(this.#$r),this.#$r=null,Br.delete(this.#Pr)),window.removeEventListener("message",this._handleMessage),this.#Ir=[],this.#xr=!1,this.#Pr=null,this.removeAllListeners(),this.#u=!0)}},qr=class{#u=!1;get destroyed(){return this.#u}#Wr;#Ur;#qr;#Vr=0;#Kr=0;#Gr;#Jr=null;#Yr=null;get lineHeight(){return this.#Wr}get maxRows(){return this.#Ur-1}get extraHeight(){return this.#qr}get currentHeight(){return this.#Vr}get currentRows(){return this.#Kr}get textarea(){return this.#Gr}constructor(e,t={}){if(!(e instanceof HTMLTextAreaElement))throw new Error("TinyTextarea: Provided element is not a <textarea>.");if("object"!=typeof t||null===t)throw new TypeError("TinyTextarea: Options must be an object if provided.");if("maxRows"in t&&"number"!=typeof t.maxRows)throw new TypeError("TinyTextarea: `maxRows` must be a number.");if("extraHeight"in t&&"number"!=typeof t.extraHeight)throw new TypeError("TinyTextarea: `extraHeight` must be a number.");if("onResize"in t&&"function"!=typeof t.onResize)throw new TypeError("TinyTextarea: `onResize` must be a function.");if("onInput"in t&&"function"!=typeof t.onInput)throw new TypeError("TinyTextarea: `onInput` must be a function.");this.#Gr=e,this.#Ur=(t.maxRows??5)+1,this.#qr=t.extraHeight??0,this.#Jr=t.onResize??null,this.#Yr=t.onInput??null,this.#Wr=this.#Xr(),e.style.overflowY="hidden",e.style.resize="none",this._handleInput=()=>this.#Qr(),e.addEventListener("input",this._handleInput),this.#Qr()}#Qr(){this.#Gr.style.height="auto";const e=window.getComputedStyle(this.#Gr),t=parseFloat(e.paddingTop)||0,r=parseFloat(e.paddingBottom)||0,i=(this.#Gr.value.match(/\n/g)||[]).length,s=this.#Gr.scrollHeight,n=this.#Wr*this.#Ur,o=Math.ceil(Math.min(s,n)-t-r+this.#qr),a=this.#Ur-1,l=i<a?i+1:a;this.#Gr.style.height=`${o}px`,this.#Gr.style.overflowY=s>n?"auto":"hidden",this.#Vr=o;const h={breakLines:i,rows:l,height:o,scrollHeight:s,maxHeight:n,lineHeight:this.#Wr,maxRows:a};l!==this.#Kr&&(this.#Kr=l,"function"==typeof this.#Jr&&this.#Jr({...h})),"function"==typeof this.#Yr&&this.#Yr(h)}#Xr(){const e=window.getComputedStyle(this.#Gr),t=parseFloat(e.lineHeight);return Number.isNaN(t)?1.2*parseFloat(e.fontSize):t}getData(){return{rows:this.#Kr,height:this.#Vr}}refresh(){this.#Qr()}destroy(){this.destroyed||(this.#Gr.removeEventListener("input",this._handleInput),this.#u=!0)}},Vr=le("TinyGamepad");class Kr{#hr=!1;#Zr=new Set;#ei=new Map;#ti=new Map;#ri=null;#ii=[];#si={};#ni=[];#oi=null;#ai=null;#li;#hi;#ui;#ci;#di;#mi;#pi;#fi;#yi=[];#gi=0;#wi=0;#bi=[];#vi=0;#Ei=null;#Ti=new Set;#Si=new Set;#xi=new Map;#Ai=new Map;#Ci=new Map;static#Ii={" ":"Space","\n":"Enter","\r":"Enter","\t":"Tab","-":"Minus",_:"Minus","=":"Equal","+":"Equal","[":"BracketLeft","{":"BracketLeft","]":"BracketRight","}":"BracketRight","\\":"Backslash","|":"Backslash",";":"Semicolon",":":"Semicolon","'":"Quote",'"':"Quote",",":"Comma","<":"Comma",".":"Period",">":"Period","/":"Slash","?":"Slash","`":"Backquote","~":"Backquote"};static addSpecialKey(e,t){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);if("string"!=typeof t)throw new TypeError("Invalid code type: expected string, got "+typeof t);Kr.#Ii[e]=t}static removeSpecialKey(e){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);delete Kr.#Ii[e]}static getSpecialKey(e){if("string"!=typeof e)throw new TypeError("Invalid char type: expected string, got "+typeof e);if(1!==e.length)throw new Error(`Invalid char length: "${e}" (must be exactly one character)`);return Kr.#Ii[e]}static getAllSpecialKeys(){return{...Kr.#Ii}}static stringToKeys(e){if("string"!=typeof e)throw new TypeError("Invalid text type: expected string, got "+typeof e);if(!e.length)throw new Error("Invalid text: cannot be empty");return Array.from(e).map(e=>{const t=e.toUpperCase();if(t>="A"&&t<="Z")return`Key${t}`;if(t>="0"&&t<="9")return`Digit${t}`;const r=Kr.#Ii[e];if(void 0!==r)return r;throw new Error(`Unsupported character: "${e}"`)})}constructor({expectedId:e=null,inputMode:t="both",ignoreIds:r=[],deadZone:i=.1,axisActiveSensitivity:s=.3,timeoutComboKeys:n=500,allowMouse:o=!1,elementBase:a=window}={}){if(null!==e&&"string"!=typeof e)throw new TypeError('"expectedId" must be a string or null, received: '+typeof e);if(!["keyboard-only","gamepad-only","both"].includes(t))throw new TypeError(`"inputMode" must be 'keyboard-only', 'gamepad-only', or 'both', received: ${t}`);if(!Array.isArray(r)||!r.every(e=>"string"==typeof e))throw new TypeError('"ignoreIds" must be an array of strings');if("number"!=typeof i||i<0||i>1)throw new RangeError(`"deadZone" must be a number between 0 and 1, received: ${i}`);if("number"!=typeof s||s<0||s>1)throw new RangeError(`"axisActiveSensitivity" must be a number between 0 and 1, received: ${s}`);if("number"!=typeof n||n<0)throw new RangeError(`"timeoutComboKeys" must be a positive number, received: ${n}`);if("boolean"!=typeof o)throw new TypeError('"allowMouse" must be a boolean, received: '+typeof o);if(!(a instanceof Window||a instanceof Element))throw new TypeError('"elementBase" must be a Window or Element instance');this.#ci=e,this.#li=t,this.#hi=new Set(r),this.#ui=i,this.#di=o,this.#mi=a,this.#pi=n,this.#fi=s,["gamepad-only","both"].includes(this.#li)&&this.#ki(),["keyboard-only","both"].includes(this.#li)&&this.#Di()}#Mi=e=>this.#Li(e.gamepad);#Ni=e=>this.#_i(e.gamepad);#ki(){window.addEventListener("gamepadconnected",this.#Mi),window.addEventListener("gamepaddisconnected",this.#Ni)}#Li(e){this.#hr||this.#hi.has(e.id)||this.#ci&&e.id!==this.#ci||this.#ri||(this.#ri=e,this.#ci=e.id,this.#Ri(),this.#ji("connected",{id:e.id,gp:e,timestamp:e.timestamp}))}#_i(e){this.#hr||this.#ri&&e.id===this.#ri.id&&(this.#ri=null,this.#oi&&(cancelAnimationFrame(this.#oi),this.#oi=null),this.#ji("disconnected",{id:e.id,gp:e,timestamp:e.timestamp}))}#Ri(){const e=()=>{this.#hr||(this.#Pi(),this.#oi=requestAnimationFrame(e))};e()}#Pi(){if(this.#hr)return;const e=navigator.getGamepads(),t=Array.from(e).find(e=>e&&e.id===this.#ci);t&&(this.#ri=t,t.buttons.forEach((e,r)=>{const i=`Button${r}`,s=this.#ii[r]?.pressed||!1;let n,o,a=!1;e.pressed&&!s?(o=1,n="down"):!e.pressed&&s?(o=0,n="up"):e.pressed&&s&&(o=1,n="hold"),e.pressed&&e.value>0&&e.value<1&&1!==e.value&&(o=e.value,a=!0),"number"==typeof o&&"string"==typeof n&&this.#Oi({key:i,source:"gamepad-button",value:o,value2:NaN,type:n,gp:t,isPressure:a,pressed:e.pressed,prevPressed:s,timestamp:t.timestamp,id:t.id}),this.#ii[r]={pressed:e.pressed,value:"number"==typeof o?o:this.#ii[r]?.value,value2:NaN}}),t.axes.forEach((e,r)=>{Math.abs(e)<this.#ui&&(e=0);const i=`Axis${r}`;e!==(this.#ni[r]??0)&&this.#Oi({key:i,source:"gamepad-analog",value:e,value2:NaN,type:"change",timestamp:t.timestamp,id:t.id,gp:t}),this.#ni[r]=e}))}#$i=e=>{if(!this.#hr){if(!(e instanceof KeyboardEvent))throw new Error("Expected KeyboardEvent in keydown listener.");this.#Zr.has(e.code)||(this.#Zr.add(e.code),this.#Oi({event:e,key:e.code,source:"keyboard",value:1,value2:NaN,type:"down",pressed:!0,prevPressed:this.#si[e.code]?.pressed??!1,id:"native_keyboard",timestamp:e.timeStamp}),this.#si[e.code]={pressed:!0})}};#Hi=e=>{if(!this.#hr){if(!(e instanceof KeyboardEvent))throw new Error("Expected KeyboardEvent in keyup listener.");this.#Zr.has(e.code)&&(this.#Zr.delete(e.code),this.#Oi({event:e,key:e.code,source:"keyboard",value:0,value2:NaN,type:"up",pressed:!1,prevPressed:this.#si[e.code]?.pressed??!1,id:"native_keyboard",timestamp:e.timeStamp}),this.#si[e.code]={pressed:!1})}};#Fi=e=>{if(this.#hr)return;if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mousedown listener.");const t=`Mouse${e.button}`;this.#Zr.add(t),this.#Oi({event:e,key:t,source:"mouse",value:1,value2:NaN,type:"down",pressed:!0,prevPressed:this.#si[t]?.pressed??!1,id:"native_mouse",timestamp:e.timeStamp}),this.#si[t]={pressed:!0}};#zi=e=>{if(this.#hr)return;if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mouseup listener.");const t=`Mouse${e.button}`;this.#Zr.delete(t),this.#Oi({event:e,key:t,source:"mouse",value:0,value2:NaN,type:"up",pressed:!1,prevPressed:this.#si[t]?.pressed??!1,id:"native_mouse",timestamp:e.timeStamp}),this.#si[t]={pressed:!1}};#Bi=e=>{if(!this.#hr){if(!(e instanceof MouseEvent))throw new Error("Expected MouseEvent in mousemove listener.");if(0!==e.movementX||0!==e.movementY){const t="MouseMove",r=this.#si[t]??{pressed:!1,value:0,value2:0};this.#Oi({event:e,key:t,source:"mouse",value:e.movementX+(r.value??0),value2:e.movementY+(r.value??0),id:"native_mouse",type:"move",pressed:!0,prevPressed:null,timestamp:e.timeStamp}),this.#si[t]={pressed:!1,value:e.movementX,value2:e.movementY}}}};#Di(){this.#mi.addEventListener("keydown",this.#$i),this.#mi.addEventListener("keyup",this.#Hi),this.#di&&(this.#mi.addEventListener("mousedown",this.#Fi),this.#mi.addEventListener("mouseup",this.#zi),this.#mi.addEventListener("mousemove",this.#Bi));const e=()=>{this.#hr||(this.#Zr.forEach(e=>{const t=e.startsWith("Mouse")?"mouse":"keyboard";this.#Oi({key:e,source:t,id:`native_${t}`,value:1,value2:NaN,type:"hold",pressed:!0,prevPressed:this.#si[e]?.pressed??!1,timestamp:NaN})}),this.#ai=requestAnimationFrame(e))};e()}#Oi(e){if(this.#hr)return;const t=this.#ti.get("input-*")||[],{pressed:r,key:i}=e,s=i.startsWith("Axis"),n="boolean"==typeof r&&r||s&&(e.value>this.#fi||e.value<-Math.abs(this.#fi)),o=s?`${i}${e.value>0?"+":e.value<0?"-":""}`:i;let a=null;if("move"!==e.type&&"hold"!==e.type){if(n){if(!s&&!this.#Ti.has(i)||s&&!this.#Ti.has(i)&&!this.#Ti.has(`${i}+`)&&!this.#Ti.has(`${i}-`)){0===this.#vi&&(this.#vi=Date.now()),this.#Ti.add(o),a=!0,this.#bi.push(o),this.#yi.length<1&&(this.#Ei&&clearTimeout(this.#Ei),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#pi));const e=this.#ti.get("mapped-key-start")??[];for(const t of e)t({key:o,activeTime:this.#vi})}}else if(!s&&this.#Ti.has(i)||s&&(this.#Ti.has(i)||this.#Ti.has(`${i}+`)||this.#Ti.has(`${i}-`))){this.#Ti.delete(i),this.#Ti.delete(`${i}+`),this.#Ti.delete(`${i}-`),a=!1;const e=this.#ti.get("mapped-key-end")??[];for(const t of e)t({key:o,activeTime:this.#vi})}for(const{sequence:e,callback:t,triggered:r}of this.#Ai.values()){const i=this.#Ai.get(e.join("+"));if(!i)continue;const s=e.every((e,t)=>this.#bi[t]===e);s&&!r?(i.triggered=!0,t(this.#vi)):!s&&r&&(i.triggered=!1)}}for(const[r,l]of this.#ei.entries()){const h=e=>"string"==typeof l&&e===l||Array.isArray(l)&&l.findIndex((t,r)=>e===l[r])>-1,u=h(o),c=s&&h(`${i}+`),d=s&&h(`${i}-`);if(u||c||d){if(n&&u){if(a||!this.#Si.has(r)){0===this.#wi&&(this.#wi=Date.now()),this.#Si.add(r),0===this.#gi&&(this.#gi=Date.now()),this.#Ei&&clearTimeout(this.#Ei),this.#yi.push(r),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#pi);const e=this.#ti.get("mapped-input-start")??[];for(const t of e)t({logicalName:r,activeTime:this.#wi,comboTime:this.#gi})}}else if(!a||this.#Si.has(r)){this.#Si.delete(r),this.#Si.size<1&&(this.#wi=0);const e=this.#ti.get("mapped-input-end")??[];for(const t of e)t({logicalName:r,activeTime:this.#wi,comboTime:this.#gi})}for(const{sequence:e,callback:t,triggered:r}of this.#xi.values()){const i=this.#xi.get(e.join("+"));if(!i)continue;const s=Array.from(this.#Si),n=e.every((e,t)=>s[t]===e);n&&!r?(i.triggered=!0,t(this.#wi)):!n&&r&&(i.triggered=!1)}}const m=[];if(s&&0===e.value){const{value:t}=this.#Ci.get(`${i}-`)??{value:0,value2:NaN},{value:r}=this.#Ci.get(`${i}+`)??{value:0,value2:NaN};e.value!==t&&m.push(`${i}-`),e.value!==r&&m.push(`${i}+`)}else m.push(o);m.forEach(i=>{if(!("*"===l||l===i||Array.isArray(l)&&l.includes(i)))return;const s=this.#ti.get(`input-${e.type}-${r}`)||[],n=this.#ti.get(`input-${r}`)||[];if(n.length<1&&s.length<1&&t.length<1)return;const o={...e,key:i,logicalName:r};for(const e of t)e(o);for(const e of n)e(o);for(const e of s)e(o);this.#Ci.set(i,{value:e.value,value2:e.value2})})}}#ji(e,t){const r=this.#ti.get(e)||[];for(const e of r)e(t)}#Wi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e);let s=this.#ti.get(i);Array.isArray(s)||(s=[],this.#ti.set(i,s)),s.push(t)}#Ui(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=s=>{this.#qi(e,i,r),t(s)};this.#Wi(e,i,r)}#Vi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e),s=this.#ti.get(i)??[];s.unshift(t),this.#ti.set(i,s)}#qi(e,t,r){if("string"!=typeof e)throw new TypeError(`"logicalName" must be a string, received ${e}`);if("function"!=typeof t)throw new TypeError('"callback" must be a function, received '+typeof t);const i=r.replace("{logicalName}",e),s=this.#ti.get(i);Array.isArray(s)&&this.#ti.set(i,s.filter(e=>e!==t))}awaitInputMapping({timeout:e=1e4,eventName:t="MappingInput",canMove:r=!1}={}){return Vr(this.#hr),new Promise((i,s)=>{if("number"!=typeof e||Number.isNaN(e)||e<0)return s(new TypeError(`Invalid "timeout": expected a positive number, got ${e}`));if("string"!=typeof t||!t.trim())return s(new TypeError(`Invalid "eventName": expected a non-empty string, got ${t}`));if("boolean"!=typeof r)return s(new TypeError(`Invalid "canMove": expected a boolean, got ${r}`));const n={key:null,source:null},o=({key:e,type:s,source:l,gp:h,value:u})=>{(r||"move"!==s)&&(n.key=e,n.source=l,n.gp=h,clearTimeout(a),this.offInputStart(t,o),this.offInputChange(t,o),r&&this.offInputMove(t,o),i(n))},a=setTimeout(()=>i(n),e);this.mapInput(t,"*"),this.onInputStart(t,o),this.onInputChange(t,o),r&&this.onInputMove(t,o)})}mapInput(e,t){if(Vr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);if(!("string"==typeof t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError(`Invalid "physicalInput": expected string or array of strings, got ${JSON.stringify(t)}`);this.#ei.set(e,t)}unmapInput(e){if(Vr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);this.#ei.delete(e)}hasMappedInput(e){if(Vr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);return this.#ei.has(e)}getMappedInput(e){if(Vr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError(`Invalid "logicalName": expected a non-empty string, got ${e}`);const t=this.#ei.get(e);if(!t)throw new Error(`No physical input mapped for logicalName: "${e}"`);return t}clearMapInputs(){Vr(this.#hr),this.#ei.clear()}registerInputSequence(e,t){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);if("function"!=typeof t)throw new TypeError("'callback' must be a function, got: "+typeof t);if(0===e.length)throw new Error("'sequence' must contain at least one input name.");const r=e.join("+");this.#xi.set(r,{sequence:e,callback:t,triggered:!1})}unregisterInputSequence(e){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");this.#xi.delete(t)}unregisterAllInputSequences(){Vr(this.#hr),this.#xi.clear()}hasInputSequence(e){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");return this.#xi.has(t)}registerKeySequence(e,t){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);if("function"!=typeof t)throw new TypeError("'callback' must be a function, got: "+typeof t);if(0===e.length)throw new Error("'sequence' must contain at least one input name.");const r=e.join("+");this.#Ai.set(r,{sequence:e,callback:t,triggered:!1})}unregisterKeySequence(e){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");this.#Ai.delete(t)}unregisterAllKeySequences(){Vr(this.#hr),this.#Ai.clear()}hasKeySequence(e){if(Vr(this.#hr),!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError(`'sequence' must be an array of strings, got: ${JSON.stringify(e)}`);const t=e.join("+");return this.#Ai.has(t)}renewComboMapped(){Vr(this.#hr),this.#Ei&&(clearTimeout(this.#Ei),this.#Ei=setTimeout(()=>this.resetComboMapped(),this.#pi))}resetComboMapped(){Vr(this.#hr),this.#Ei&&clearTimeout(this.#Ei),this.#bi=[],this.#Ei=null,this.#vi=0,this.#yi=[],this.#gi=0}onMappedKeyStart(e){return Vr(this.#hr),this.#Wi("",e,"mapped-key-start")}onceMappedKeyStart(e){return Vr(this.#hr),this.#Ui("",e,"mapped-key-start")}prependMappedKeyStart(e){return Vr(this.#hr),this.#Vi("",e,"mapped-key-start")}offMappedKeyStart(e){return Vr(this.#hr),this.#qi("",e,"mapped-key-start")}offAllMappedKeyStart(){Vr(this.#hr),this.#ti.delete("mapped-key-start")}onMappedKeyEnd(e){return Vr(this.#hr),this.#Wi("",e,"mapped-key-end")}onceMappedKeyEnd(e){return Vr(this.#hr),this.#Ui("",e,"mapped-key-end")}prependMappedKeyEnd(e){return Vr(this.#hr),this.#Vi("",e,"mapped-key-end")}offMappedKeyEnd(e){return Vr(this.#hr),this.#qi("",e,"mapped-key-end")}offAllMappedKeyEnd(){Vr(this.#hr),this.#ti.delete("mapped-key-end")}onMappedInputStart(e){return Vr(this.#hr),this.#Wi("",e,"mapped-input-start")}onceMappedInputStart(e){return Vr(this.#hr),this.#Ui("",e,"mapped-input-start")}prependMappedInputStart(e){return Vr(this.#hr),this.#Vi("",e,"mapped-input-start")}offMappedInputStart(e){return Vr(this.#hr),this.#qi("",e,"mapped-input-start")}offAllMappedInputStart(){Vr(this.#hr),this.#ti.delete("mapped-input-start")}onMappedInputEnd(e){return Vr(this.#hr),this.#Wi("",e,"mapped-input-end")}onceMappedInputEnd(e){return Vr(this.#hr),this.#Ui("",e,"mapped-input-end")}prependMappedInputEnd(e){return Vr(this.#hr),this.#Vi("",e,"mapped-input-end")}offMappedInputEnd(e){return Vr(this.#hr),this.#qi("",e,"mapped-input-end")}offAllMappedInputEnd(){Vr(this.#hr),this.#ti.delete("mapped-input-end")}onInput(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-{logicalName}")}onceInput(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-{logicalName}")}prependInput(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-{logicalName}")}offInput(e,t){return Vr(this.#hr),this.#qi(e,t,"input-{logicalName}")}onInputStart(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-down-{logicalName}")}onceInputStart(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-down-{logicalName}")}prependInputStart(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-down-{logicalName}")}offInputStart(e,t){return Vr(this.#hr),this.#qi(e,t,"input-down-{logicalName}")}onInputEnd(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-up-{logicalName}")}onceInputEnd(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-up-{logicalName}")}prependInputEnd(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-up-{logicalName}")}offInputEnd(e,t){return Vr(this.#hr),this.#qi(e,t,"input-up-{logicalName}")}onInputHold(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-hold-{logicalName}")}onceInputHold(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-hold-{logicalName}")}prependInputHold(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-hold-{logicalName}")}offInputHold(e,t){return Vr(this.#hr),this.#qi(e,t,"input-hold-{logicalName}")}onInputChange(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-change-{logicalName}")}onceInputChange(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-change-{logicalName}")}prependInputChange(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-change-{logicalName}")}offInputChange(e,t){return Vr(this.#hr),this.#qi(e,t,"input-change-{logicalName}")}onInputMove(e,t){return Vr(this.#hr),this.#Wi(e,t,"input-move-{logicalName}")}onceInputMove(e,t){return Vr(this.#hr),this.#Ui(e,t,"input-move-{logicalName}")}prependInputMove(e,t){return Vr(this.#hr),this.#Vi(e,t,"input-move-{logicalName}")}offInputMove(e,t){return Vr(this.#hr),this.#qi(e,t,"input-move-{logicalName}")}getCalls(e,t="all"){if(Vr(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i=`${{all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t]}${e}`,s=this.#ti.get(i);return Array.isArray(s)?[...s]:[]}offAllInputs(e,t="all"){if(Vr(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i={all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t];i&&this.#ti.delete(`${i}${e}`)}getCallSize(e,t="all"){if(Vr(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"logicalName" must be a non-empty string, received ${e}`);const r=["all","start","end","hold","change","move"];if(!r.includes(t))throw new TypeError(`"type" must be one of ${r.join(", ")}, received ${t}`);const i={all:"input-",start:"input-down-",end:"input-up-",hold:"input-hold-",change:"input-change-",move:"input-move-"}[t],s=this.#ti.get(`${i}${e}`);return Array.isArray(s)?s.length:0}#Ki={type:"dual-rumble",params:{startDelay:0,duration:200,weakMagnitude:.5,strongMagnitude:1}};get defaultHapticEffect(){return Vr(this.#hr),{type:this.#Ki.type,params:{...this.#Ki.params}}}setDefaultHapticEffect(e,t){if(Vr(this.#hr),"string"!=typeof e)throw new TypeError(`"type" must be a valid GamepadHapticEffectType string, received ${e}`);if("object"!=typeof t||null===t)throw new TypeError(`"params" must be a non-null object, received ${t}`);this.#Ki.type=e,this.#Ki.params=t}hasHapticEffect(){Vr(this.#hr);const e=this.#ri;return!!e&&e.vibrationActuator instanceof GamepadHapticActuator}vibrate(e,t){if(Vr(this.#hr),void 0!==e&&("object"!=typeof e||null===e))throw new TypeError(`"params" must be an object if provided, received ${e}`);if(void 0!==t&&"string"!=typeof t)throw new TypeError(`"type" must be a valid GamepadHapticEffectType string if provided, received ${t}`);const r=this.#ri;if(!r)return new Promise(e=>e("complete"));const i=r.vibrationActuator;return i instanceof GamepadHapticActuator?i.playEffect(t??this.#Ki.type,{...this.#Ki.params,...e}):new Promise(e=>e("complete"))}ignoreId(e){if(Vr(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"id" must be a non-empty string, received ${e}`);this.#hi.add(e)}unignoreId(e){if(Vr(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError(`"id" must be a non-empty string, received ${e}`);this.#hi.delete(e)}onConnected(e){return Vr(this.#hr),this.#Wi("",e,"connected")}onceConnected(e){return Vr(this.#hr),this.#Ui("",e,"connected")}prependConnected(e){return Vr(this.#hr),this.#Vi("",e,"connected")}offConnected(e){return Vr(this.#hr),this.#qi("",e,"connected")}offAllConnected(){Vr(this.#hr),this.#ti.delete("connected")}onDisconnected(e){return Vr(this.#hr),this.#Wi("",e,"disconnected")}onceDisconnected(e){return Vr(this.#hr),this.#Ui("",e,"disconnected")}prependDisconnected(e){return Vr(this.#hr),this.#Vi("",e,"disconnected")}offDisconnected(e){return Vr(this.#hr),this.#qi("",e,"disconnected")}offAllDisconnected(){Vr(this.#hr),this.#ti.delete("disconnected")}hasGamepad(){return Vr(this.#hr),this.#ri instanceof Gamepad}getGamepad(){if(Vr(this.#hr),!this.#ri)throw new Error("No gamepad is currently connected.");return this.#ri}hasLastButtonState(e){return Vr(this.#hr),!!this.#ii[e]}getLastButtonState(e){if(Vr(this.#hr),!this.#ii[e])throw new Error(`No last button state found for index ${e}`);return{...this.#ii[e]}}exportConfig(){return Vr(this.#hr),{expectedId:this.#ci,ignoreIds:Array.from(this.#hi),deadZone:this.#ui,timeoutComboKeys:this.#pi,axisActiveSensitivity:this.#fi,inputMap:Array.from(this.#ei.entries())}}importConfig(e){if(Vr(this.#hr),"string"!=typeof e&&("object"!=typeof e||null===e))throw new TypeError(`"json" must be a string or a non-null object, received: ${e}`);const t="string"==typeof e?JSON.parse(e):e;if(void 0!==t.expectedId&&"string"!=typeof t.expectedId&&null!==t.expectedId)throw new TypeError('"expectedId" must be a string or null if provided');if(void 0!==t.ignoreIds&&!Array.isArray(t.ignoreIds))throw new TypeError('"ignoreIds" must be an array if provided');if(void 0!==t.deadZone&&"number"!=typeof t.deadZone)throw new TypeError('"deadZone" must be a number if provided');if(void 0!==t.timeoutComboKeys&&"number"!=typeof t.timeoutComboKeys)throw new TypeError('"timeoutComboKeys" must be a number if provided');if(void 0!==t.axisActiveSensitivity&&"number"!=typeof t.axisActiveSensitivity)throw new TypeError('"axisActiveSensitivity" must be a number if provided');if(void 0!==t.inputMap&&!Array.isArray(t.inputMap))throw new TypeError('"inputMap" must be an array if provided');void 0!==t.expectedId&&(this.#ci=t.expectedId),Array.isArray(t.ignoreIds)&&(this.#hi=new Set(t.ignoreIds)),"number"==typeof t.deadZone&&(this.#ui=t.deadZone),"number"==typeof t.timeoutComboKeys&&(this.#pi=t.timeoutComboKeys),"number"==typeof t.axisActiveSensitivity&&(this.#fi=t.axisActiveSensitivity),Array.isArray(t.inputMap)&&(this.#ei=new Map(t.inputMap))}get mappedKeyStartCalls(){Vr(this.#hr);const e=this.#ti.get("mapped-key-start");return Array.isArray(e)?[...e]:[]}get mappedKeyEndCalls(){Vr(this.#hr);const e=this.#ti.get("mapped-key-end");return Array.isArray(e)?[...e]:[]}get comboMappedKeys(){return Vr(this.#hr),[...this.#bi]}get comboMappedInputs(){return Vr(this.#hr),[...this.#yi]}get keySequenceSize(){return Vr(this.#hr),this.#Ai.size}get keySequences(){Vr(this.#hr);const e=[];for(const[,t]of this.#Ai.entries())e.push(t.callback);return e}get activeMappedKeys(){return Vr(this.#hr),[...this.#Ti]}get mappedInputStartCalls(){Vr(this.#hr);const e=this.#ti.get("mapped-input-start");return Array.isArray(e)?[...e]:[]}get mappedInputEndCalls(){Vr(this.#hr);const e=this.#ti.get("mapped-input-end");return Array.isArray(e)?[...e]:[]}get inputSequenceSize(){return Vr(this.#hr),this.#xi.size}get inputSequences(){Vr(this.#hr);const e=[];for(const[,t]of this.#xi.entries())e.push(t.callback);return e}get activeMappedInputs(){return Vr(this.#hr),[...this.#Si]}get mappedInputs(){Vr(this.#hr);const e={};for(const[t,r]of this.#ei.entries())e[t]=r;return e}get mappedInputSize(){return Vr(this.#hr),this.#ei.size}get connectedCalls(){Vr(this.#hr);const e=this.#ti.get("connected");return Array.isArray(e)?[...e]:[]}get disconnectedCalls(){Vr(this.#hr);const e=this.#ti.get("disconnected");return Array.isArray(e)?[...e]:[]}get ignoredDeviceIds(){return Vr(this.#hr),[...this.#hi]}get heldKeys(){return Vr(this.#hr),[...this.#Zr]}get eventsSize(){Vr(this.#hr);let e=0;return this.#ti.forEach(t=>{e+=t.length}),e}get callSize(){return Vr(this.#hr),this.#ti.size}get connectedCallSize(){Vr(this.#hr);const e=this.#ti.get("connected");return Array.isArray(e)?e.length:0}get disconnectedCallSize(){Vr(this.#hr);const e=this.#ti.get("disconnected");return Array.isArray(e)?e.length:0}get mappedKeyStartCallSize(){Vr(this.#hr);const e=this.#ti.get("mapped-key-start");return Array.isArray(e)?e.length:0}get mappedKeyEndCallSize(){Vr(this.#hr);const e=this.#ti.get("mapped-key-end");return Array.isArray(e)?e.length:0}get mappedInputStartCallSize(){Vr(this.#hr);const e=this.#ti.get("mapped-input-start");return Array.isArray(e)?e.length:0}get mappedInputEndCallSize(){Vr(this.#hr);const e=this.#ti.get("mapped-input-end");return Array.isArray(e)?e.length:0}get lastButtonStates(){Vr(this.#hr);const e=[];return this.#ii.forEach(t=>{e.push({...t})}),e}get lastAxes(){return Vr(this.#hr),[...this.#ni]}get inputMode(){return Vr(this.#hr),this.#li}get elementBase(){return Vr(this.#hr),this.#mi}get timeComboInputs(){return Vr(this.#hr),this.#gi}get timeComboKeys(){return Vr(this.#hr),this.#vi}get timeMappedInputs(){return Vr(this.#hr),this.#wi}get timeoutComboKeys(){return Vr(this.#hr),this.#pi}set timeoutComboKeys(e){if(Vr(this.#hr),"number"!=typeof e||e<0||!Number.isFinite(e))throw new TypeError("Timeout combo keys must be a non-negative finite number.");this.#pi=e}get axisActiveSensitivity(){return Vr(this.#hr),this.#fi}set axisActiveSensitivity(e){if(Vr(this.#hr),"number"!=typeof e||e<0||e>1)throw new RangeError("Axis sensitivity must be a number between 0 and 1.");this.#fi=e}get deadZone(){return Vr(this.#hr),this.#ui}set deadZone(e){if(Vr(this.#hr),"number"!=typeof e||e<0||e>1)throw new RangeError("Dead zone must be a number between 0 and 1.");this.#ui=e}get expectedId(){return Vr(this.#hr),this.#ci}set expectedId(e){if(Vr(this.#hr),"string"!=typeof e)throw new TypeError("Expected device id be a string.");this.#ci=e}get isDestroyed(){return this.#hr}destroy(){this.#hr||(this.#oi&&cancelAnimationFrame(this.#oi),this.#ai&&cancelAnimationFrame(this.#ai),this.#oi=null,this.#ai=null,["keyboard-only","both"].includes(this.#li)&&(this.#mi.removeEventListener("keydown",this.#$i),this.#mi.removeEventListener("keyup",this.#Hi),this.#di&&(this.#mi.removeEventListener("mousedown",this.#Fi),this.#mi.removeEventListener("mouseup",this.#zi),this.#mi.removeEventListener("mousemove",this.#Bi))),["gamepad-only","both"].includes(this.#li)&&(window.removeEventListener("gamepadconnected",this.#Mi),window.removeEventListener("gamepaddisconnected",this.#Ni)),this.resetComboMapped(),this.#ei.clear(),this.#ti.clear(),this.#Zr.clear(),this.#Si.clear(),this.#Ti.clear(),this.#xi.clear(),this.#Ai.clear(),this.#hi.clear(),this.#Ci.clear(),this.#ii=[],this.#ni=[],this.#si={},this.#ri=null,this.#ci=null,this.#di=!1,this.#wi=0,this.#hr=!0)}}const Gr=Kr,Jr=le("TinyDayNightCycle"),Yr=class{#Gi=!0;#Ji=86400;#Yi=3600;#Xi=60;#Qi=new Map;#Zi=[];#es;#ts;#rs={main:null};#is=0;#ss=0;#ns=0;#os="";#as=1;#ls=1;#hs=1;#hr=!1;#us=[31,31,31,31,31,31,31,31,31,31,31,31];#cs={default:{},day:{},night:{},hours:{},seasons:{}};#ds={min:60,max:180};#ms=0;get daySize(){return Jr(this.#hr),this.#Ji}get autoSizeAdjuste(){return Jr(this.#hr),this.#Gi}set autoSizeAdjuste(e){if(Jr(this.#hr),"boolean"!=typeof e)throw new TypeError("autoSizeAdjuste must be a boolean.");this.#Gi=e}set daySize(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("daySize must be a positive finite number.");const t=this.#Yi/this.#Ji,r=this.#Xi/this.#Ji;this.#Ji=e,this.#Gi&&(this.#Yi=e*t,this.#Xi=e*r)}get hourSize(){return Jr(this.#hr),this.#Yi}set hourSize(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("hourSize must be a positive finite number.");const t=this.#Ji/this.#Yi,r=this.#Xi/this.#Yi;this.#Yi=e,this.#Gi&&(this.#Ji=e*t,this.#Xi=e*r)}get minuteSize(){return Jr(this.#hr),this.#Xi}set minuteSize(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e)||e<=0)throw new Error("minuteSize must be a positive finite number.");const t=this.#Yi/this.#Xi,r=this.#Ji/this.#Xi;this.#Xi=e,this.#Gi&&(this.#Yi=e*t,this.#Ji=e*r)}get isDestroyed(){return this.#hr}get currentSeconds(){return Jr(this.#hr),this.#is}set currentSeconds(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentSeconds must be a finite number, received "+typeof e);if(e<0||e>=this.#Ji)throw new RangeError(`currentSeconds must be between 0 and 86399, received ${e}`);this.#is=Math.floor(e),this.#ss=Math.floor(e/this.#Xi),this.#ns=Math.floor(e/this.#Yi)}get currentMinutes(){return Jr(this.#hr),this.#ss}set currentMinutes(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentMinutes must be a finite number, received "+typeof e);if(e<0||e>=1440)throw new RangeError(`currentMinutes must be between 0 and 1439, received ${e}`);this.#ss=Math.floor(e),this.#ns=Math.floor(e/this.#Xi),this.#is=Math.floor(e*this.#Xi)}get currentHours(){return Jr(this.#hr),this.#ns}set currentHours(e){if(Jr(this.#hr),"number"!=typeof e||!Number.isFinite(e))throw new TypeError("currentHours must be a finite number, received "+typeof e);if(e<0||e>=24)throw new RangeError(`currentHours must be between 0 and less than 24, received ${e}`);this.#ns=Math.floor(e),this.#ss=Math.floor(e*this.#Xi),this.#is=Math.floor(e*this.#Yi)}get moons(){return Jr(this.#hr),this.#Zi.map(e=>this.getMoon(e))}get seasons(){return Jr(this.#hr),Array.from(this.#Qi.keys())}get dayStart(){return Jr(this.#hr),this.#es}get nightStart(){return Jr(this.#hr),this.#ts}get weather(){return Jr(this.#hr),{...this.#rs}}get currentSeason(){return Jr(this.#hr),this.#os}get currentDay(){return Jr(this.#hr),this.#as}get currentMonth(){return Jr(this.#hr),this.#ls}get currentYear(){return Jr(this.#hr),this.#hs}get monthDays(){return Jr(this.#hr),[...this.#us]}get weatherDuration(){return Jr(this.#hr),{...this.#ds}}get weatherTimeLeft(){return Jr(this.#hr),this.#ms}set dayStart(e){if(Jr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("dayStart must be a positive non-zero number, received "+typeof e);this.#es=e}set nightStart(e){if(Jr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("nightStart must be a positive non-zero number, received "+typeof e);this.#ts=e}set weather(e){if(Jr(this.#hr),"object"!=typeof e||null===e||Array.isArray(e)||!Object.values(e).every(e=>"string"==typeof e))throw new TypeError("weather must be a object with strings, received "+typeof e);this.#rs=e}set currentSeason(e){if(Jr(this.#hr),"string"!=typeof e||!this.#Qi.has(e))throw new TypeError(`currentSeason must be one of ${Array.from(this.#Qi).map(e=>e[0]).join(", ")}, received ${e}`);this.#os=e}set currentDay(e){if(Jr(this.#hr),"number"!=typeof e||e<1||e>this.#us[this.#ls-1])throw new TypeError("currentDay must be a valid day number, received "+typeof e);this.#as=e}set currentMonth(e){if(Jr(this.#hr),"number"!=typeof e||"number"!=typeof this.#us[e-1])throw new TypeError("currentMonth must be a valid month number, received "+typeof e);this.#ls=e}set currentYear(e){if(Jr(this.#hr),"number"!=typeof e||e<1)throw new TypeError("currentYear must be a positive number non-zero, received "+typeof e);this.#hs=e}set monthDays(e){if(Jr(this.#hr),!Array.isArray(e))throw new TypeError("monthDays must be a array");if(!e.every(e=>"number"==typeof e))throw new TypeError("monthDays must have number values");this.#us=[...e]}set weatherDuration(e){if(Jr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("weatherDuration must be a non-null object");if("number"!=typeof e.min||"number"!=typeof e.max)throw new TypeError("weatherDuration.min and weatherDuration.max must be numbers");this.#ds={...e}}set weatherTimeLeft(e){if(Jr(this.#hr),"number"!=typeof e)throw new TypeError("weatherTimeLeft must be a number, received "+typeof e);this.#ms=e}get weatherConfig(){Jr(this.#hr);const e={},t={};for(const t in this.#cs.hours)e[t]={...this.#cs.hours[t]};for(const e in this.#cs.seasons)t[e]={...this.#cs.seasons[e]};return{default:{...this.#cs.default},day:{...this.#cs.day},night:{...this.#cs.night},hours:e,seasons:t}}set weatherConfig(e){if(Jr(this.#hr),"object"!=typeof e||null===e)throw new TypeError(`weatherConfig must be a non-null object, received ${e}`);const t=["default","day","night","hours","seasons"];for(const r of t)if(!(r in e))throw new TypeError(`weatherConfig is missing required property "${r}".`);const r={},i={},s=(e,t)=>{if("object"!=typeof e||null===e)throw new TypeError(`${t} must be an object, received ${e}`);for(const r in e){const i=typeof e[r];if("number"!==i&&"function"!==i)throw new TypeError(`${t}["${r}"] must be a number or function, received ${i}`)}};for(const t in e.hours)s(e.hours[t],`hours["${t}"]`),r[t]={...e.hours[t]};for(const t in e.seasons)s(e.seasons[t],`seasons["${t}"]`),i[t]={...e.seasons[t]};const n=(e,t)=>(s(e,t),{...e});this.#cs={default:n(e.default,"default"),day:n(e.day,"day"),night:n(e.night,"night"),hours:r,seasons:i}}constructor(e=6,t=18){this.#es=e,this.#ts=t}addSeason(e,t){if(Jr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);if(!Array.isArray(t)||!t.every(e=>"number"==typeof e))throw new TypeError("Season values must be an array of numbers");this.#Qi.set(e,t)}removeSeason(e){if(Jr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);this.#Qi.delete(e),this.#os===e&&(this.#os="")}hasSeason(e){if(Jr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);return this.#Qi.has(e)}getSeason(e){if(Jr(this.#hr),"string"!=typeof e)throw new TypeError("Season name must be a string, received "+typeof e);const t=this.#Qi.get(e);if(!t)throw new Error(`Season "${e}" not found`);return[...t]}setTime({hour:e=0,minute:t=0,second:r=0}){Jr(this.#hr),this.currentSeconds=(e*this.#Yi+t*this.#Xi+r)%this.#Ji}addTime({hours:e=0,minutes:t=0,seconds:r=0}){Jr(this.#hr);let i=this.currentSeconds+e*this.#Yi+t*this.#Xi+r;for(;i>=this.#Ji;)i-=this.#Ji,this.nextDay();for(;i<0;)i+=this.#Ji,this.prevDay();this.currentSeconds=i,this.updateWeatherTimer((e*this.#Yi+t*this.#Xi+r)/this.#Xi)}getTime({withSeconds:e=!1,hourSize:t=this.#Yi,minuteSize:r=this.#Xi}={}){Jr(this.#hr);const i=Math.floor(this.currentSeconds/t),s=Math.floor(this.currentSeconds%t/r),n=this.currentSeconds%r;return{hour:i,minute:s,second:n,formatted:`${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`+(e?`:${n.toString().padStart(2,"0")}`:"")}}isDay(){return Jr(this.#hr),this.#es<this.#ts?this.#ss>=this.#es*this.#Xi&&this.#ss<this.#ts*this.#Xi:this.#ss>=this.#es*this.#Xi||this.#ss<this.#ts*this.#Xi}minutesUntilDay(){return this.timeUntil(this.#es,"minutes")}secondsUntilDay(){return this.timeUntil(this.#es,"seconds")}hoursUntilDay(){return this.timeUntil(this.#es,"hours")}minutesUntilNight(){return this.timeUntil(this.#ts,"minutes")}secondsUntilNight(){return this.timeUntil(this.#ts,"seconds")}hoursUntilNight(){return this.timeUntil(this.#ts,"hours")}timeUntil(e,t){Jr(this.#hr);let r=e*this.#Yi-this.#is;switch(r<=0&&(r+=this.#Ji),t){case"minutes":return r/this.#Xi;case"hours":return r/this.#Yi;default:return r}}setTo(e){Jr(this.#hr),"day"===e?this.setTime({hour:this.#es}):"night"===e&&this.setTime({hour:this.#ts})}nextDay(e=1){Jr(this.#hr);for(let t=0;t<e;t++){this.#as++;const e=this.#us[this.#ls-1];if(Number.isNaN(e)||!Number.isFinite(e))throw new Error("Invalid month day count: monthDays must be a finite number.");this.#as>e&&(this.#as=1,this.#ls++,this.#ls>this.#us.length&&(this.#ls=1,this.#hs++)),this.updateSeason(),this.advanceMoons(1)}}prevDay(e=1){Jr(this.#hr);for(let t=0;t<e;t++)this.#as--,this.#as<1&&(this.#ls--,this.#ls<1&&(this.#ls=this.#us.length,this.#hs--),this.#as=this.#us[this.#ls-1]||30),this.updateSeason(),this.rewindMoons(1)}updateSeason(){Jr(this.#hr),this.#Qi.forEach((e,t)=>{e.includes(this.#ls)&&(this.#os=t)})}setWeatherConfig(e){Jr(this.#hr),this.#cs={...this.#cs,...e}}setWeatherDuration(e,t){Jr(this.#hr),this.#ds.min=e,this.#ds.max=t}updateWeatherTimer(e){Jr(this.#hr),this.#ms-=e,this.#ms<=0&&this.chooseNewWeather()}forceWeather({where:e="main",type:t,duration:r=null}){Jr(this.#hr);const i=this.#rs;i[e]=t,this.weather=i,this.#ms=r??this._randomInRange(this.#ds.min,this.#ds.max)}chooseNewWeather({customWeather:e,where:t="main"}={}){Jr(this.#hr);let r={};const i=e=>{for(const[t,i]of Object.entries(e)){let e=i;"function"==typeof e&&(e=e({hour:Math.floor(this.#ss/this.#Xi),minute:this.#ss%this.#Xi,currentMinutes:this.#ss,isDay:this.isDay(),season:this.#os,weather:this.#rs})),"number"!=typeof e||Number.isNaN(e)||(r[t]=(r[t]||0)+e)}};i(this.#cs.default||{});for(const e in this.#cs.hours){const[t,r]=e.split("-").map(e=>{const[t,r]=e.split(":").map(Number);return t*this.#Xi+(r||0)}),s=this.#ss;(t<=r?s>=t&&s<=r:s>=t||s<=r)&&i(this.#cs.hours[e])}this.isDay()&&this.#cs.day?i(this.#cs.day):!this.isDay()&&this.#cs.night&&i(this.#cs.night),this.#cs.seasons?.[this.#os]&&i(this.#cs.seasons[this.#os]),e&&"object"==typeof e&&i(e);const s=Object.entries(r).filter(([,e])=>e>0);if(!s.length)return this.#rs[t]=null,null;const n=s.reduce((e,[,t])=>e+t,0);let o=Math.random()*n;for(const[e,r]of s){if(o<r)return this.#rs[t]=e,this.#ms=this._randomInRange(this.#ds.min,this.#ds.max),e;o-=r}return this.#rs[t]=null,null}_randomInRange(e,t){return Math.floor(Math.random()*(t-e+1))+e}addMoon(e,t,r,i=0){Jr(this.#hr);const s=Math.max(1,t);return this.#Zi.push({name:e,cycleLength:s,currentPhase:(i%s+s)%s,phaseNames:r}),this.#Zi.length-1}removeMoon(e){Jr(this.#hr),this.#Zi=this.#Zi.filter(t=>t.name!==e)}advanceMoons(e=1){for(const t in this.#Zi)this.advanceMoon(parseInt(t),e)}rewindMoons(e=1){for(const t in this.#Zi)this.rewindMoon(parseInt(t),e)}advanceMoon(e,t=1){Jr(this.#hr);const r=this.#Zi[e];if(!r)throw new RangeError(`No moon found at index ${e}`);r.currentPhase=(r.currentPhase+t)%r.cycleLength}rewindMoon(e,t=1){Jr(this.#hr);const r=this.#Zi[e];if(!r)throw new RangeError(`No moon found at index ${e}`);r.currentPhase=(r.currentPhase-t+r.cycleLength)%r.cycleLength}moonExists(e){return Jr(this.#hr),!!this.#Zi[e]}getMoon(e){let t;if(Jr(this.#hr),"number"==typeof e){if(t=this.#Zi[e],!t)throw new RangeError(`No moon found at index ${e}`)}else{if(!e||"object"!=typeof e||"string"!=typeof e.name||"number"!=typeof e.cycleLength||"number"!=typeof e.currentPhase)throw new TypeError("Invalid moon reference. Expected a number index or a MoonRaw object, received "+typeof e);t=e}return{name:t.name,phaseIndex:t.currentPhase,phaseName:t.phaseNames?t.phaseNames[t.currentPhase]??String(t.currentPhase):String(t.currentPhase),cycleLength:t.cycleLength}}destroy(){this.#hr||(this.#Qi.clear(),this.#Zi.length=0,this.#es=0,this.#ts=0,this.#is=0,this.#ss=0,this.#ns=0,this.#as=1,this.#ls=1,this.#hs=1,this.#ms=0,this.#os="",this.#rs={main:null},this.#us=[],this.#cs.default={},this.#cs.day={},this.#cs.night={},this.#cs.hours={},this.#cs.seasons={},this.#ds={min:0,max:0},this.#hr=!0)}},Xr=le("TinyAdvancedRaffle"),Qr=e().EventEmitter;class Zr extends Qr{#hr=!1;#ps;#fs;#ys=[];#gs=[];#ws=[];#bs=new Map;#vs=new Set;#Es=new Map;#Ts;#Ss=new Map;#xs=new Map;get isDestroyed(){return this.#hr}get freq(){return Xr(this.#hr),Object.fromEntries(this.#xs)}get size(){return Xr(this.#hr),this.#Ss.size}get normalization(){return Xr(this.#hr),this.#ps}set normalization(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("normalization must be a non-empty string (e.g., 'relative', 'softmax').");this.#ps=e}get seed(){return Xr(this.#hr),this.#fs}set seed(e){if(Xr(this.#hr),null!==e&&("number"!=typeof e||!Number.isFinite(e)))throw new TypeError("seed must be a finite number or null.");this.#fs=e,null!==e&&(this.#Ts=this._makeSeededRng(e))}get globalModifiers(){return Xr(this.#hr),[...this.#ys]}set globalModifiers(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>"function"==typeof e))throw new TypeError("globalModifiers must be an array of functions (WeightsCallback).");this.#ys=e}get temporaryModifiers(){return Xr(this.#hr),[...this.#gs]}set temporaryModifiers(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>e&&"function"==typeof e.fn&&Number.isInteger(e.uses)&&e.uses>0))throw new TypeError("temporaryModifiers must be an array of objects { fn: function, uses: positive integer }.");this.#gs=e}get conditionalRules(){return Xr(this.#hr),[...this.#ws]}set conditionalRules(e){if(Xr(this.#hr),!Array.isArray(e)||!e.every(e=>"function"==typeof e))throw new TypeError("conditionalRules must be an array of functions (WeightsCallback).");this.#ws=e}get pitySystems(){return Xr(this.#hr),Object.fromEntries(this.#bs)}set pitySystems(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e&&"number"==typeof e.threshold&&"number"==typeof e.increment&&"number"==typeof e.cap&&"number"==typeof e.counter&&"number"==typeof e.currentAdd)))throw new TypeError("pitySystems must be a Map<string, Pity> with all numeric fields.");this.#bs=e}get exclusions(){return Xr(this.#hr),Array.from(this.#vs)}set exclusions(e){if(Xr(this.#hr),!(e instanceof Set&&[...e].every(e=>"string"==typeof e)))throw new TypeError("exclusions must be a Set<string>.");this.#vs=e}get groups(){Xr(this.#hr);const e={};return this.#Es.forEach((t,r)=>e[r]=Array.from(t)),e}set groups(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e instanceof Set&&[...e].every(e=>"string"==typeof e))))throw new TypeError("groups must be a Map<string, Set<string>>.");this.#Es=e}get rng(){return Xr(this.#hr),this.#Ts}set rng(e){if(Xr(this.#hr),"function"!=typeof e||"number"!=typeof e())throw new TypeError("rng must be a function returning a number (RngGenerator).");this.#Ts=e}get items(){Xr(this.#hr);const e={};return this.#Ss.forEach((t,r)=>{e[r]={...t,groups:Array.from(t.groups)}}),e}set items(e){if(Xr(this.#hr),!(e instanceof Map&&[...e.values()].every(e=>e&&"string"==typeof e.id&&"string"==typeof e.label&&"number"==typeof e.baseWeight&&e.groups instanceof Set&&"boolean"==typeof e.locked&&"object"==typeof e.meta)))throw new TypeError("items must be a Map<string, ItemData> with valid item structures.");this.clearList(),this.#Ss=e}constructor(e={}){super();const{rng:t=null,seed:r=null,normalization:i="relative"}=e;this.#ps=i,this.#fs=r,"function"==typeof t?this.#Ts=t:null!==this.#fs?this.#Ts=this._makeSeededRng(this.#fs):this.#Ts=Math.random,this.#fs=r??null}hasItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#Ss.has(e)}addItem(e,t={}){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");if("object"!=typeof t||null===t)throw new TypeError("opts must be an object");let{weight:r=1,label:i=e,meta:s={},groups:n=[]}=t;if("number"!=typeof r||!Number.isFinite(r)||r<0)throw new TypeError("weight must be a non-negative number");if("string"!=typeof i)throw new TypeError("label must be a string");if("object"!=typeof s||null===s)throw new TypeError("meta must be an object");if(!(Array.isArray(n)||n instanceof Set))throw new TypeError("groups must be an array or a Set of strings");n=Array.isArray(n)?n:[...n];for(const e of n)if("string"!=typeof e)throw new TypeError("groups must contain only strings");const o={id:e,label:i,baseWeight:Math.max(0,Number(r)||0),meta:{...s},groups:new Set(n),locked:!1};this.#Ss.set(e,o);for(const t of n)this._ensureGroup(t).add(e);return this.emit("itemAdded",o),o}removeItem(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");const t=this.#Ss.get(e);if(!t)return!1;for(const r of t.groups){const t=this.#Es.get(r);t&&t.delete(e)}return this.#Ss.delete(e),this.emit("itemRemoved",e),this.resetFreq(e),this.resetPity(e),!0}setBaseWeight(e,t){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");if("number"!=typeof t||!Number.isFinite(t)||t<0)throw new TypeError("weight must be a non-negative number");const r=this.#Ss.get(e);if(!r)throw new Error("Item not found");r.baseWeight=Math.max(0,Number(t)||0),this.emit("weightChanged",{id:e,weight:r.baseWeight})}getItem(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("id must be a non-empty string");return this.#Ss.get(e)??null}listItems(){return Xr(this.#hr),Array.from(this.#Ss.values()).map(e=>({...e}))}clearList(){Xr(this.#hr),this.#Ss.clear(),this.clearFreqs(),this.clearPities()}hasGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");return this.#ys.includes(e)}addGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");this.#ys.push(e)}removeGlobalModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");this.#ys=this.#ys.filter(t=>t!==e)}hasTemporaryModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");return this.#gs.some(t=>t.fn===e)}addTemporaryModifier(e,t=1){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");if("number"!=typeof t||Number.isNaN(t))throw new TypeError("uses must be a number");this.#gs.push({fn:e,uses:Math.max(1,Math.floor(t))})}removeTemporaryModifier(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("fn must be a function");const t=this.#gs.length;return this.#gs=this.#gs.filter(t=>t.fn!==e),this.#gs.length!==t}hasConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");return this.#ws.includes(e)}addConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");this.#ws.push(e)}removeConditionalRule(e){if(Xr(this.#hr),"function"!=typeof e)throw new TypeError("ruleFn must be a function");const t=this.#ws.length;return this.#ws=this.#ws.filter(t=>t!==e),this.#ws.length!==t}hasPity(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#bs.has(e)}configurePity(e,t){if(Xr(this.#hr),!this.#Ss.has(e))throw new Error("Item not found");if("object"!=typeof t||null===t)throw new TypeError("cfg must be an object");const{threshold:r,increment:i,cap:s=1/0}=t;if("number"!=typeof r||r<=0)throw new TypeError("threshold must be a positive number");if("number"!=typeof i)throw new TypeError("increment must be a number");if("number"!=typeof s)throw new TypeError("cap must be a number");this.#bs.set(e,{threshold:Math.max(1,r),increment:Number(i)||0,cap:Number(s)||1/0,counter:0,currentAdd:0})}resetPity(e){if(Xr(this.#hr),"string"!=typeof e||!e.trim())throw new TypeError("itemId must be a non-empty string");const t=this.#bs.get(e);t&&(t.counter=0,t.currentAdd=0)}clearPities(){Xr(this.#hr),this.#bs.clear()}hasExclusion(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");return this.#vs.has(e)}excludeItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#vs.add(e)}includeItem(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#vs.delete(e)}_ensureGroup(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("name must be a string");let t=this.#Es.get(e);return t||(t=new Set,this.#Es.set(e,t)),t}hasInGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Es.get(t);return!!r&&r.has(e)}addToGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Ss.get(e);if(!r)throw new Error("Item missing");r.groups.add(t),this._ensureGroup(t).add(e)}removeFromGroup(e,t){if(Xr(this.#hr),"string"!=typeof e||"string"!=typeof t)throw new TypeError("itemId and groupName must be strings");const r=this.#Es.get(t);r&&r.delete(e);const i=this.#Ss.get(e);i&&i.groups.delete(t)}clearFreqs(){Xr(this.#hr),this.#xs.clear()}resetFreq(e){if(Xr(this.#hr),"string"!=typeof e)throw new TypeError("itemId must be a string");this.#xs.delete(e)}computeEffectiveWeights(e={}){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("computeEffectiveWeights: parameter 'context' must be a non-null object, got "+typeof e);if("previousDraws"in e&&!Array.isArray(e.previousDraws))throw new TypeError("computeEffectiveWeights: context.previousDraws must be an array if provided, got "+typeof e.previousDraws);if("metadata"in e&&void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata))throw new TypeError("computeEffectiveWeights: context.metadata must be a non-null object if provided, got "+typeof e.metadata);const t=new Map;for(const[e,r]of this.#Ss)t.set(e,r.baseWeight);for(const r of this.#ys){const i=r(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const r of this.#gs){const i=r.fn(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const r of this.#ws){const i=r(t,e);if(i instanceof Map)for(const[e,r]of i)t.set(e,Math.max(0,(t.get(e)||0)+r))}for(const[e,r]of this.#bs)if(t.has(e)&&r.counter>r.threshold){r.currentAdd=Math.min(r.cap,r.currentAdd+r.increment);const i=t.get(e);i&&t.set(e,i+r.currentAdd)}for(const e of this.#vs)t.delete(e);for(const[e,r]of Array.from(t.entries()))r>0||t.delete(e);return t}_weightsToDistribution(e){if(!(e instanceof Map))throw new TypeError("_weightsToDistribution: parameter 'weights' must be a Map, got "+typeof e);for(const[t,r]of e){if("string"!=typeof t)throw new TypeError("_weightsToDistribution: weights Map key must be string, got "+typeof t);if("number"!=typeof r||!Number.isFinite(r)||r<0)throw new TypeError(`_weightsToDistribution: weights Map value must be finite non-negative number, got ${r} for key ${t}`)}const t=Array.from(e.entries()).map(([e,t])=>({id:e,weight:t}));if(0===t.length)return[];if("softmax"===this.#ps){const e=Math.max(...t.map(e=>e.weight)),r=t.map(t=>Math.exp(t.weight-e)),i=r.reduce((e,t)=>e+t,0);let s=0;return t.map((e,t)=>{const n=r[t]/i;return s+=n,{id:e.id,weight:e.weight,p:n,cumulative:s}})}{const e=t.reduce((e,t)=>e+t.weight,0);let r=0;return t.map(t=>{const i=t.weight/e;return r+=i,{id:t.id,weight:t.weight,p:i,cumulative:r}})}}drawOne(e={}){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("drawOne: parameter 'opts' must be a non-null object, got "+typeof e);if("previousDraws"in e&&!Array.isArray(e.previousDraws))throw new TypeError("drawOne: opts.previousDraws must be an array if provided, got "+typeof e.previousDraws);if("metadata"in e&&void 0!==e.metadata&&("object"!=typeof e.metadata||null===e.metadata))throw new TypeError("drawOne: opts.metadata must be a non-null object if provided, got "+typeof e.metadata);const t={previousDraws:e.previousDraws??[],metadata:e.metadata??{},activeModifiers:[...this.#gs]},r=this.computeEffectiveWeights(t),i=this._weightsToDistribution(r);if(!i.length)return null;const s=this.#Ts(),n=i.find(e=>s<=e.cumulative)??i[i.length-1];for(const[e,t]of this.#bs)e===n.id?(t.counter=0,t.currentAdd=0):t.counter++;this._consumeTemporaryModifiers();const o=this.#Ss.get(n.id);if(!o)return null;const a={id:o.id,label:o.label,meta:{...o.meta},prob:n.p};return this.emit("draw",a),a&&this.#xs.set(a.id,(this.#xs.get(a.id)||0)+1),a}_consumeTemporaryModifiers(){for(let e=this.#gs.length-1;e>=0;--e){const t=this.#gs[e];t.uses-=1,t.uses<=0&&this.#gs.splice(e,1)}}drawMany(e=1,t={}){if(Xr(this.#hr),!Number.isInteger(e)||e<=0)throw new TypeError(`drawMany: parameter 'count' must be a positive integer, got ${e}`);if("object"!=typeof t||null===t)throw new TypeError("drawMany: parameter 'opts' must be a non-null object, got "+typeof t);if("withReplacement"in t&&"boolean"!=typeof t.withReplacement)throw new TypeError("drawMany: opts.withReplacement must be boolean if provided, got "+typeof t.withReplacement);if("ensureUnique"in t&&"boolean"!=typeof t.ensureUnique)throw new TypeError("drawMany: opts.ensureUnique must be boolean if provided, got "+typeof t.ensureUnique);if("metadata"in t&&void 0!==t.metadata&&("object"!=typeof t.metadata||null===t.metadata))throw new TypeError("drawMany: opts.metadata must be a non-null object if provided, got "+typeof t.metadata);if("previousDraws"in t&&!Array.isArray(t.previousDraws))throw new TypeError("drawMany: opts.previousDraws must be an array if provided, got "+typeof t.previousDraws);const r=t.withReplacement??!0,i=t.ensureUnique??!1,s=[],n=t.previousDraws??[];if(!r&&i){const r=new Set;for(let i=0;i<e;++i){const e=new Set(this.#vs);for(const e of r)this.#vs.add(e);const i=this.drawOne({previousDraws:n,metadata:t.metadata});if(this.#vs=e,!i)break;s.push(i),r.add(i.id),n.push(i)}return s}for(let i=0;i<e;++i){const e=this.drawOne({previousDraws:n,metadata:t.metadata});if(!e)break;s.push(e),n.push(e),r||this.excludeItem(e.id)}if(!r)for(const e of s)this.includeItem(e.id);return s}exportToJson(){return Xr(this.#hr),{items:Array.from(this.#Ss.values()).map(e=>({id:e.id,label:e.label,baseWeight:e.baseWeight,meta:e.meta,groups:Array.from(e.groups),locked:!1})),pity:Array.from(this.#bs.entries()),exclusions:Array.from(this.#vs),normalization:this.#ps,seed:this.#fs}}loadFromJson(e){if(Xr(this.#hr),"object"!=typeof e||null===e)throw new TypeError("data must be a non-null object");if(!Array.isArray(e.items)||!Array.isArray(e.pity)||!Array.isArray(e.exclusions))throw new TypeError("data must have items, pity, and exclusions arrays");if("string"!=typeof e.normalization)throw new TypeError("data.normalization must be a string");if(void 0!==e.seed&&null!==e.seed&&"number"!=typeof e.seed)throw new TypeError("data.seed must be a number, null, or undefined");this.clearList();for(const t of e.items){if("object"!=typeof t||null===t)throw new TypeError("Each item must be a non-null object");if("string"!=typeof t.id||!t.id.trim())throw new TypeError("Each item.id must be a non-empty string");if("string"!=typeof t.label)throw new TypeError(`Item with id "${t.id}" has invalid label; must be string`);if("number"!=typeof t.baseWeight||!Number.isFinite(t.baseWeight)||t.baseWeight<0)throw new TypeError(`Item with id "${t.id}" has invalid baseWeight; must be a finite non-negative number`);if(void 0!==t.groups&&!Array.isArray(t.groups))throw new TypeError(`Item with id "${t.id}" has invalid groups; must be an array of strings`);if(t.groups&&!t.groups.every(e=>"string"==typeof e))throw new TypeError(`Item with id "${t.id}" has groups containing non-string values`);if(void 0!==t.meta&&("object"!=typeof t.meta||null===t.meta))throw new TypeError(`Item with id "${t.id}" has invalid meta; must be an object`);this.#Ss.set(t.id,{id:t.id,label:t.label,baseWeight:t.baseWeight,meta:t.meta||{},groups:new Set(t.groups||[]),locked:!1});for(const e of t.groups||[])this._ensureGroup(e).add(t.id)}this.pitySystems=new Map(e.pity||[]),this.exclusions=new Set(e.exclusions||[]),this.normalization=e.normalization,void 0!==e.seed&&(this.seed=e.seed)}clone(){Xr(this.#hr);const e=new Zr;return e.#ps=this.#ps,e.#fs=this.#fs,e.#ys=[...this.#ys],e.#gs=this.#gs.map(e=>({fn:e.fn,uses:e.uses})),e.#ws=[...this.#ws],e.#bs=new Map([...this.#bs.entries()].map(([e,t])=>[e,{...t}])),e.#vs=new Set(this.#vs),e.#Es=new Map([...this.#Es.entries()].map(([e,t])=>[e,new Set(t)])),e.#Ts=this.#Ts,e.#Ss=new Map([...this.#Ss.entries()].map(([e,t])=>[e,{...t,groups:new Set(t.groups),meta:{...t.meta}}])),e.#xs=new Map(this.#xs),e}_makeSeededRng(e){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError("seed must be a finite number");let t=e>>>0;return function(){t+=1831565813;let e=Math.imul(t^t>>>15,1|t);return e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}destroy(){this.#hr||(this.#bs.clear(),this.#vs.clear(),this.#Es.clear(),this.#Ss.clear(),this.#xs.clear(),this.#ys=[],this.#gs=[],this.#ws=[],this.#fs=null,this.#hr=!0)}}const ei=Zr,ti=class{#ie;get data(){return this.#ie}set data(e){if(!(Array.isArray(e)||e instanceof Set))throw new TypeError("Paginator expects an array or Set as data source.");this.#ie=e}get size(){return Array.isArray(this.#ie)?this.#ie.length:this.#ie.size}constructor(e){if(!(Array.isArray(e)||e instanceof Set))throw new TypeError("Paginator expects an array or Set as data source.");this.#ie=e}get({page:e,perPage:t,filter:r}){if(!Number.isInteger(e)||e<1)throw new RangeError("Page number must be a positive integer.");if(!Number.isInteger(t)||t<1)throw new RangeError("Items per page must be a positive integer.");const i=Array.isArray(this.#ie)?this.#ie:Array.from(this.#ie);let s=i;if(r)if("function"==typeof r)s=i.filter((e,t,i)=>r(e,t,i));else{if("object"!=typeof r)throw new TypeError("Filter must be an object or a function");s=i.filter(e=>Object.entries(r).every(([t,r])=>{const i=e[t];return r instanceof RegExp?r.test(i):i===r}))}else s=i;const n=s.length,o=Math.max(1,Math.ceil(n/t)),a=Math.min(e,o),l=(a-1)*t,h=l+t,u=a>1,c=a<o;return{items:s.slice(l,h),page:a,perPage:t,totalItems:n,totalPages:o,hasPrev:u,hasNext:c}}};class ri{static#As=new Map;static get itemRegistry(){const e={},t=Object.fromEntries(ri.#As);for(const r in t)e[r]={...t[r],metadata:{...t[r].metadata}};return e}static defineItem(e){if(!e||"object"!=typeof e)throw new TypeError("Config must be a valid object.");if(!e.id||"string"!=typeof e.id)throw new TypeError("Item must have a valid string 'id'.");if(void 0!==e.weight&&("number"!=typeof e.weight||e.weight<0))throw new TypeError(`weight must be a number >= 0. Received: ${e.weight}`);if(void 0!==e.maxStack&&(!Number.isInteger(e.maxStack)||e.maxStack<=0))throw new TypeError(`maxStack must be a positive integer. Received: ${e.maxStack}`);if(void 0!==e.metadata&&"object"!=typeof e.metadata)throw new TypeError("metadata must be an object.");if(void 0!==e.onUse&&null!==e.onUse&&"function"!=typeof e.onUse)throw new TypeError("onUse must be a function or null.");if(void 0!==e.type&&null!==e.type&&"string"!=typeof e.type)throw new TypeError("type must be a string or null.");ri.#As.set(e.id,{id:e.id,weight:e.weight||0,maxStack:e.maxStack||1,metadata:e.metadata||{},type:e.type??null,onUse:"function"==typeof e.onUse?e.onUse:null})}static removeItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");return ri.#As.delete(e)}static hasItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");return ri.#As.has(e)}static getItem(e){if("string"!=typeof e)throw new TypeError("itemId must be a string.");const t=ri.#As.get(e);if(!t)throw new Error(`Item '${e}' not defined in registry.`);return t}#Cs=new Map;#Is={add:[],remove:[],use:[],set:[]};#Ss=[];#ks;#Ds;#Ms;#Ls;get maxStack(){return this.#ks}set maxStack(e){if(!Number.isInteger(e)||Number.isFinite(e)&&e<=0)throw new TypeError(`maxStack must be a positive integer. Received: ${e}`);this.#ks=e}get maxSize(){return this.#Ds}set maxSize(e){if(null!==e&&(!Number.isInteger(e)||e<=0))throw new TypeError(`maxSize must be null or a positive integer. Received: ${e}`);this.#Ds=e}get maxSlots(){return this.#Ms}set maxSlots(e){if(null!==e&&(!Number.isInteger(e)||e<=0))throw new TypeError(`maxSlots must be null or a positive integer. Received: ${e}`);this.#Ms=e}get maxWeight(){return this.#Ls}set maxWeight(e){if(null!==e&&("number"!=typeof e||e<=0))throw new TypeError(`maxWeight must be null or a positive number. Received: ${e}`);this.#Ls=e}get events(){return{add:[...this.#Is.add],remove:[...this.#Is.remove],use:[...this.#Is.use],set:[...this.#Is.set]}}get items(){return[...this.#Ss].map(e=>e?this.#Ns(e):null)}get specialSlots(){return new Map([...this.#Cs.entries()].map(([e,t])=>[e,{type:t.type,item:t.item?this.#Ns(t.item):null}]))}get size(){const e=this.getAllItems();let t=0;for(const r of e)t+=r.quantity;return t}get slotsSize(){return this.getAllItems().length}get weight(){return this.getAllItems().reduce((e,t)=>{const r=ri.getItem(t.id);return e+(r?.weight||0)*t.quantity},0)}_cleanNulls(){let e=this.#Ss.length-1;for(;e>=0&&null===this.#Ss[e];)e--;this.#Ss=this.#Ss.slice(0,e+1)}constructor(e={}){if("object"!=typeof e||null===e)throw new TypeError("`options` must be an object.");if(void 0!==e.maxWeight&&null!==e.maxWeight&&"number"!=typeof e.maxWeight)throw new TypeError("`maxWeight` must be a number or null.");if(void 0!==e.maxSlots&&null!==e.maxSlots&&"number"!=typeof e.maxSlots)throw new TypeError("`maxSlots` must be a number or null.");if(void 0!==e.maxSize&&null!==e.maxSize&&"number"!=typeof e.maxSize)throw new TypeError("`maxSize` must be a number or null.");if(void 0!==e.maxStack&&"number"!=typeof e.maxStack)throw new TypeError("`maxStack` must be a number.");if(void 0!==e.specialSlots&&"object"!=typeof e.specialSlots)throw new TypeError("`specialSlots` must be an object if defined.");if(this.#Ls=e.maxWeight??null,this.#Ms=e.maxSlots??null,this.#Ds=e.maxSize??null,this.#ks=e.maxStack??1/0,e.specialSlots)for(const t in e.specialSlots){const r=e.specialSlots[t];if("object"!=typeof r||null===r)throw new TypeError("Each `specialSlot` entry must be an object.");if(void 0!==r.type&&null!==r.type&&"string"!=typeof r.type)throw new TypeError("`specialSlot.type` must be a string or null.");this.#Cs.set(t,{type:r.type??null,item:null})}}hasSpace({weight:e=0,sizeLength:t=0,slotsLength:r=0}={}){if("number"!=typeof e)throw new TypeError("`weight` must be a number.");if("number"!=typeof t)throw new TypeError("`sizeLength` must be a number.");if("number"!=typeof r)throw new TypeError("`slotsLength` must be a number.");return!(this.areFull(t)||this.areFullSlots(r)||this.isHeavy(e))}isHeavy(e=0){if("number"!=typeof e)throw new TypeError("`extraWeight` must be a number.");return null!==this.#Ls&&this.weight+e>this.#Ls}areFull(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ds&&this.size+e>this.#Ds}isFull(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ds&&this.size+e>=this.#Ds}areFullSlots(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ms&&this.slotsSize+e>this.#Ms}isFullSlots(e=0){if("number"!=typeof e)throw new TypeError("`extraLength` must be a number.");return null!==this.#Ms&&this.slotsSize+e>=this.#Ms}#_s(e,t){if("string"!=typeof e)throw new TypeError("`type` must be a string.");if("object"!=typeof t||null===t)throw new TypeError("`payload` must be an object.");if(this.#Is[e])for(const r of this.#Is[e])r(t)}off(e,t){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");if("function"!=typeof t)throw new TypeError("`callback` must be a function.");if(!this.#Is[e])return;const r=this.#Is[e],i=r.indexOf(t);-1!==i&&r.splice(i,1)}offAll(e){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");this.#Is[e]&&(this.#Is[e]=[])}cloneEventCallbacks(e){if("string"!=typeof e)throw new TypeError("`eventType` must be a string.");return this.#Is[e]?[...this.#Is[e]]:[]}onAddItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.add.push(e)}onSetItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.set.push(e)}onRemoveItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.remove.push(e)}onUseItem(e){if("function"!=typeof e)throw new TypeError("`callback` must be a function.");this.#Is.use.push(e)}compactInventory(){this.#Ss=this.#Ss.filter((e,t)=>{const r=null!==e;return r||this.#_s("remove",{index:t,item:null,isCollection:!0,specialSlot:null,remove:()=>{}}),r})}addItem({itemId:e,quantity:t=1,metadata:r={},forceSpace:i=!1}){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw new TypeError("`quantity` must be a positive number.");if("object"!=typeof r||null===r)throw new TypeError("`metadata` must be an object.");if("boolean"!=typeof i)throw new TypeError("`forceSpace` must be a boolean.");const s=ri.getItem(e);let n=t;const o=s.maxStack<=this.#ks?s.maxStack:this.#ks,a=[],l=(e,t)=>JSON.stringify(e)===JSON.stringify(t);let h=!0;for(;n>0&&h;){h=!1;for(const t in this.#Ss){const u=this.#Ss[t];if(u&&u.id===e&&u.quantity<o&&l(u.metadata,r)){const e=Math.min(o-u.quantity,n);if(!i&&!this.hasSpace({weight:s.weight*e,sizeLength:e}))continue;u.quantity+=e,n-=e,h=!0;const r=Number(t),l=a.findIndex(e=>e.index===r);if(l<0?a.push({index:r,quantity:e}):a[l].quantity+=e,this.#_s("add",{item:this.#Ns(u),index:r,isCollection:!0,specialSlot:null,remove:this.#Rs({locationType:"normal",slotIndex:r,forceSpace:i,item:u})}),n<=0)break}}}if(n>0)for(const t in this.#Ss)if(null===this.#Ss[t]){const l=Math.min(o,n);if(!i&&!this.hasSpace({weight:s.weight*l,sizeLength:l}))continue;const h={id:e,quantity:l,metadata:r};this.#Ss[t]=h,n-=l;const u=Number(t),c=a.findIndex(e=>e.index===u);if(c<0?a.push({index:u,quantity:l}):a[c].quantity+=l,this.#_s("add",{item:this.#Ns(h),index:u,isCollection:!0,specialSlot:null,remove:this.#Rs({locationType:"normal",slotIndex:u,forceSpace:i,item:h})}),n<=0)break}for(;n>0;){const t=Math.min(o,n);if(!i&&!this.hasSpace({weight:s.weight*t,sizeLength:t,slotsLength:1}))break;const l={id:e,quantity:t,metadata:r};this.#Ss.push(l);const h=this.#Ss.length-1,u=a.findIndex(e=>e.index===h);u<0?a.push({index:h,quantity:t}):a[u].quantity+=t,this.#_s("add",{item:this.#Ns(l),index:h,isCollection:!0,specialSlot:null,remove:this.#Rs({locationType:"normal",slotIndex:h,forceSpace:i,item:l})}),n-=t}return{remaining:n,placesAdded:a}}getItemFrom(e){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if(e<0||e>=this.#Ss.length)throw new Error(`Slot index '${e}' out of bounds .`);return this.#Ss[e]?this.#Ns(this.#Ss[e]):null}setItem({slotIndex:e,item:t,forceSpace:r=!1}){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be a boolean.");const i=t&&"object"==typeof t&&"string"==typeof t.id&&"number"==typeof t.quantity&&!Number.isNaN(t.quantity)&&Number.isFinite(t.quantity)&&t.quantity>-1&&"object"==typeof t.metadata;if(null!==t&&!i)throw new Error("Invalid item type: must be null or a valid InventoryItem.");const s=t?ri.#As.get(t.id):null;if(null!==t&&!s)throw new Error(`Item '${t?.id??"unknown"}' not defined in registry.`);if(s&&t){const e=s.maxStack<=this.#ks?s.maxStack:this.#ks;if(t.quantity>e)throw new Error(`Item '${t.id}' exceeds max stack size. Allowed: ${e}, got: ${t.quantity}.`)}if(null!==this.#Ms&&(e<0||e>=this.#Ms))throw new Error(`Slot index ${e} out of range.`);const n=this.#Ss[e]??null,o=n?ri.#As.get(n.id)??null:null,a=(e,t)=>t?t.weight*(e?e.quantity:0):0,l=e=>e?e.quantity:0;if(!r&&!this.hasSpace({weight:a(t,s)-a(n,o),sizeLength:l(t)-l(n)}))throw new Error("Inventory is full or overweight.");for(;this.#Ss.length<=e;)this.#Ss.push(null);this.#Ss[e]=t,this._cleanNulls(),this.#_s("set",{index:e,isCollection:!0,item:t?this.#Ns(t):null,specialSlot:null,remove:t?this.#Rs({locationType:"normal",slotIndex:e,forceSpace:r,item:t}):()=>{}})}deleteItem(e,t=!1){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");if("boolean"!=typeof t)throw new TypeError("`forceSpace` must be a boolean.");this.setItem({slotIndex:e,item:null,forceSpace:t})}moveItem(e,t,r=!1){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`fromIndex` must be an integer.");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError("`toIndex` must be an integer.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be a boolean.");const i=this.#Ss[e];if(!i)throw new Error(`No item found in slot ${e}.`);this.setItem({slotIndex:t,item:i,forceSpace:r}),this.setItem({slotIndex:e,item:null,forceSpace:r})}removeItem({itemId:e,metadata:t=null,quantity:r=1}){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if(null!==t&&"object"!=typeof t)throw new TypeError("`metadata` must be an object or null.");if("number"!=typeof r||!Number.isFinite(r)||r<=0)throw new TypeError("`quantity` must be a positive number.");let i=r;const s=(e,t)=>JSON.stringify(e)===JSON.stringify(t);for(let r=0;r<this.#Ss.length;r++){const n=this.#Ss[r];if(n&&n.id===e&&(null===t||s(n.metadata,t))){const e=Math.min(n.quantity,i);n.quantity-=e,i-=e;const t=Number(r);if(n.quantity<=0&&(this.#Ss[r]=null),i<=0)return this._cleanNulls(),this.#_s("remove",{index:t,item:this.#Ns(n),isCollection:!0,specialSlot:null,remove:this.#Rs({locationType:"normal",slotIndex:t,item:n})}),!0}}return this._cleanNulls(),this.#Cs.forEach((r,n)=>{if(i>0&&r.item&&r.item.id===e&&(null===t||s(r.item.metadata,t))){const e=Math.min(r.item.quantity,i);r.item.quantity-=e,r.item.quantity<0&&(r.item.quantity=0),i-=e,r.item.quantity<=0&&(r.item=null),this.#Cs.set(n,r),this.#_s("remove",{index:null,item:r.item?this.#Ns(r.item):null,isCollection:!1,specialSlot:n,remove:r.item?this.#Rs({locationType:"special",specialSlot:n,item:r.item}):()=>{}})}}),i<=0}#Rs({locationType:e,specialSlot:t,slotIndex:r,item:i,forceSpace:s=!1}){if("normal"!==e&&"special"!==e)throw new TypeError("`locationType` must be 'normal' or 'special'.");if("boolean"!=typeof s)throw new TypeError("`forceSpace` must be boolean.");if(!i||"object"!=typeof i)throw new TypeError("`item` must be an InventoryItem object.");if("special"===e&&t&&"string"!=typeof t)throw new TypeError("`specialSlot` must be a string when locationType is 'special'.");if("normal"===e&&"number"!=typeof r)throw new TypeError("`slotIndex` must be a number when locationType is 'normal'.");return(n=s)=>{if("special"===e&&t){const e=this.#Cs.get(t);if(!e?.item)throw new Error(`Special slot '${t}' is empty.`);e.item.quantity>1?(e.item.quantity-=1,this.#Cs.set(t,e)):this.setSpecialSlot({slotId:t,item:null,forceSpace:n})}else{if("number"!=typeof r)throw new Error("Invalid remove operation: no valid slotIndex or specialSlot provided.");i.quantity>1?this.setItem({slotIndex:r,item:{...i,quantity:i.quantity-1},forceSpace:n}):this.setItem({slotIndex:r,item:null,forceSpace:n})}}}useItem({slotIndex:e,specialSlot:t,forceSpace:r=!1},...i){if(void 0!==e&&("number"!=typeof e||!Number.isInteger(e)))throw new TypeError("`slotIndex` must be an integer if provided.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("`specialSlot` must be a string if provided.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");let s=null,n="normal",o=null;if(t){if(!this.#Cs.has(t))throw new Error(`Special slot '${t}' not found.`);s=this.#Cs.get(t).item,n="special"}else o=this.#Ss,s=o[e??-1]??null,n="normal";if(!s)throw new Error("special"===n?`No item found in special slot '${t}'.`:`No item found in slot ${e} of inventory.`);const a=ri.getItem(s.id);if(a.onUse){const l={inventory:this,item:this.#Ns(s),index:e??null,specialSlot:t??null,isCollection:!!o,itemDef:a,remove:this.#Rs({locationType:n,specialSlot:t,slotIndex:e,forceSpace:r,item:s}),...i},h=a.onUse(l);return this.#_s("use",l),h}return null}hasSpecialSlot(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");return this.#Cs.has(e)}getSpecialItem(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const t=this.#Cs.get(e);return t?.item?this.#Ns(t.item):null}getSpecialSlotType(e){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const t=this.#Cs.get(e);return t?.type??null}setSpecialSlot({slotId:e,item:t,forceSpace:r=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' not found.`);const i=t&&"object"==typeof t&&"string"==typeof t.id&&"number"==typeof t.quantity&&!Number.isNaN(t.quantity)&&Number.isFinite(t.quantity)&&t.quantity>-1&&"object"==typeof t.metadata;if(null!==t&&!i)throw new Error("Invalid item type: must be null or a valid InventoryItem.");const s=t?ri.#As.get(t.id):null;if(null!==t&&!s)throw new Error(`Item '${t?.id??"unknown"}' not defined in registry.`);const n=this.#Cs.get(e);if(!n)throw new Error(`Special slot ${e} out of range for slot '${e}'.`);const o=n.item?ri.#As.get(n.item.id):null,a=(e,t)=>t?t.weight*(e?1:0):0,l=e=>e?1:0;if(!r&&!this.hasSpace({weight:a(t,s)-a(n.item,o),sizeLength:l(t)-l(n.item)}))throw new Error("Inventory is full or overweight.");n.item=t,this.#_s("set",{index:null,item:t?this.#Ns(t):null,isCollection:!1,specialSlot:e,remove:t?this.#Rs({locationType:"special",specialSlot:e,forceSpace:r,item:t}):()=>{}})}deleteSpecialItem(e,t=!1){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("boolean"!=typeof t)throw new TypeError("`forceSpace` must be boolean.");this.setSpecialSlot({slotId:e,item:null,forceSpace:t})}equipItem({slotId:e,slotIndex:t,quantity:r=1,forceSpace:i=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError("`slotIndex` must be an integer.");if("number"!=typeof r||!Number.isFinite(r)||r<=0)throw new TypeError("`quantity` must be a positive number.");if("boolean"!=typeof i)throw new TypeError("`forceSpace` must be boolean.");if(r<=0||!Number.isFinite(r))throw new Error(`Invalid quantity '${r}'.`);if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const s=this.getItemFrom(t);if(!s)throw new Error(`No item found in inventory slot ${t}.`);if(s.quantity<r)throw new Error(`Not enough quantity of item '${s.id}' in inventory slot.`);const n=ri.getItem(s.id),o=this.#Cs.get(e);if(!o)throw new Error(`Slot '${e}' not defined in registry.`);const a=o.type??null;if(null!==a&&n.type!==a)throw new Error(`Item '${s.id}' cannot be equipped in slot '${e}'.`);const l=Math.min(n.maxStack,this.#ks);if(o.item&&o.item.id===s.id){const t=Math.max(0,l-o.item.quantity);if(t<=0)return r;const i=Math.min(r,t);return this.removeItem({itemId:s.id,quantity:i,metadata:null}),o.item.quantity+=i,this.#Cs.set(e,o),r-i}o.item&&this.unequipItem({slotId:e,forceSpace:i});const h=Math.min(r,l);return this.removeItem({itemId:s.id,quantity:h,metadata:null}),o.item={id:s.id,quantity:h,metadata:s.metadata},this.#Cs.set(e,o),r-h}unequipItem({slotId:e,quantity:t=null,forceSpace:r=!1}){if("string"!=typeof e)throw new TypeError("`slotId` must be a string.");if(null!==t&&("number"!=typeof t||!Number.isFinite(t)||t<=0))throw new TypeError("`quantity` must be a positive number or null.");if("boolean"!=typeof r)throw new TypeError("`forceSpace` must be boolean.");if(!this.#Cs.has(e))throw new Error(`Special slot '${e}' does not exist.`);const i=this.#Cs.get(e);if(!i)throw new Error(`Slot '${e}' not defined in registry.`);if(!i.item)return!1;const s=i.item,n=null===t?s.quantity:t;if(n<=0)throw new Error(`Invalid unequip quantity: ${n}`);if(n>s.quantity)throw new Error(`Not enough items in slot '${e}' to unequip.`);return this.addItem({itemId:s.id,quantity:n,metadata:s.metadata,forceSpace:r}),n===s.quantity?i.item=null:(s.quantity-=n,i.item=s),this.#Cs.set(e,i),!0}#Ns(e){if(!e||"object"!=typeof e)throw new TypeError("`item` must be an InventoryItem object.");if("string"!=typeof e.id)throw new TypeError("`item.id` must be a string.");if("number"!=typeof e.quantity||!Number.isFinite(e.quantity))throw new TypeError("`item.quantity` must be a finite number.");if(!e.metadata||"object"!=typeof e.metadata)throw new TypeError("`item.metadata` must be an object.");return{id:e.id,quantity:e.quantity,metadata:{...e.metadata}}}getItemList(){return[...this.#Ss].map((e,t)=>[e?this.#Ns(e):null,t]).filter(e=>null!==e[0])}getAllItems(){const e=[...this.#Ss].filter(e=>null!==e).map(this.#Ns);return this.#Cs.forEach(t=>{const r=t.item;r&&e.push(r)}),e}getItemsByMetadata(e){if("function"!=typeof e)throw new TypeError("`filterFn` must be a function.");return this.getAllItems().filter(t=>{const r=ri.getItem(t.id);return e(r.metadata,t)})}findItem(e){if("function"!=typeof e)throw new TypeError("`predicate` must be a function.");return this.getAllItems().find(e)}findItems(e){if("function"!=typeof e)throw new TypeError("`predicate` must be a function.");return this.getAllItems().filter(e)}getItemCount(e){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");return this.getAllItems().filter(t=>t.id===e).reduce((e,t)=>e+t.quantity,0)}hasItem(e,t=1){if("string"!=typeof e)throw new TypeError("`itemId` must be a string.");if("number"!=typeof t||!Number.isFinite(t)||t<0)throw new TypeError("`quantity` must be a non-negative number.");return this.getItemCount(e)>=t}existsItemAt(e){if("number"!=typeof e||!Number.isInteger(e))throw new TypeError("`slotIndex` must be an integer.");return!!this.#Ss[e]}clear(){this.clearAllItems(),this.clearAllEvents()}clearAllEvents(){this.#Is={add:[],remove:[],use:[],set:[]}}clearAllItems(){this.clearItems(),this.clearSpecialItems()}clearItems(){for(let e=this.#Ss.length-1;e>=0;e--)this.#Ss[e]&&this.deleteItem(e,!0)}clearSpecialItems(){for(const e of this.#Cs.keys()){const t=this.#Cs.get(e);t?.item&&this.deleteSpecialItem(e,!0)}}clone(){const e=this.toObject();return ri.fromObject(e)}toObject(){const e={};for(const[t,r]of this.#Cs.entries())e[t]={type:r?.type??null,item:r?.item?this.#Ns(r.item):null};return{__schema:"TinyInventory",version:1,maxWeight:this.#Ls,maxSlots:this.#Ms,maxSize:this.#Ds,maxStack:this.#ks,items:this.#Ss.map(e=>e?this.#Ns(e):null),specialSlots:e}}toJSON(e=0){if("number"!=typeof e||!Number.isFinite(e)||e<0)throw new TypeError("`space` must be a non-negative number.");return JSON.stringify(this.toObject(),null,e)}static fromObject(e){if(!e||"object"!=typeof e)throw new TypeError("Invalid state: expected object.");if("TinyInventory"!==e.__schema||"number"!=typeof e.version)throw new TypeError("Invalid or missing schema header.");if(1!==e.version)throw new TypeError(`Unsupported TinyInventory state version: ${e.version}`);const t={};if(e.specialSlots&&"object"==typeof e.specialSlots)for(const r of Object.keys(e.specialSlots))t[r]={type:e.specialSlots[r]?.type??null};const r=new ri({maxWeight:e.maxWeight??null,maxSlots:e.maxSlots??null,maxSize:e.maxSize??null,maxStack:e.maxStack??null,specialSlots:t});if(Array.isArray(e.items))for(const t in e.items){const i=e.items[t];if(null!==i){const e={id:String(i.id),quantity:Math.max(1,Number(i.quantity)||1),metadata:i.metadata&&"object"==typeof i.metadata?i.metadata:{}};r.setItem({slotIndex:Number(t),item:e,forceSpace:!0})}else r.setItem({slotIndex:Number(t),item:null,forceSpace:!0})}if(e.specialSlots&&"object"==typeof e.specialSlots)for(const[t,i]of Object.entries(e.specialSlots)){if(!r.hasSpecialSlot(t))continue;const e=i?.item;if(e&&e.id){const i={id:String(e.id),quantity:Math.max(1,Number(e.quantity)||1),metadata:e.metadata&&"object"==typeof e.metadata?e.metadata:{}};r.setSpecialSlot({slotId:t,item:i,forceSpace:!0})}}return r}static fromJSON(e){if("string"!=typeof e)throw new TypeError("`json` must be a string.");const t=JSON.parse(e);return ri.fromObject(t)}}const ii=ri,si=class{#js=null;#Ps=null;get sender(){return this.#js}get receiver(){return this.#Ps}set sender(e){if(!(e instanceof ii&&this.receiver instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#js=e}set receiver(e){if(!(this.sender instanceof ii&&e instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#Ps=e}constructor(e,t){if(e||t){if(!(e instanceof ii&&t instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.connect(e,t)}}connect(e,t){if(!(e instanceof ii&&t instanceof ii))throw new Error("Both sender and receiver must be TinyInventory instances.");this.#js=e,this.#Ps=t}disconnect(){this.#js=null,this.#Ps=null}invert(){const e=this.#js,t=this.#Ps;this.#js=t,this.#Ps=e}transferItem({slotIndex:e,specialSlot:t,quantity:r=1,receiverSlotIndex:i,forceSpace:s=!1,strict:n=!1}){if(!this.#js||!this.#Ps)throw new Error("Sender and receiver inventories must be connected.");let o;if(t){if(o=this.#js.getSpecialItem(t),!o)throw new Error(`No item found in sender special slot '${t}'.`)}else{if("number"!=typeof e)throw new Error("Must provide either slotIndex or specialSlot.");if(o=this.#js.getItemFrom(e),!o)throw new Error(`No item found in sender slot ${e}.`)}if(o.quantity<r)throw new Error(`Sender does not have enough quantity of '${o.id}' to transfer.`);const a={id:o.id,quantity:r,metadata:o.metadata};let l;if(n)if("number"==typeof i){const e=this.#Ps.existsItemAt(i)?this.#Ps.getItemFrom(i):null;if(e){if(e.id!==a.id)throw new Error(`Receiver slot ${i} contains a different item.`);const t=ii.getItem(e.id).maxStack-e.quantity;if(a.quantity>t)throw new Error(`Strict mode: not enough space in receiver slot ${i}.`)}}else if(this.#Ps.clone().addItem({itemId:a.id,quantity:a.quantity,metadata:a.metadata,forceSpace:s}).remaining>0)throw new Error("Strict mode: not enough space in receiver inventory.");if("number"==typeof i){const e=this.#Ps.existsItemAt(i)?this.#Ps.getItemFrom(i):null;let t=a.quantity;if(e){if(e.id!==a.id)throw new Error(`Receiver slot ${i} contains a different item.`);const r=ii.getItem(e.id).maxStack-e.quantity;t=Math.min(r,a.quantity),t>0&&this.#Ps.setItem({slotIndex:i,item:{...e,quantity:e.quantity+t},forceSpace:s})}else this.#Ps.setItem({slotIndex:i,item:a,forceSpace:s});l={remaining:a.quantity-t}}else l=this.#Ps.addItem({itemId:a.id,quantity:a.quantity,metadata:a.metadata,forceSpace:s});const h=a.quantity-l.remaining;if(h>0)if(t)this.#js.unequipItem({slotId:t,quantity:h,forceSpace:s});else if("number"==typeof e){const t=o.quantity-h;this.#js.setItem({slotIndex:e,item:t>0?{...o,quantity:t}:null,forceSpace:s})}return l}transferMultiple(e){return e.map(e=>this.transferItem(e))}},ni=class{#Os;#vt={message:"We use cookies to improve your experience.",acceptText:"Accept All",rejectText:"Reject All",settingsText:"Manage Settings",categories:[],storageKey:"cookie-consent-preferences",onSave:e=>console.log("Preferences saved:",e),animationDuration:400,renderBar:null,renderModal:null};get preferences(){const e=localStorage.getItem(this.#vt.storageKey);return e?JSON.parse(e):{}}get config(){return{...this.#vt,categories:[...this.#vt.categories]}}set config(e){this.validateConfig(e),this.#vt=Object.assign(this.#vt,e)}constructor(e){if(!e||"object"!=typeof e)throw new TypeError("Config must be an object.");this.config=e;const t=this.loadPreferences();this.#Os=t??{},t||this.showConsentBar()}validateConfig(e){if(void 0!==e.message&&"string"!=typeof e.message)throw new TypeError("Config.message must be a string.");if(["acceptText","rejectText","settingsText","storageKey"].forEach(t=>{if(void 0!==e[t]&&"string"!=typeof e[t])throw new TypeError(`Config.${t} must be a string.`)}),void 0!==e.categories){if(!Array.isArray(e.categories))throw new TypeError("Config.categories must be an array of Category objects.");e.categories.forEach((e,t)=>this.validateCategory(e,t))}if(void 0!==e.onSave&&"function"!=typeof e.onSave)throw new TypeError("Config.onSave must be a function.");if(void 0!==e.animationDuration&&("number"!=typeof e.animationDuration||e.animationDuration<0))throw new TypeError("Config.animationDuration must be a positive number.");if(void 0!==e.renderBar&&null!==e.renderBar&&"function"!=typeof e.renderBar)throw new TypeError("Config.renderBar must be a function or null.");if(void 0!==e.renderModal&&null!==e.renderModal&&"function"!=typeof e.renderModal)throw new TypeError("Config.renderModal must be a function or null.")}validateCategory(e,t){if(!e||"object"!=typeof e)throw new TypeError(`Category at index ${t} must be an object.`);if("string"!=typeof e.label)throw new TypeError(`Category.label at index ${t} must be a string.`);if("boolean"!=typeof e.required)throw new TypeError(`Category.required at index ${t} must be a boolean.`);if("boolean"!=typeof e.default)throw new TypeError(`Category.default at index ${t} must be a boolean.`)}loadPreferences(){const e=localStorage.getItem(this.#vt.storageKey);return e?JSON.parse(e):null}removeWithAnimation(e){if(!(e instanceof HTMLElement))throw new TypeError("removeWithAnimation expects an HTMLElement.");e.classList.add("closing"),setTimeout(()=>e.remove(),this.#vt.animationDuration)}savePreferences(e){if(!e||"object"!=typeof e)throw new TypeError("Preferences must be an object.");localStorage.setItem(this.#vt.storageKey,JSON.stringify(e)),this.#vt.onSave(e)}showConsentBar(){const e=document.createElement("div");e.className="cookie-consent-bar",e.innerHTML=this.#vt.renderBar?this.#vt.renderBar(this.#vt):`\n <div><p>${this.#vt.message}</p></div>\n <div><button class="accept">${this.#vt.acceptText}</button></div>\n <div><button class="reject">${this.#vt.rejectText}</button></div>\n <div><button class="settings">${this.#vt.settingsText}</button></div>\n `,document.body.appendChild(e);const t=e.querySelector(".accept");t instanceof HTMLElement&&(t.onclick=()=>{const t={};this.#vt.categories.forEach(e=>t[e.label]=!0),this.savePreferences(t),this.removeWithAnimation(e)});const r=e.querySelector(".reject");r instanceof HTMLElement&&(r.onclick=()=>{const t={};this.#vt.categories.forEach(e=>t[e.label]=e.required),this.savePreferences(t),this.removeWithAnimation(e)});const i=e.querySelector(".settings");i instanceof HTMLElement&&(i.onclick=()=>this.showSettingsModal(e))}showSettingsModal(e){const t=document.createElement("div");t.className="cookie-consent-modal",t.innerHTML=this.#vt.renderModal?this.#vt.renderModal(this.#vt):`\n <div class="modal-content">\n <h2>Cookie Settings</h2>\n <form class="settings-form">\n ${this.#vt.categories.map(e=>`\n <label>\n <input type="checkbox" name="${e.label}" \n ${e.default?"checked":""} \n ${e.required?"disabled":""}>\n ${e.label}\n </label>\n `).join("")}\n </form>\n <button class="save">Save Preferences</button>\n </div>\n `,document.body.appendChild(t);const r=t.querySelector(".save");r instanceof HTMLElement&&(r.onclick=()=>{const r={};t.querySelectorAll("input[type=checkbox]").forEach(e=>{e instanceof HTMLInputElement&&(r[e.name]=e.checked)}),this.savePreferences(r),this.removeWithAnimation(t),e&&this.removeWithAnimation(e)})}isAllowed(e){if("string"!=typeof e)throw new TypeError("isAllowed expects a string as category.");return!!this.#Os&&!!this.#Os[e]}};var oi=r(942),ai=r(913);const li=le("TinyI18");class hi{static#$s=null;static#Hs=null;static#Fs=null;static#zs=null;static set _join(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_join" must be a function');if(null!==hi.#$s)throw new Error('TinyI18: "_join" has already been set');hi.#$s=e}static set _existsSync(e){if("function"!=typeof e&&!1!==e)throw new TypeError('TinyI18: "_existsSync" must be a function or false');if(null!==hi.#Hs)throw new Error('TinyI18: "_existsSync" has already been set');hi.#Hs=e}static set _readFile(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_readFile" must be a function');if(null!==hi.#Fs)throw new Error('TinyI18: "_readFile" has already been set');hi.#Fs=e}static set _writeFile(e){if("function"!=typeof e)throw new TypeError('TinyI18: "_writeFile" must be a function');if(null!==hi.#zs)throw new Error('TinyI18: "_writeFile" has already been set');hi.#zs=e}static async mergeLocaleFiles({files:e,output:t,spaces:r=0}){if(null===hi.#Hs||null===hi.#Fs||null===hi.#zs)throw new Error('TinyI18: "mergeLocaleFiles" requires "_existsSync", "_readFile", and "_writeFile" to be set');if("number"!=typeof r||Number.isNaN(r)||r<0)throw new TypeError('mergeLocaleFiles: "spaces" must be a non-negative number');if(!Array.isArray(e)||0===e.length)throw new TypeError('mergeLocaleFiles: "files" must be a non-empty array of file paths');if("string"!=typeof t||!t)throw new TypeError('mergeLocaleFiles: "output" must be a non-empty string path');const i={};for(const t of e){if("string"!=typeof t||!t)throw new TypeError("mergeLocaleFiles: each file path must be a non-empty string");if(!1!==hi.#Hs&&!hi.#Hs(t))throw new Error(`mergeLocaleFiles: file "${t}" does not exist`);const e=await hi.#Fs(t,"utf-8");let r;try{r=JSON.parse(e)}catch(e){throw new Error(`mergeLocaleFiles: file "${t}" is not valid JSON`)}Object.assign(i,r)}await hi.#zs(t,JSON.stringify(i,null,r),"utf-8")}#u=!1;get destroyed(){return this.#u}#Bs;#Ws;#Us=null;#qs;#Vs=!1;#Ks=null;#Gs=new Map;#Js=new Map;#Ys=new Map;#Xs=new Map;get currentLocale(){return li(this.#u),this.#Us}get defaultLocale(){return li(this.#u),this.#Ws}get mode(){return li(this.#u),this.#Bs}get strict(){return li(this.#u),this.#qs}get acceptNullResults(){return li(this.#u),this.#Vs}get basePath(){return li(this.#u),this.#Ks}get stats(){li(this.#u);const e=[];for(const t of this.#Gs.keys())e.push(this.getStatsForLocale(t));return e}get stringTables(){li(this.#u);const e={};for(const[t,r]of this.#Gs.entries())e[t]=this.#Qs(r);return e}get patternTables(){li(this.#u);const e={};for(const[t,r]of this.#Js.entries())e[t]=r.map(e=>({$pattern:new RegExp(e.$pattern.source,e.$pattern.flags),value:this.#Qs(e.value),elseValue:this.#Qs(e.elseValue)}));return e}get helpers(){li(this.#u);const e={};for(const[t,r]of this.#Ys.entries())e[t]=r;return e}get regexCache(){li(this.#u);const e={};for(const[t,r]of this.#Xs.entries())e[t]=new RegExp(r.source,r.flags);return e}#Qs(e){if(null==e||"string"==typeof e||"function"==typeof e||"number"==typeof e)return e;if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(Array.isArray(e))return e.map(e=>this.#Qs(e));if("object"==typeof e){const t={};for(const[r,i]of Object.entries(e))t[r]=this.#Qs(i);return t}return e}#Zs(e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('#resolveOrder: "forceLocale" must be a string if provided');const t=[];return e&&"string"==typeof e&&this.#Gs.has(e)?t.push(e):this.#Us&&t.push(this.#Us),t.push(this.#Ws),t}#en(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError('#resolveExact: "order" must be an array of strings');if("string"!=typeof t||!t)throw new TypeError('#resolveExact: "key" must be a non-empty string');for(const r of e){const e=this.#Gs.get(r);if(e&&Object.prototype.hasOwnProperty.call(e,t))return e[t]}}#tn(e,t){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError('#resolveByPattern: "order" must be an array of strings');if("string"!=typeof t||!t)throw new TypeError('#resolveByPattern: "key" must be a non-empty string');for(const r of e){const e=this.#Js.get(r)||[];for(const r of e)return r.$pattern.test(t)?r.value:r.elseValue??void 0}}#rn(e,t){if(null==e){if(this.#qs)throw new TypeError('#materialize: "value" cannot be null or undefined');return""}if("string"==typeof e)return this.#in(e,t);if("function"==typeof e)return e(t??{},this.#sn());if(e&&"object"==typeof e&&"string"==typeof e.$fn){const r=this.#Ys.get(e.$fn);if("function"!=typeof r){if(this.#qs)throw new Error(`TinyI18: helper "${e.$fn}" is not registered`);return""}return r({...t??{},args:void 0!==e.args?e.args:void 0},this.#sn())}if(this.#qs)throw new Error("TinyI18: unsupported entry type");return""}#in(e,t){if("string"!=typeof e)throw new TypeError('#interpolate: "template" must be a string');if(void 0!==t&&(null===t||"object"!=typeof t))throw new TypeError('#interpolate: "params" must be an object if provided');return t&&"object"==typeof t?e.replace(/\{([a-zA-Z0-9_.$-]+)\}/g,(e,r)=>{const i=this.#nn(t,r);return null==i?"":String(i)}):e}#nn(e,t){if(!e||"object"!=typeof e)throw new TypeError('#dotGet: "obj" must be an object');if("string"!=typeof t||!t)throw new TypeError('#dotGet: "path" must be a non-empty string');const r=t.split(".");let i=e;for(const e of r){if(null==i)return;i=i[e]}return i}#sn(){return{has:e=>this.#Ys.has(e),call:(e,t,r)=>{const i=this.#Ys.get(e);if("function"!=typeof i)throw new Error(`Helper "${e}" not found`);return i(t,r??{})}}}#on(e,t){if("string"!=typeof e||!e)throw new TypeError('#ingestLocale: "locale" must be a non-empty string');if(!t||"object"!=typeof t)throw new TypeError('#ingestLocale: "raw" must be an object');if("string"!=typeof e||!e)throw new TypeError("#ingestLocale: invalid locale");if(!t||"object"!=typeof t)throw new TypeError('#ingestLocale: "raw" must be an object');const r={...this.#Gs.get(e)??{}},i=[...this.#Js.get(e)??[]],s=(e,t)=>{if(null!=t)if("string"==typeof t||"function"==typeof t||t&&"object"==typeof t&&"string"==typeof t.$fn){if(!e)throw new TypeError("Leaf value requires a key path");r[e]=t}else if(t&&"object"==typeof t){if(t.$pattern instanceof RegExp&&Object.prototype.hasOwnProperty.call(t,"value"))return void i.push({$pattern:t.$pattern,value:t.value,elseValue:t.elseValue});for(const[r,i]of Object.entries(t))s(e?`${e}.${r}`:r,i)}};s("",t),this.#Gs.set(e,r),this.#Js.set(e,i),this.#Gs.has(this.#Ws)||(this.#Gs.set(this.#Ws,{}),this.#Js.set(this.#Ws,[]))}#an(e){if("string"!=typeof e||!e)throw new TypeError('#unloadLocale: "locale" must be a non-empty string');e!==this.#Ws&&(this.#Gs.delete(e),this.#Js.delete(e))}async#ln(e){if(null===hi.#$s||null===hi.#Fs)throw new Error('TinyI18: "file" mode requires "_join" and "_readFile" to be set');if("string"!=typeof e||!e)throw new TypeError('#loadLocaleFromFile: "locale" must be a non-empty string');if("string"!=typeof this.#Ks||!this.#Ks)throw new TypeError('#loadLocaleFromFile: "this.#basePath" must be a non-empty string');const t=hi.#$s(this.#Ks,`${e}.json`);let r;try{const e=await hi.#Fs(t,"utf8");r=JSON.parse(e)}catch(r){if(!(r instanceof Error))return;if(this.#qs)throw new Error(`TinyI18: failed to load or parse ${t}: ${r.message}`);return this.#Gs.set(e,{}),void this.#Js.set(e,[])}const i={...this.#Gs.get(e)??{}},s=[...this.#Js.get(e)??[]],n=(e,t)=>{if(null!=t){if(t&&"object"==typeof t&&"string"==typeof t.$pattern&&Object.prototype.hasOwnProperty.call(t,"value")){const e=this.#hn(t.$pattern);return void s.push({$pattern:e,value:this.#un(t.value),elseValue:this.#un(t.elseValue)})}if("string"==typeof t||t&&"object"==typeof t&&"string"==typeof t.$fn){if(!e)throw new TypeError("Leaf value requires a key path");i[e]=this.#un(t)}else if(t&&"object"==typeof t)for(const[r,i]of Object.entries(t))n(e?`${e}.${r}`:r,i)}};n("",r),this.#Gs.set(e,i),this.#Js.set(e,s)}#hn(e){if("string"!=typeof e||!e)throw new TypeError('#safeRegExp: "src" must be a non-empty string');const t=this.#Xs.get(e);if(t)return t;try{const t=new RegExp(e);return this.#Xs.set(e,t),t}catch{if(this.#qs)throw new Error(`TinyI18: invalid regex "${e}" in file`);return/^$/}}#un(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"string"==typeof e.$fn)return{$fn:String(e.$fn),args:e.args};if(this.#qs)throw new Error("TinyI18: unsupported value in file JSON");return""}constructor(e){if(!e||"object"!=typeof e)throw new TypeError("TinyI18: options must be an object");const{mode:t,defaultLocale:r,basePath:i,localResources:s,strict:n=!0,acceptNullResults:o=!1}=e;if("local"!==t&&"file"!==t)throw new TypeError('TinyI18: "mode" must be "local" or "file"');if("string"!=typeof r||!r)throw new TypeError('TinyI18: "defaultLocale" must be a non-empty string');if("boolean"!=typeof n)throw new TypeError('TinyI18: "strict" must be a boolean');if("boolean"!=typeof o)throw new TypeError('TinyI18: "acceptNullResults" must be a boolean');if("file"===t){if("string"!=typeof i||!i)throw new TypeError('TinyI18: "basePath" is required in file mode');this.#Ks=i}if(this.#Bs=t,this.#Ws=r,this.#qs=n,this.#Vs=o,"local"===t&&s&&"object"==typeof s)for(const[e,t]of Object.entries(s))this.#on(e,t);this.#Gs.has(this.#Ws)||(this.#Gs.set(this.#Ws,{}),this.#Js.set(this.#Ws,[]))}clearRegexCache(){li(this.#u),this.#Xs.clear()}registerHelper(e,t){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('registerHelper: "name" must be non-empty string');if("function"!=typeof t)throw new TypeError('registerHelper: "fn" must be a function');this.#Ys.set(e,t)}unregisterHelper(e){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('unregisterHelper: "name" must be a non-empty string');return this.#Ys.delete(e)}loadLocaleLocal(e,t){if(li(this.#u),"local"!==this.#Bs)throw new TypeError('loadLocaleLocal is only available in "local" mode');this.#on(e,t)}async setLocale(e){if(li(this.#u),null!==e&&("string"!=typeof e||!e))throw new TypeError('setLocale: "locale" must be string or null');const t=this.#Us;null!==e&&("file"===this.#Bs?await this.#ln(e):this.#Gs.has(e)||(this.#Gs.set(e,{}),this.#Js.set(e,[]))),"file"===this.#Bs&&t&&t!==this.#Ws&&t!==e&&this.#an(t),this.#Us=e}t(e,t=void 0,r=void 0){return this.get(e,t,r)}get(e,t=void 0,r=void 0){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('get: "key" must be a non-empty string');const{locale:i}=r||{},s=this.#Zs(i);let n=this.#en(s,e);if(void 0===n){if(this.#qs)throw new Error(`TinyI18: missing translation for key "${e}"`);return this.#Vs?null:e}return this.#rn(n,t)}p(e,t){return this.resolveByPattern(e,t)}resolveByPattern(e,t){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('get: "key" must be a non-empty string');const{locale:r}=t||{},i=this.#Zs(r);let s=this.#tn(i,e);if(void 0===s){if(this.#qs)throw new Error(`TinyI18: missing translation for key "${e}"`);return this.#Vs?null:e}return s}resetToDefaultOnly(){if(li(this.#u),"file"===this.#Bs)for(const e of Array.from(this.#Gs.keys()))e!==this.#Ws&&this.#an(e);this.#Us=null}getStatsForLocale(e){if(li(this.#u),"string"!=typeof e||!e)throw new TypeError('getStatsForLocale: "locale" must be a non-empty string');if(!this.#Gs.has(e))throw new Error(`getStatsForLocale: locale "${e}" is not registered`);return{locale:e,strings:Object.keys(this.#Gs.get(e)??{}).length,patterns:this.#Js.get(e)?.length??0,isDefault:e===this.#Ws,isCurrent:e===this.#Us}}destroy(){this.#u||(this.#Gs.clear(),this.#Js.clear(),this.#Ys.clear(),this.#Xs.clear(),this.#Us=null,this.#Ks=null,this.#u=!0)}}const ui=hi;class ci extends ui{constructor(e){super(e)}}ci._join=(...e)=>(0,t().join)(...e),ci._existsSync=(...e)=>(0,ai.existsSync)(...e),ci._readFile=(...e)=>(0,oi.readFile)(...e),ci._writeFile=(...e)=>(0,oi.writeFile)(...e);const di=ci;class mi{#cn=new Map;#dn;#mn;#pn;get factors(){const e={};for(let[t,r]of this.#cn.entries())e[t]={...r};return e}get currentPercent(){return this.#mn/this.#dn*100}set maxValue(e){if("number"!=typeof e||Number.isNaN(e)||e<=0)throw new TypeError("maxValue must be a positive number.");this.#dn=e,this.#mn=Math.min(this.#mn,e)}get maxValue(){return this.#dn}get currentValue(){return this.#mn}set infiniteValue(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("infiniteValue must be a number.");this.#pn=e,this.#mn=Math.max(0,e),this.#mn=Math.min(this.#mn,this.#dn)}get infiniteValue(){return this.#pn}constructor(e=100,t=1,r=1){if("number"!=typeof e||Number.isNaN(e)||e<=0)throw new TypeError("maxValue must be a positive number.");this.#dn=e,this.setFactor("main",t,r),this.#mn=e,this.#pn=e}getFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");const t=this.#cn.get(e);if(!t)throw new Error(`Factor with key "${e}" not found.`);return{...t}}hasFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");return this.#cn.has(e)}setFactor(e,t,r=1){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");if("number"!=typeof t||Number.isNaN(t))throw new TypeError("Amount must be a valid number.");if("number"!=typeof r||Number.isNaN(r))throw new TypeError("Multiplier must be a valid number.");this.#cn.set(e,{amount:t,multiplier:r})}removeFactor(e){if("string"!=typeof e||!e)throw new TypeError("Key must be a non-empty string.");return this.#cn.delete(e)}#fn(e){const t=this.#pn;return this.#pn-=e,this.#mn=Math.max(0,this.#mn-e),{prevValue:t,removedTotal:e,removedPercent:e/this.#dn*100,currentPercent:this.currentPercent,remainingValue:this.#mn,infiniteRemaining:this.#pn}}tick(){let e=0;for(let[t,r]of this.#cn.entries())e+=r.amount*r.multiplier;return this.#fn(e)}tickWithTempFactor(e){if("object"!=typeof e||null===e)throw new TypeError("You must provide a valid factor object.");if("number"!=typeof e.amount||Number.isNaN(e.amount))throw new TypeError('Temp factor "amount" must be a valid number.');if("multiplier"in e&&("number"!=typeof e.multiplier||Number.isNaN(e.multiplier)))throw new TypeError('Temp factor "multiplier" must be a valid number if provided.');let t=0;for(let[e,r]of this.#cn.entries())t+=r.amount*r.multiplier;return e&&(t+=e.amount*(e.multiplier??1)),this.#fn(t)}tickSingleFactor(e){if("object"!=typeof e||null===e)throw new TypeError("You must provide a valid factor object.");if("number"!=typeof e.amount||Number.isNaN(e.amount))throw new TypeError('Temp factor "amount" must be a valid number.');if("multiplier"in e&&("number"!=typeof e.multiplier||Number.isNaN(e.multiplier)))throw new TypeError('Temp factor "multiplier" must be a valid number if provided.');if(!e)throw new Error("You must provide a factor to apply.");const t=e.amount*(e.multiplier??1);return this.#fn(t)}toJSON(){return{maxValue:this.#dn,currentValue:this.#mn,infiniteValue:this.#pn,factors:this.factors}}static fromJSON(e){const t=new mi(e.maxValue,0,0);t.infiniteValue=e.infiniteValue,t.#cn.clear();for(const[r,i]of Object.entries(e.factors))t.setFactor(r,i.amount,i.multiplier);return t}clone(){return mi.fromJSON(this.toJSON())}clearFactors(){this.#cn.clear()}}const pi=mi;class fi{static _safeEvaluate(e){if(!/^[\d+\-*/%.()\s^]+$/.test(e))throw new Error(`Invalid characters in expression: "${e}"`);const t=e.replace(/\^/g,"**");try{return Function(`"use strict"; return (${t})`)()}catch(t){if(!(t instanceof Error))throw new Error("Unknown Error");throw new Error(`Invalid expression "${e}": ${t.message}`)}}static replaceValues(e,t){let r=0;return e.replace(/(\d*)d(\d+)/g,(e,i)=>{const s=i?Number(i):1;let n=0;for(let e=0;e<s;e++){const e=t[r++];n+=void 0!==e?e:0}return String(n)})}static tokenizeValues(e,t){const r=fi.replaceValues(e,t),i=[],s=/\d+|[()+\-*/]/g;let n;for(;null!==(n=s.exec(r));)/^\d+$/.test(n[0])?i.push(Number(n[0])):i.push(n[0]);return{tokens:i,text:r}}static parseString(e){if("string"!=typeof e)throw new TypeError("Input must be a string.");const t=e.split(",").map(e=>e.trim()).filter(Boolean),r=[],i=[];if(t.forEach((e,t)=>{const s=/\b(?:(\d+)?d(\d+))\b/g;let n;const o=[],a=e.replace(/\(([^()]+?\|[^()]+?)\)/g,(e,t)=>{const r="string"==typeof t?t.split("|").map(e=>e.trim()).filter(Boolean):[];if(0===r.length)throw new Error(`Invalid random-choice group: "${e}"`);return r[Math.floor(Math.random()*r.length)]});for(;null!==(n=s.exec(a));){const e=parseInt(n[1]||"1",10),r=parseInt(n[2],10);if(isNaN(r))throw new Error(`Invalid dice sides in expression "${n[0]}" at position ${t+1}.`);o.push({count:e,sides:r})}if(0===o.length&&Number.isNaN(parseFloat(a)))throw new Error(`Invalid dice expression at position ${t+1}: "${e}"`);r.push(...o),i.push({index:t,original:e,expression:a})}),0===r.length)throw new Error("Invalid dice amount.");return{sides:r,modifiers:i}}static applyModifiers(e,t){if(!Array.isArray(e)||!e.every(e=>"number"==typeof e&&!Number.isNaN(e)||v(e)&&"number"==typeof e.value&&!Number.isNaN(e.value)&&"number"==typeof e.sides&&!Number.isNaN(e.sides)))throw new TypeError("Bases must be a valid numbers.");if(!Array.isArray(t))throw new TypeError("Modifiers must be an array of modifier objects.");let r=0;const i=[],s=[...e];for(const e in t){const n=t[e];if("string"!=typeof n.expression)throw new Error("Each modifier must include an expression string.");const o=n.original,a=n.expression,l=[],h=[],u=[],c=e=>e.match(/\(\s*[^()]+\|\s*[^()]+\s*\)|\b\d*d\d+\b|[-+]?\d+(?:\.\d+)?|[+\-*/%^()]/g)||[],d=c(a),m=c(o),p=[...d],f=[],y=a.replace(/\b\d*d\d+\b/g,e=>{const t=e.split("d"),r=()=>{for(const t in d)if(d[t]===e&&f.indexOf(t)<0){f.push(t),u.push(Number(t));break}},i=e=>{if(e.value>e.sides)throw new Error(`Invalid dice roll: value (${e.value}) must be between 1 and ${e.sides}.`)};if(0===t[0].trim().length){const t=s.shift(),n="number"==typeof t?t:v(t)?t.value:0;v(t)&&i(t),l.push([n]);for(const t in p)if(p[t]===e){p[t]=String(n),h.push(Number(t));break}return r(),n}const n=[],o=Number(t[0]),a=["("];let c="(";for(let e=0;e<o;e++){const t=s.shift(),r="number"==typeof t?t:v(t)?t.value:0;v(t)&&i(t),a.push(String(r));const l=e<o-1?" + ":")";a.push(l),c+=`${r}${l}`,n.push(r)}for(const t in p){const r=Number(t);if(p[r]===e){p.splice(r,1,...a);let e=1;for(let t=0;t<o;t++)h.push(r+t+e),e++;break}}return l.push(n),r(),c});let g;try{g=fi._safeEvaluate(y)}catch(e){if(!(e instanceof Error))throw new Error("Unknown Error");throw new Error(`Error evaluating expression "${y}" (from "${a}"): ${e.message}`)}i.push({rawTokensP:d,rawTokens:m,tokens:p,rawDiceTokenSlots:u,diceTokenSlots:h,dicesResult:l,total:g}),r+=g}return{final:r,steps:i}}static rollArrayIndex(e){const t=Array.isArray(e),r=e instanceof Set;if(!t&&!r)throw new TypeError("rollArrayIndex expects an array or Set.");return Math.floor(Math.random()*(t?e.length:e.size))}#dn;#yn;get maxValue(){return this.#dn}set maxValue(e){if(!Number.isInteger(e)||e<0)throw new TypeError("maxValue must be an integer greater than -1.");this.#dn=e}get allowZero(){return this.#yn}set allowZero(e){if("boolean"!=typeof e)throw new TypeError("allowZero must be a boolean.");this.#yn=e}constructor({maxValue:e,allowZero:t=!0}){if("boolean"!=typeof t)throw new TypeError("allowZero must be an boolean.");if(!Number.isInteger(e)||e<0)throw new TypeError("maxValue must be an integer greater than -1.");this.#dn=e,this.#yn=t}roll(){const e=this.#yn?0:1;return Math.floor(Math.random()*(this.#dn-e+1))+e}}const yi=fi,gi=class{#S=null;get overlay(){return this.#S}#gn=null;get messageElement(){return this.#gn}#P;get container(){return this.#P}#wn={fadeIn:null,fadeOut:null,zIndex:9999};get options(){return{...this.#wn}}set options(e){if("object"!=typeof e||null===e)throw new TypeError("options must be an object");if(void 0!==e.fadeIn&&null!==e.fadeIn&&("number"!=typeof e.fadeIn||e.fadeIn<0))throw new TypeError("fadeIn must be a non-negative number or null");if(void 0!==e.fadeOut&&null!==e.fadeOut&&("number"!=typeof e.fadeOut||e.fadeOut<0))throw new TypeError("fadeOut must be a non-negative number or null");if(void 0!==e.zIndex&&("number"!=typeof e.zIndex||!Number.isInteger(e.zIndex)))throw new TypeError("zIndex must be an integer number");this.#wn={fadeIn:e.fadeIn??null,fadeOut:e.fadeOut??null,zIndex:e.zIndex??9999}}#bn="none";get status(){return this.#bn}#vn="";get defaultMessage(){return this.#vn}set defaultMessage(e){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("defaultMessage must be a string or an HTMLElement");this.#vn=e}#En=null;get message(){return this.#En}#Tn=!1;get allowHtmlText(){return this.#Tn}set allowHtmlText(e){if("boolean"!=typeof e)throw new TypeError("allowHtmlText must be a boolean");this.#Tn=e}#Sn=null;get fadeInTimeout(){return null!==this.#Sn}#xn=null;get fadeOutTimeout(){return null!==this.#xn}get visible(){return!!this.#S}#An=null;get onChange(){return this.#An}set onChange(e){if(null!==e&&"function"!=typeof e)throw new TypeError("onChange must be a function or null");this.#An=e}_emitChange(){"function"==typeof this.#An&&this.#An(this.#bn)}constructor(e=document.body){if(!(e instanceof HTMLElement))throw new TypeError("container must be an HTMLElement");this.#P=e}_updateMessage(e=this.#vn){if(!this.#gn)throw new Error("messageElement is not initialized");if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");if(this.#En=e,"string"==typeof e)this.#Tn?this.#gn.innerHTML=e:this.#gn.textContent=e;else{if(!this.#Tn)throw new Error("HTMLElement messages require allowHtmlText = true");this.#gn.textContent="",this.#gn.appendChild(e)}}_removeOldClasses(){this.#S?.classList.remove("active"),this.#S?.classList.remove("fadeIn"),this.#S?.classList.remove("fadeOut")}start(e=this.#vn){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");if(!this.#S){this.#S=document.createElement("div"),this.#S.classList.add("loading-overlay"),this.#S.style.zIndex=String(this.#wn.zIndex);const t=document.createElement("div");t.classList.add("loading-container");const r=document.createElement("div");r.classList.add("loading-content");const i=document.createElement("div");i.classList.add("loading-spinner"),this.#gn=document.createElement("div"),this.#gn.classList.add("loading-message"),r.appendChild(i),r.appendChild(this.#gn),t.appendChild(r),this.#S.appendChild(t),this.#P.appendChild(this.#S),this._removeOldClasses(),this.#bn="fadeIn",this.#S.classList.add("fadeIn"),this._emitChange();const s=()=>{this._removeOldClasses(),this.#Sn=null,this.#bn="active",this.#S?.classList.add("active"),this._emitChange()};return"number"==typeof this.#wn.fadeIn?(this.#Sn&&clearTimeout(this.#Sn),this.#Sn=setTimeout(s,this.#wn.fadeIn)):s(),this._updateMessage(e),!0}return this.#gn&&this._updateMessage(e),!1}update(e=this.#vn){if("string"!=typeof e&&!(e instanceof HTMLElement))throw new TypeError("message must be a string or an HTMLElement");return!!this.#gn&&(this._updateMessage(e),!0)}stop(){if(this.#S){this._removeOldClasses(),this.#bn="fadeOut",this.#S.classList.add("fadeOut"),this._emitChange();const e=()=>{this._removeOldClasses(),this.#xn=null,this.#bn="none",this.#S?.remove(),this.#S=null,this.#gn=null,this.#En=null,this._emitChange()};return"number"==typeof this.#wn.fadeOut?(this.#xn&&clearTimeout(this.#xn),this.#xn=setTimeout(e,this.#wn.fadeOut)):e(),!0}return!1}};class wi{static#Cn=/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;static#In=/^#([A-Fa-f0-9]{8})$/;static#kn="(0|1|0?\\.\\d+)";static#Dn="(0|[1-9]\\d?|1\\d{2}|2[0-4]\\d|25[0-5])";static#Mn="(0|[1-9]\\d?|[1-2]\\d{2}|3[0-5]\\d|360)";static#Ln="(0|[1-9]?\\d|100)";static#Nn=new RegExp(`^rgb\\(\\s*${wi.#Dn}\\s*,\\s*${wi.#Dn}\\s*,\\s*${wi.#Dn}\\s*\\)$`);static#_n=new RegExp(`^rgba\\(\\s*${wi.#Dn}\\s*,\\s*${wi.#Dn}\\s*,\\s*${wi.#Dn}\\s*,\\s*${wi.#kn}\\s*\\)$`);static#Rn=new RegExp(`^hsl\\(\\s*${wi.#Mn}\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#Ln}%\\s*\\)$`);static#jn=new RegExp(`^hsla\\(\\s*${wi.#Mn}\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#Ln}%\\s*,\\s*${wi.#kn}\\s*\\)$`);static#Pn=new RegExp(`^hwb\\(\\s*${wi.#Mn}(deg|grad|rad|turn)?\\s*${wi.#Ln}%\\s*${wi.#Ln}%\\s*\\)$`);static#On="(-?\\d+)";static#$n=new RegExp(`^lab\\(\\s*${wi.#Ln}%?\\s*${wi.#On}%?\\s*${wi.#On}%?\\s*\\)$`);static#Hn=new RegExp(`^lch\\(\\s*${wi.#Ln}%?\\s*${wi.#Ln}%?\\s*${wi.#Mn}(deg|grad|rad|turn)?\\s*\\)$`);static#Fn=new Set(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"]);static#zn=new Set(["transparent","currentColor"]);static getNames(){return Array.from(wi.#Fn)}static addName(e){const t=wi.#Fn.size;return wi.#Fn.add(e.toLowerCase()),wi.#Fn.size>t}static removeName(e){return wi.#Fn.delete(e.toLowerCase())}static hasName(e){return wi.#Fn.has(e.toLowerCase())}static getSpecialNames(){return Array.from(wi.#zn)}static addSpecialName(e){const t=wi.#zn.size;return wi.#zn.add(e),wi.#zn.size>t}static removeSpecialName(e){return wi.#zn.delete(e)}static hasSpecialName(e){return wi.#zn.has(e)}#Bn;get code(){return this.#Bn}#Wn;get type(){return this.#Wn}constructor(e){this.#Bn=e,this.#Wn=wi.isColor(this.#Bn)}static isHex(e){if("string"!=typeof e)throw new TypeError("isHex: input must be a string.");return wi.#Cn.test(e.trim())}isHex(){return wi.isHex(this.#Bn)}static isHexa(e){if("string"!=typeof e)throw new TypeError("isHexa: input must be a string.");return wi.#In.test(e.trim())}isHexa(){return wi.isHexa(this.#Bn)}static isRgb(e){if("string"!=typeof e)throw new TypeError("isRgb: input must be a string.");return wi.#Nn.test(e.trim())}isRgb(){return wi.isRgb(this.#Bn)}static isRgba(e){if("string"!=typeof e)throw new TypeError("isRgba: input must be a string.");return wi.#_n.test(e.trim())}isRgba(){return wi.isRgba(this.#Bn)}static isHsl(e){if("string"!=typeof e)throw new TypeError("isHsl: input must be a string.");return wi.#Rn.test(e.trim())}isHsl(){return wi.isHsl(this.#Bn)}static isHsla(e){if("string"!=typeof e)throw new TypeError("isHsla: input must be a string.");return wi.#jn.test(e.trim())}isHsla(){return wi.isHsla(this.#Bn)}static isHwb(e){if("string"!=typeof e)throw new TypeError("isHwb: input must be a string.");return wi.#Pn.test(e.trim())}isHwb(){return wi.isHwb(this.#Bn)}static isLab(e){if("string"!=typeof e)throw new TypeError("isLab: input must be a string.");return wi.#$n.test(e.trim())}isLab(){return wi.isLab(this.#Bn)}static isLch(e){if("string"!=typeof e)throw new TypeError("isLch: input must be a string.");return wi.#Hn.test(e.trim())}isLch(){return wi.isLch(this.#Bn)}static isName(e){if("string"!=typeof e)throw new TypeError("isName: input must be a string.");return wi.#Fn.has(e.trim().toLowerCase())}isName(){return wi.isName(this.#Bn)}static isSpecialName(e){if("string"!=typeof e)throw new TypeError("isSpecialName: input must be a string.");return wi.#zn.has(e.trim())}isSpecialName(){return wi.isSpecialName(this.#Bn)}static isColor(e){if("string"!=typeof e)throw new TypeError("isColor: input must be a string.");return wi.isHex(e)?"hex":wi.isHexa(e)?"hexa":wi.isRgb(e)?"rgb":wi.isRgba(e)?"rgba":wi.isHsl(e)?"hsl":wi.isHsla(e)?"hsla":wi.isHwb(e)?"hwb":wi.isLab(e)?"lab":wi.isLch(e)?"lch":wi.isName(e)?"name":wi.isSpecialName(e)?"specialName":null}parse(){switch(this.#Wn){case"hex":return wi.parseHex(this.code);case"hexa":return wi.parseHexa(this.code);case"rgb":return wi.parseRgb(this.code);case"rgba":return wi.parseRgba(this.code);case"hsl":return wi.parseHsl(this.code);case"hsla":return wi.parseHsla(this.code);case"hwb":return wi.parseHwb(this.code);case"lab":return wi.parseLab(this.code);case"lch":return wi.parseLch(this.code);case"name":case"specialName":return this.#Bn.trim().toLowerCase();default:return null}}static parseHex(e){if("string"!=typeof e)throw new TypeError("parseHex: input must be a string.");const t=new RegExp(wi.#Cn,"gm").exec(e.trim());return t?t[1]:null}parseHex(){return wi.parseHex(this.#Bn)}static parseHexa(e){if("string"!=typeof e)throw new TypeError("parseHexa: input must be a string.");const t=new RegExp(wi.#In,"gm").exec(e.trim());return t?t[1]:null}parseHexa(){return wi.parseHexa(this.#Bn)}static parseRgb(e){if("string"!=typeof e)throw new TypeError("parseRgb: input must be a string.");const t=new RegExp(wi.#Nn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseRgb(){return wi.parseRgb(this.#Bn)}static parseRgba(e){if("string"!=typeof e)throw new TypeError("parseRgba: input must be a string.");const t=new RegExp(wi.#_n,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])]:null}parseRgba(){return wi.parseRgba(this.#Bn)}static parseHsl(e){if("string"!=typeof e)throw new TypeError("parseHsl: input must be a string.");const t=new RegExp(wi.#Rn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseHsl(){return wi.parseHsl(this.#Bn)}static parseHsla(e){if("string"!=typeof e)throw new TypeError("parseHsla: input must be a string.");const t=new RegExp(wi.#jn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])]:null}parseHsla(){return wi.parseHsla(this.#Bn)}static parseHwb(e){if("string"!=typeof e)throw new TypeError("parseHwb: input must be a string.");const t=new RegExp(wi.#Pn,"gm").exec(e.trim());return t?[parseFloat(t[1]),t[2]??null,parseFloat(t[3]),parseFloat(t[4])]:null}parseHwb(){return wi.parseHwb(this.#Bn)}static parseLab(e){if("string"!=typeof e)throw new TypeError("parseLab: input must be a string.");const t=new RegExp(wi.#$n,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]:null}parseLab(){return wi.parseLab(this.#Bn)}static parseLch(e){if("string"!=typeof e)throw new TypeError("parseLch: input must be a string.");const t=new RegExp(wi.#Hn,"gm").exec(e.trim());return t?[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),t[4]??null]:null}parseLch(){return wi.parseLch(this.#Bn)}}const bi=wi,vi=le("TinyAnalogClock"),Ei=class{#Un;#qn;#Vn;#vt;#oi=null;#u=!1;get destroyed(){return this.#u}_getDate(){const e=new Date,t=e.getSeconds(),r=e.getMinutes(),i=e.getHours();return{now:e,s:t,m:r,h:i}}constructor(e={}){this.#vt={bgColor:"#f0f0f0",borderColor:"#333",borderWidth:8,markColor:"#333",hourHandColor:"#000",minuteHandColor:"#444",secondHandColor:"#d81c1c",textColor:"#000",skinUrl:null,showNumbers:!0,showSeconds:!0,size:800,sizeAdjust:.04,padding:45,angleDistance:.95,pwH:.008,phH:.08,pwM:.005,phM:.03,...e},this.#Un=document.createElement("div"),this.#Un.className="analog-clock-container",this.#Un.style.position="relative",this.#Un.style.borderRadius="50%",this.#Un.style.overflow="hidden",this.#Un.style.boxSizing="border-box",this.#Vn=document.createElement("div"),this.#Vn.style.position="absolute",this.#Vn.style.inset="0",this.#Vn.style.backgroundSize="cover",this.#Vn.style.backgroundPosition="center",this.#Vn.style.zIndex="0",this.#qn=document.createElement("div"),this.#qn.style.position="absolute",this.#qn.style.inset="0",this.#qn.style.zIndex="1",this.#qn.style.pointerEvents="none";const t=document.createElement("div");t.style.position="absolute",t.style.inset="0",t.style.zIndex="2",t.style.pointerEvents="none",t.innerHTML='\n <div class="hand hour-hand"></div>\n <div class="hand minute-hand"></div>\n <div class="hand second-hand"></div>\n <div class="center-pin"></div>\n ',this.#Un.appendChild(this.#Vn),this.#Un.appendChild(this.#qn),this.#Un.appendChild(t);const r=document.createElement("style");r.textContent="\n .analog-clock-container .hand {\n position: absolute;\n bottom: 50%;\n left: 50%;\n transform-origin: bottom center;\n border-radius: 4px;\n transform: translateX(-50%) rotate(0deg);\n z-index: 5;\n }\n .analog-clock-container .center-pin {\n position: absolute;\n top: 50%; left: 50%;\n width: 12px; height: 12px;\n background: #333;\n border-radius: 50%;\n transform: translate(-50%, -50%);\n z-index: 10;\n }\n .analog-clock-container .clock-mark {\n position: absolute;\n top: 50%; left: 50%;\n background: currentColor;\n transform-origin: center center;\n }\n .analog-clock-container .clock-number {\n position: absolute;\n top: 50%; left: 50%;\n transform: translate(-50%, -50%);\n font-family: sans-serif;\n font-weight: bold;\n text-align: center;\n line-height: 1;\n }\n ",this.#Un.appendChild(r),this._applyConfig(),this._renderFace(),this._startTicker()}_applyConfig(){const e=this.#Un.style,t=this.#vt;e.width=`${t.size}px`,e.height=`${t.size}px`,e.border=`${t.borderWidth}px solid ${t.borderColor}`,e.backgroundColor=t.bgColor,t.skinUrl?(this.#Vn.style.backgroundImage=`url(${t.skinUrl})`,this.#Vn.style.display="block"):this.#Vn.style.display="none";const r=e=>{const t=this.#Un.querySelector(e);if(!(t instanceof HTMLDivElement))throw new Error(`TinyAnalogClock: Element ${e} not found.`);return t},i=r(".hour-hand");i.style.backgroundColor=t.hourHandColor,i.style.width=.025*t.size+"px",i.style.height=.25*t.size+"px",i.style.marginLeft=.025*t.size/-2+"px",i.style.bottom="50%",i.style.left="50%",i.style.transformOrigin="bottom center";const s=r(".minute-hand");s.style.backgroundColor=t.minuteHandColor,s.style.width=.015*t.size+"px",s.style.height=.35*t.size+"px",s.style.marginLeft=.015*t.size/-2+"px";const n=r(".second-hand");t.showSeconds?(n.style.display="block",n.style.backgroundColor=t.secondHandColor,n.style.width=.005*t.size+"px",n.style.height=.4*t.size+"px",n.style.marginLeft=.005*t.size/-2+"px"):n.style.display="none",r(".center-pin").style.background=t.borderColor}_renderFace(){this.#qn.innerHTML="";const e=this.#vt.size/2-this.#vt.borderWidth;for(let t=0;t<60;t++){const r=t%5==0,i=document.createElement("div");i.className="clock-mark";const s=r?this.#vt.size*this.#vt.pwH:this.#vt.size*this.#vt.pwM,n=r?this.#vt.size*this.#vt.phH:this.#vt.size*this.#vt.phM,o=this.#vt.markColor;i.style.width=`${s}px`,i.style.height=`${n}px`,i.style.color=o;const a=e-this.#vt.padding-n/2;i.style.transform=`translate(-50%, -50%) rotate(${6*t}deg) translate(0, -${a}px)`,this.#qn.appendChild(i)}if(this.#vt.showNumbers)for(let t=1;t<=12;t++){const r=30*t*(Math.PI/180),i=e*this.#vt.angleDistance,s=e+Math.sin(r)*i,n=e-Math.cos(r)*i,o=document.createElement("div");o.className="clock-number",o.innerText=t.toString(),o.style.left=`${s}px`,o.style.top=`${n}px`,o.style.color=this.#vt.textColor,o.style.fontSize=this.#vt.size*this.#vt.sizeAdjust+"px",this.#qn.appendChild(o)}}_startTicker(){if(this.#oi)return;const e=()=>{const{s:t,m:r,h:i}=this._getDate(),s=6*t,n=6*r+.1*t,o=i%12*30+.5*r,a=e=>{const t=this.#Un.querySelector(e);if(!(t instanceof HTMLDivElement))throw new Error(`${e} not found.`);return t};this.#Un.querySelector(".second-hand")&&(a(".second-hand").style.transform=`rotate(${s}deg)`),a(".minute-hand").style.transform=`rotate(${n}deg)`,a(".hour-hand").style.transform=`rotate(${o}deg)`,this.#oi=requestAnimationFrame(e)};e()}get element(){return vi(this.#u),this.#Un}set size(e){if(vi(this.#u),"number"!=typeof e||e<=0||isNaN(e))throw new Error(`TinyAnalogClock: 'size' must be a positive number. Received: ${e}`);this.#vt.size=e,this._applyConfig(),this._renderFace()}get size(){return vi(this.#u),this.#vt.size}set skinUrl(e){if(vi(this.#u),null!==e&&"string"!=typeof e)throw new Error("TinyAnalogClock: 'skin' must be a URL string or null. Received type: "+typeof e);this.#vt.skinUrl=e,this._applyConfig()}get skinUrl(){return vi(this.#u),this.#vt.skinUrl}set borderColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'borderColor' must be a non-empty string. Received: ${e}`);this.#vt.borderColor=e,this._applyConfig(),this._renderFace()}get borderColor(){return vi(this.#u),this.#vt.borderColor}set markColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'markColor' must be a non-empty string. Received: ${e}`);this.#vt.markColor=e,this._applyConfig(),this._renderFace()}get markColor(){return vi(this.#u),this.#vt.markColor}set textColor(e){if(vi(this.#u),"string"!=typeof e||""===e.trim())throw new Error(`TinyAnalogClock: 'textColor' must be a non-empty string. Received: ${e}`);this.#vt.textColor=e,this._applyConfig(),this._renderFace()}get textColor(){return vi(this.#u),this.#vt.textColor}set showNumbers(e){if(vi(this.#u),"boolean"!=typeof e)throw new Error("TinyAnalogClock: 'showNumbers' must be a boolean. Received type: "+typeof e);this.#vt.showNumbers=e,this._renderFace()}get showNumbers(){return vi(this.#u),this.#vt.showNumbers}set bgColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'bgColor' must be a non-empty string.");this.#vt.bgColor=e,this._applyConfig()}get bgColor(){return vi(this.#u),this.#vt.bgColor}set borderWidth(e){if(vi(this.#u),"number"!=typeof e||e<0)throw new Error("TinyAnalogClock: 'borderWidth' must be a non-negative number.");this.#vt.borderWidth=e,this._applyConfig(),this._renderFace()}get borderWidth(){return vi(this.#u),this.#vt.borderWidth}set hourHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'hourHandColor' must be a non-empty string.");this.#vt.hourHandColor=e,this._applyConfig()}get hourHandColor(){return vi(this.#u),this.#vt.hourHandColor}set minuteHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'minuteHandColor' must be a non-empty string.");this.#vt.minuteHandColor=e,this._applyConfig()}get minuteHandColor(){return vi(this.#u),this.#vt.minuteHandColor}set secondHandColor(e){if(vi(this.#u),"string"!=typeof e||!e)throw new Error("TinyAnalogClock: 'secondHandColor' must be a non-empty string.");this.#vt.secondHandColor=e,this._applyConfig()}get secondHandColor(){return vi(this.#u),this.#vt.secondHandColor}set showSeconds(e){if(vi(this.#u),"boolean"!=typeof e)throw new Error("TinyAnalogClock: 'showSeconds' must be a boolean.");this.#vt.showSeconds=e,this._applyConfig()}get showSeconds(){return vi(this.#u),this.#vt.showSeconds}set sizeAdjust(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'sizeAdjust' must be a positive number.");this.#vt.sizeAdjust=e,this._renderFace()}get sizeAdjust(){return vi(this.#u),this.#vt.sizeAdjust}set padding(e){if(vi(this.#u),"number"!=typeof e||e<0)throw new Error("TinyAnalogClock: 'padding' must be a non-negative number.");this.#vt.padding=e,this._renderFace()}get padding(){return vi(this.#u),this.#vt.padding}set angleDistance(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'angleDistance' must be a positive number.");this.#vt.angleDistance=e,this._renderFace()}get angleDistance(){return vi(this.#u),this.#vt.angleDistance}set pwH(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'pwH' must be a positive number.");this.#vt.pwH=e,this._renderFace()}get pwH(){return vi(this.#u),this.#vt.pwH}set phH(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'phH' must be a positive number.");this.#vt.phH=e,this._renderFace()}get phH(){return vi(this.#u),this.#vt.phH}set pwM(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'pwM' must be a positive number.");this.#vt.pwM=e,this._renderFace()}get pwM(){return vi(this.#u),this.#vt.pwM}set phM(e){if(vi(this.#u),"number"!=typeof e||e<=0)throw new Error("TinyAnalogClock: 'phM' must be a positive number.");this.#vt.phM=e,this._renderFace()}get phM(){return vi(this.#u),this.#vt.phM}destroy(){this.#u||(this.#oi&&(cancelAnimationFrame(this.#oi),this.#oi=null),this.#Un.remove(),this.#u=!0)}},Ti=le("TinyTextDiffer"),Si=class{#Kn=[];#u=!1;get destroyed(){return this.#u}get history(){return Ti(this.#u),[...this.#Kn]}set history(e){if(Ti(this.#u),!Array.isArray(e))throw new TypeError("History data must be provided as an array.");if(!e.every(e=>"string"==typeof e))throw new TypeError("All items in the history array must be strings.");this.#Kn=[...e]}get size(){return Ti(this.#u),this.#Kn.length}constructor(e=[]){this.history=e}#Gn(e){if("number"!=typeof e)throw new TypeError("The provided index must be a valid number.")}#Jn(e){if("string"!=typeof e)throw new TypeError("The provided text must be a valid string.")}get(e){if(Ti(this.#u),this.#Gn(e),void 0===this.#Kn[e])throw new Error(`No text version found at index ${e}.`);return this.#Kn[e]}has(e){return Ti(this.#u),this.#Gn(e),void 0!==this.#Kn[e]}add(e){Ti(this.#u),this.#Jn(e),this.#Kn.push(e)}remove(){return Ti(this.#u),this.#Kn.pop()}addAt(e,t){Ti(this.#u),this.#Gn(e),this.#Jn(t),this.#Kn.splice(e,0,t)}removeAt(e){Ti(this.#u),this.#Gn(e);const t=this.#Kn.length;return this.#Kn.splice(e,1),t!==this.#Kn.length}clear(){Ti(this.#u),this.#Kn=[]}compare(...e){Ti(this.#u);const t=e.length;if(0===t||t%2!=0)throw new Error("The compare method requires an even number of indices to form comparison pairs.");const r=[];for(let i=0;i<t;i+=2){const s=i+1;if(s>t-1)continue;this.#Gn(e[i]),this.#Gn(e[s]);const n=this.#Kn[e[i]],o=this.#Kn[e[s]];r.push(this._computeDiff(n,o))}return r}_computeDiff(e,t){const r=e.length,i=t.length,s=Array(r+1).fill(null).map(()=>Array(i+1).fill(0));let n=1,o=1;for(n=1;n<=r;n++)for(o=1;o<=i;o++)e[n-1]===t[o-1]?s[n][o]=s[n-1][o-1]+1:s[n][o]=Math.max(s[n-1][o],s[n][o-1]);n=r,o=i;const a=[];for(;n>0||o>0;)n>0&&o>0&&e[n-1]===t[o-1]?(a.unshift({value:e[n-1],type:"normal"}),n--,o--):o>0&&(0===n||s[n][o-1]>=s[n-1][o])?(a.unshift({value:t[o-1],type:"added"}),o--):n>0&&(0===o||s[n][o-1]<s[n-1][o])&&(a.unshift({value:e[n-1],type:"deleted"}),n--);return a.reduce((e,t)=>{const r=e.length-1;return e.length>0&&e[r].type===t.type?e[r].value+=t.value:e.push(t),e},[])}destroy(){this.#u||(this.#Kn=[],this.#u=!0)}};class xi{static generateHash(e){let t;try{t="object"==typeof e&&null!==e?JSON.stringify(e):String(e)}catch(e){throw new TypeError("Failed to stringify item for hashing. Ensure the object does not have circular references.")}let r=0;for(let e=0,i=t.length;e<i;e++)r=(r<<5)-r+t.charCodeAt(e),r|=0;return r.toString(36)}#Yn=[];#Xn=null;#Qn=!0;get idKey(){return this.#Xn}set idKey(e){if(null!==e&&"string"!=typeof e)throw new TypeError("The idKey must be a string or null.");this.#Xn=e}get deepComparison(){return this.#Qn}set deepComparison(e){if("boolean"!=typeof e)throw new TypeError("The deepComparison option must be a boolean.");this.#Qn=e}get oldArray(){return this.#Yn}set oldArray(e){if(!Array.isArray(e))throw new TypeError("The provided oldArray must be a valid Array.");this.#Yn=e}constructor(e,t={}){void 0!==e&&(this.oldArray=e),"string"==typeof t.idKey&&(this.idKey=t.idKey),"boolean"==typeof t.deepComparison&&(this.deepComparison=t.deepComparison)}_generateHash(e){return xi.generateHash(e)}#Zn(e,t){const r={added:{},deleted:{},modified:{},nested:{}},i=new Set([...Object.keys(e),...Object.keys(t)]);for(const s of i){const i=e[s],n=t[s];if(s in e)if(s in t)if("object"!=typeof i||null===i||"object"!=typeof n||null===n||Array.isArray(i)||Array.isArray(t))i!==n&&(r.modified[s]={oldValue:i,newValue:n});else{const e=this.#Zn(i,n);(Object.keys(e.added).length>0||Object.keys(e.deleted).length>0||Object.keys(e.modified).length>0||Object.keys(e.nested).length>0)&&(r.nested[s]=e)}else r.deleted[s]=i;else r.added[s]=n}return r}compare(e){if(!Array.isArray(e))throw new TypeError("The provided newArray must be a valid Array.");const t={oldItemsMap:new Map,affectedItems:[]};for(const e of this.#Yn){const r=this._generateHash(e),i=null!==this.#Xn&&null!==e&&"object"==typeof e&&this.#Xn in e?e[this.#Xn]:r;t.oldItemsMap.set(i,{item:e,hash:r})}for(const r of e){const e=this._generateHash(r),i=null!==this.#Xn&&null!==r&&"object"==typeof r&&this.#Xn in r?r[this.#Xn]:e,s=t.oldItemsMap.get(i);if(s)if(s.hash===e)t.oldItemsMap.delete(i);else{const e={item:r,oldItem:s.item,status:"edited"};this.#Qn&&"object"==typeof r&&null!==r&&"object"==typeof s.item&&null!==s.item&&(e.details=this.#Zn(s.item,r)),t.affectedItems.push(e),t.oldItemsMap.delete(i)}else t.affectedItems.push({item:r,status:"added"})}for(const e of t.oldItemsMap.values())t.affectedItems.push({item:e.item,status:"deleted"});return t.affectedItems}}const Ai=xi,Ci=e=>{if(!Array.isArray(e))throw new TypeError("Parameter 'sets' must be an array.");if(!e.every(e=>e instanceof Mi))throw new TypeError("All elements in the array must be instances of FuzzySet.")},Ii=(e,t,r=.5)=>{Di(e,"object","defuzzifyCentroid.fuzzyOutput");for(const t in e)Di(e[t],"number",`fuzzyOutput['${t}']`);Ci(t),Di(r,"number","defuzzifyCentroid.step");let i=0,s=0;for(let n=0;n<=100;n+=r){let r=0;t.forEach(t=>{const i=e[t.name]||0,s=Math.min(i,t.calculate(n));r=Math.max(r,s)}),i+=n*r,s+=r}return 0===s?0:i/s},ki=(e,t,r,i,s,n=!1)=>{if(n){if(e<=t||e>=s)return 0;if(e>=r&&e<=i)return 1}const o=t===r?1:(e-t)/(r-t),a=i===s?1:(s-e)/(s-i),l=Math.max(0,Math.min(o,1,a));return isNaN(l)?0:l},Di=(e,t,r)=>{if(typeof e!==t)throw new TypeError(`Parameter '${r}' must be a ${t}.`)};class Mi{static trapezoid(e,t,r,i,s,n=!1){return ki(e,t,r,i,s,n)}#eo="";#to=0;#ro=0;#io=0;#so=0;#no=!1;get name(){return this.#eo}set name(e){Di(e,"string","FuzzySet.name"),this.#eo=e}get a(){return this.#to}set a(e){Di(e,"number","FuzzySet.a"),this.#to=e}get b(){return this.#ro}set b(e){Di(e,"number","FuzzySet.b"),this.#ro=e}get c(){return this.#io}set c(e){Di(e,"number","FuzzySet.c"),this.#io=e}get d(){return this.#so}set d(e){Di(e,"number","FuzzySet.d"),this.#so=e}get optimize(){return this.#no}set optimize(e){Di(e,"boolean","FuzzySet.optimize"),this.#no=e}constructor(e,t,r,i,s,n=!1){this.name=e,this.a=t,this.b=r,this.c=i,this.d=s,this.optimize=n}calculate(e){return Di(e,"number","calculate.x"),Mi.trapezoid(e,this.#to,this.#ro,this.#io,this.#so,this.#no)}}class Li{#oo=new Map;addVariable(e,t){Di(e,"string","addVariable.name"),Ci(t),this.#oo.set(e,t)}removeVariable(e){return Di(e,"string","removeVariable.name"),this.#oo.delete(e)}getVariable(e){Di(e,"string","getVariable.name");const t=this.#oo.get(e);if(!t)throw new Error(`Linguistic variable '${e}' not found in the inference system.`);return[...t]}hasVariable(e){return Di(e,"string","hasVariable.name"),this.#oo.has(e)}fuzzify(e,t){Di(e,"string","fuzzify.varName"),Di(t,"number","fuzzify.value");const r=this.#oo.get(e)||[],i={};return r.forEach(e=>{i[e.name]=e.calculate(t)}),i}}class Ni{#ao=new Set;get appliedPlugins(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return[...this.#ao]}#ho=[];get appliedPluginClasses(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return[...this.#ho]}get size(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return this.#ho.length}#uo;get currentClass(){if(this.#lo)throw new Error("[TinyClassManager] Cannot get a consumed manager instance.");return this.#uo}#lo=!1;get used(){return this.#lo}constructor(e,t=[]){this.#uo=e,this.#ho=[...t,e]}#co(e,t,r){if(this.#lo)throw new Error("[TinyClassManager] Cannot reuse a consumed manager instance.");if(this.#ao.has(e))throw new Error(`[TinyClassManager] Plugin conflict: "${e}" is already installed.`);for(const r of t)if(!this.#ao.has(r))throw new Error(`[TinyClassManager] Missing Dependency: "${e}" requires "${r}" to be installed first.`);const i=new Ni(r,this.#ho);return this.#ao.forEach(e=>i.#ao.add(e)),i.#ao.add(e),this.#lo=!0,this.#ao.clear(),this.#ho=[],i}use(e){const t=e.dependencies||[],r=e.apply(this.#uo,this.appliedPluginClasses);return this.#co(e.name,t,r)}insert(e){const t=e(this.#uo,this.appliedPluginClasses),r=t._tinyDepName;if(!r)throw new Error("[TinyClassManager] Plugin class must define a static '_tinyDepName' property.");const i=t._tinyDeps??[];if(!Array.isArray(i)||!i.every(e=>"string"==typeof e))throw new Error("[TinyClassManager] Plugin class must define a static array of strings in '_tinyDepName' property.");return this.#co(r,i,t)}build(){if(this.#lo)throw new Error("[TinyClassManager] Cannot build from an already finalized manager.");return this.#lo=!0,this.#ao.clear(),this.#ho=[],this.#uo}}const _i=Ni,Ri=le("TinyRadioFm"),ji=e().EventEmitter;class Pi extends ji{static async parseContent(e,t,r,i,s,n=!0){return or(e,t,r,i,s,n,Pi.#do)}static#do="Unknown Artist";static get unknownArtist(){return Pi.#do}static set unknownArtist(e){if("string"!=typeof e&&"function"!=typeof e)throw new TypeError("unknownArtist must have an string or function.");Pi.#do=e}#u=!1;get destroyed(){return this.#u}get size(){return Ri(this.#u),this.#mo.length+this.#po.length}get musicSize(){return Ri(this.#u),this.#mo.length}get voiceSize(){return Ri(this.#u),this.#po.length}get customPosSize(){return Ri(this.#u),this.#fo.length}get tasksSize(){return Ri(this.#u),this.#yo.length}get cycleCacheSize(){return Ri(this.#u),this.#go.size}#mo=[];get musicList(){return Ri(this.#u),structuredClone(this.#mo)}#po=[];get voiceList(){return Ri(this.#u),structuredClone(this.#po)}#fo=[];get customPositions(){return Ri(this.#u),structuredClone(this.#fo)}#yo=[];get scheduledTasks(){return Ri(this.#u),structuredClone(this.#yo)}get allList(){return Ri(this.#u),[...this.musicList,...this.voiceList]}#fs=0;get seed(){return Ri(this.#u),this.#fs}set seed(e){if(Ri(this.#u),"number"!=typeof e)throw new TypeError("Seed must be a number.");this.#fs=e,this.#go.clear(),this.emit("seedChanged",{seed:e})}#wo=Date.now();get anchorDate(){return Ri(this.#u),this.#wo}#go=new Map;#vt={mode:"playlist",voiceMode:"playlist",silenceDuration:0,queryLimit:1e5,voiceAfterMusic:!0,voiceMin:0,voiceMax:1,voiceWeight:1,musicMaxConsecutive:0,musicMinConsecutive:0,voiceMaxConsecutive:0,voiceMinConsecutive:0};get config(){return Ri(this.#u),structuredClone(this.#vt)}set config(e){Ri(this.#u),this.#bo(e),this.#vt=structuredClone(e),this.#go.clear(),this.emit("configChanged",{config:this.config})}#bo(e){if("object"!=typeof e||null===e)throw new TypeError("Configuration must be a valid object.");const t=["playlist","random"];if(void 0!==e.mode&&!t.includes(e.mode))throw new TypeError(`Invalid mode: "${e.mode}". Must be one of: ${t.join(", ")}.`);if(void 0!==e.voiceMode&&!t.includes(e.voiceMode))throw new TypeError(`Invalid voiceMode: "${e.voiceMode}". Must be one of: ${t.join(", ")}.`);if(void 0!==e.silenceDuration&&("number"!=typeof e.silenceDuration||e.silenceDuration<0))throw new TypeError("silenceDuration must be a non-negative number.");if(void 0!==e.queryLimit&&("number"!=typeof e.queryLimit||e.queryLimit<=0))throw new TypeError("queryLimit must be a positive number.");if(void 0!==e.voiceAfterMusic&&"boolean"!=typeof e.voiceAfterMusic)throw new TypeError("voiceAfterMusic must be a boolean.");const r=(e,t)=>{if(void 0!==e&&("number"!=typeof e||e<0))throw new TypeError(`${t} must be a non-negative number.`)};r(e.voiceWeight,"voiceWeight"),r(e.voiceMin,"voiceMin"),r(e.voiceMax,"voiceMax"),r(e.musicMinConsecutive,"musicMinConsecutive"),r(e.musicMaxConsecutive,"musicMaxConsecutive"),r(e.voiceMinConsecutive,"voiceMinConsecutive"),r(e.voiceMaxConsecutive,"voiceMaxConsecutive");const i=e.voiceMin??this.#vt.voiceMin,s=e.voiceMax??this.#vt.voiceMax;if(s<i)throw new RangeError(`Logical error: voiceMax (${s}) cannot be less than voiceMin (${i}).`);const n=e.musicMinConsecutive??this.#vt.musicMinConsecutive,o=e.musicMaxConsecutive??this.#vt.musicMaxConsecutive;if(-1!==o&&n>o)throw new RangeError(`Logical error: musicMinConsecutive (${n}) cannot be greater than musicMaxConsecutive (${o}).`)}#vo=!0;get optimizeMediaMemory(){return Ri(this.#u),this.#vo}set optimizeMediaMemory(e){if(Ri(this.#u),"boolean"!=typeof e)throw new TypeError("optimizeMediaMemory must be a boolean.");this.#vo=e}#Eo=!0;get optimizePictureMemory(){return Ri(this.#u),this.#Eo}set optimizePictureMemory(e){if(Ri(this.#u),"boolean"!=typeof e)throw new TypeError("optimizePictureMemory must be a boolean.");this.#Eo=e}constructor(e=null,t=0){if(super(),null!==e&&"object"!=typeof e)throw new TypeError("initialData must be an object or null.");if("number"!=typeof t)throw new TypeError("seed must be a number.");this.#fs=t,e?this.#To(e):this.#wo=Date.now()}_ccBase64ToBlobUrl(e){this.#vo&&"string"==typeof e.url&&e.url.startsWith("data:")&&(e.url=er(e.url)),e.picture&&Array.isArray(e.picture)&&(e.picture=e.picture.map(e=>{if(this.#Eo){const t="string"==typeof e.data&&e.data.startsWith("data:"),r=e.data instanceof Uint8Array;if(t||r)return{...e,data:er(e.data,e.format)}}return e}))}async _rcblobUrlToBase64(e){this.#vo&&"string"==typeof e.url&&e.url.startsWith("blob:")&&(e.url=await tr(e.url)),this.#Eo&&e.picture&&Array.isArray(e.picture)&&(e.picture=await Promise.all(e.picture.map(async e=>"string"==typeof e.data&&e.data.startsWith("blob:")?{...e,data:await tr(e.data)}:e)))}add(e,t,r=!0){if(Ri(this.#u),!["music","voice","custom"].includes(e))throw new TypeError('Type must be "music", "voice", or "custom".');if(!t||"string"!=typeof t.id||"number"!=typeof t.duration)throw new TypeError("Content must have a string ID and a valid numerical duration in milliseconds.");if("boolean"!=typeof r)throw new TypeError("smartQueue must be a boolean.");sr(t);const i=structuredClone(t);this._ccBase64ToBlobUrl(i),"music"===e?(this.#mo.push(i),this.#go.clear()):"voice"===e?(this.#po.push(i),this.#go.clear()):"custom"===e&&this.#So(i,r),this.#xo(Date.now()),this.emit("contentAdded",{type:e,data:structuredClone(i)})}scheduleTask(e,t,r,i,s=!0){if(Ri(this.#u),"number"!=typeof e||isNaN(e))throw new TypeError("timestamp must be a valid number.");if(!["add","remove","move"].includes(t))throw new TypeError('action must be "add", "remove", or "move".');if(!["music","voice"].includes(r))throw new TypeError('type must be "music" or "voice".');if("boolean"!=typeof s)throw new TypeError("smartQueue must be a boolean.");if("add"===t){if("object"!=typeof i||null===i||"string"!=typeof i.id||"number"!=typeof i.duration)throw new TypeError('Payload for "add" must be a MediaContent object (id: string, duration: number).')}else if("remove"===t){if("string"!=typeof i)throw new TypeError('Payload for "remove" must be a string (the content ID).')}else if("move"===t&&("object"!=typeof i||null===i||"string"!=typeof i.id||"number"!=typeof i.newIndex))throw new TypeError('Payload for "move" must be a ScheduledMovePayload (id: string, newIndex: number).');let n=e;if(s){const t=this.#Ao(e,e);t&&(n=t.absoluteEnd)}v(i)&&"number"!=typeof i.newIndex&&sr(i);const o={timestamp:n,action:t,type:r,payload:i};this.#yo.push(o),this.#xo(Date.now()),this.emit("taskScheduled",structuredClone(o))}remove(e){if(Ri(this.#u),"string"!=typeof e)throw new TypeError("id must be a string.");this.#mo.filter(t=>t.id===e).forEach(e=>rr(e)),this.#po.filter(t=>t.id===e).forEach(e=>rr(e)),this.#fo.filter(t=>t.content?.id===e).forEach(e=>rr(e.content));const t=t=>t.id!==e&&t.content?.id!==e;this.#mo=this.#mo.filter(t),this.#po=this.#po.filter(t),this.#fo=this.#fo.filter(t),this.#yo=this.#yo.filter(t=>"add"===t.action&&"object"==typeof t.payload&&null!==t.payload&&"id"in t.payload?t.payload.id!==e||(rr(t.payload),!1):t.payload!==e),this.#go.clear(),this.emit("contentRemoved",{id:e})}setConfig(e){Ri(this.#u),this.#bo(e);const t={...this.#vt,...e};this.#bo(t),this.#vt=t,this.#go.clear(),this.emit("configChanged",{config:this.config})}getCurrentEvent(){Ri(this.#u);const e=Date.now();return this.#xo(e),this.#Ao(e,e)}queryTimeline(e,t=10){if(Ri(this.#u),"number"!=typeof t||isNaN(t))throw new TypeError("Invalid query limit value. Ensure it is a number.");if(t>this.#vt.queryLimit||t<=0)throw new RangeError(`Invalid query limit. Ensure it is > 0 and <= ${this.#vt.queryLimit}.`);const r=new Pi(JSON.parse(this._exportState())),i=[];let s=e;for(let n=0;n<t;n++){r.#xo(s);const t=r.#Co(s,e);if(!t)break;i.push(t),s=t.absoluteEnd}return r.destroy(!1),this.emit("timelineQueried",{targetDate:e,limit:t,resultCount:i.length}),i}searchCustomPositions(){return Ri(this.#u),this.#xo(Date.now()),[...this.#fo]}async _processListForExport(e){return Promise.all(e.map(async e=>{sr(e);const t=structuredClone(e);return await this._rcblobUrlToBase64(t),t}))}_exportState(){return JSON.stringify({music:this.#mo,voice:this.#po,custom:this.#fo,tasks:this.#yo,seed:this.#fs,anchorDate:this.#wo,config:this.#vt})}async exportState(){Ri(this.#u);const e=await this._processListForExport(this.#mo),t=await this._processListForExport(this.#po),r=await Promise.all(this.#fo.map(async e=>{const t=await this._processListForExport([e.content]);return{...e,content:t[0]}})),i=await Promise.all(this.#yo.map(async e=>{if("add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload){const t=await this._processListForExport([e.payload]);return{...e,payload:t[0]}}return e}));return JSON.stringify({music:e,voice:t,custom:r,tasks:i,seed:this.#fs,anchorDate:this.#wo,config:this.#vt})}importState(e){let t;if(Ri(this.#u),"string"==typeof e)try{t=JSON.parse(e)}catch{throw new TypeError("Provided string is not valid JSON.")}else{if("object"!=typeof e||null===e)throw new TypeError("Import data must be a valid JSON string or an object.");t=e}this.#To(t),this.emit("stateImported",{data:structuredClone(t)})}_prng(e){return function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}#Io(e,t,r,i=0,s=0,n=null,o=0){if(0===e.length)return{items:[],lastId:n,consecutiveCount:o};if("random"!==r){const t=[...e],r=t[t.length-1];return{items:t,lastId:r.id,consecutiveCount:n===r.id?o+1:1}}const a=this._prng(t),l=[];let h=n,u=o;const c=new ei({rng:a,normalization:"relative"}),d=[...e];for(d.forEach(e=>{const t=e.weight??1,r=c.getItem(e.id);r?c.setBaseWeight(e.id,r.baseWeight+t):c.addItem(e.id,{weight:t})});d.length>0;){let e=null,t=-1;if(null!==h&&u<i&&(t=d.findIndex(e=>e.id===h),-1!==t?e=d[t]:l.length>0&&(e=l[l.length-1])),!e){let r=null;null!==h&&-1!==s&&u>=s&&d.some(e=>e.id!==h)&&(c.excludeItem(h),r=h);const i=c.drawOne();i&&(t=d.findIndex(e=>e.id===i.id),-1!==t&&(e=d[t])),r&&c.includeItem(r)}if(e||(e=d[0],t=0),l.push(e),-1!==t)if(d.splice(t,1),d.some(t=>t.id===e.id)){const t=c.getItem(e.id);if(t){const r=Math.max(0,t.baseWeight-(e.weight??1));r<=0?c.removeItem(e.id):c.setBaseWeight(e.id,r)}}else c.removeItem(e.id);e.id===h?u++:(h=e.id,u=1)}return c.destroy(),{items:l,lastId:h,consecutiveCount:u}}#ko(e){const t=this.#fs+e,r=this._prng(10*t);let i=null,s=0,n=null,o=0;if(e>0){const t=this.#go.get(e-1);t&&(i=t.lastMusicId??null,s=t.musicConsecutiveCount??0,n=t.lastVoiceId??null,o=t.voiceConsecutiveCount??0)}const a=this.#Io(this.#mo,t+1,this.#vt.mode,this.#vt.musicMinConsecutive,this.#vt.musicMaxConsecutive,i,s),l=a.items,h=this.#Io(this.#po,t+2,this.#vt.voiceMode,this.#vt.voiceMinConsecutive,this.#vt.voiceMaxConsecutive,n,o),u=h.items,c=[];let d=0,m=0;for(let e=0;e<l.length;e++){const t=l[e];if(c.push({...t,cycleStart:d,cycleEnd:d+t.duration}),d+=t.duration+this.#vt.silenceDuration,this.#vt.voiceAfterMusic&&u.length>0){const e=this.#vt.voiceWeight/(this.#vt.voiceWeight+1);if(r()<e){const e=this.#vt.voiceMax-this.#vt.voiceMin+1,t=Math.floor(r()*e)+this.#vt.voiceMin;for(let e=0;e<t;e++){const e=u[m%u.length];m++,c.push({...e,cycleStart:d,cycleEnd:d+e.duration}),d+=e.duration+this.#vt.silenceDuration}}}}return{items:c,duration:d,lastMusicId:a.lastId,musicConsecutiveCount:a.consecutiveCount,lastVoiceId:h.lastId,voiceConsecutiveCount:h.consecutiveCount}}#Do(e){if(0===this.#mo.length)return null;let t=this.#wo,r=0;for(;;){if(r>this.#vt.queryLimit)throw new Error("Safety limit hit during cycle location.");let i=this.#go.get(r);if(i||(i=this.#ko(r),this.#go.set(r,i)),0===i.duration)return null;if(e>=t&&e<t+i.duration)return{block:i,startTimestamp:t,loopIndex:r};t+=i.duration,r++}}#Co(e,t){const r=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration>e).sort((e,t)=>e.intendedTimestamp-t.intendedTimestamp)[0];let i=null;if(r){const e=Math.max(t,r.intendedTimestamp);i=this.#Mo(r.content,r.intendedTimestamp,e,!0)}const s=this.#Lo(e,t);return s||i?s?i?i.absoluteStart<=s.absoluteStart?i:(i.absoluteStart<s.absoluteEnd&&(s.absoluteEnd=i.absoluteStart,s.duration=s.absoluteEnd-s.absoluteStart,s.remainingTime=Math.max(0,s.absoluteEnd-t),s.progress=Math.min(1,s.elapsedTime/s.duration)),s):s:i:null}#Lo(e,t){let r=this.#Do(e);if(!r)return null;const{block:i,startTimestamp:s}=r,n=e-s;let o,a=i.items.find(e=>e.cycleEnd>n);if(a)o=s+a.cycleStart;else{if(r=this.#Do(s+i.duration),!r||0===r.block.items.length)return null;a=r.block.items[0],o=r.startTimestamp+a.cycleStart}const l=Math.max(t,o);return this.#Mo(a,o,l,!1)}#Ao(e,t){const r=this.#fo.find(t=>e>=t.intendedTimestamp&&e<t.intendedTimestamp+t.content.duration);if(r)return this.#Mo(r.content,r.intendedTimestamp,t,!0);const i=this.#Do(e);if(!i)return null;const{block:s,startTimestamp:n}=i,o=e-n,a=s.items.find(e=>o>=e.cycleStart&&o<e.cycleEnd);return a?this.#Mo(a,n+a.cycleStart,t,!1):null}#Mo(e,t,r,i){const s=r-t;return{id:e.id,title:e.title,artist:e.artist,duration:e.duration,url:e.url,absoluteStart:t,absoluteEnd:t+e.duration,elapsedTime:s,remainingTime:e.duration-s,progress:Math.min(1,s/e.duration),isCustom:i}}#So(e,t){let r=e.timestamp||Date.now();const i=e.duration;if(t){const e=this.#Ao(r,r);e&&(r=e.absoluteEnd)}const s=[...this.#fo].sort((e,t)=>e.intendedTimestamp-t.intendedTimestamp);let n=r;if(s.some(e=>r<e.intendedTimestamp+e.content.duration&&r+i>e.intendedTimestamp)){const e=[];let t=Date.now();for(const r of s)r.intendedTimestamp>t&&e.push({start:t,end:r.intendedTimestamp}),t=Math.max(t,r.intendedTimestamp+r.content.duration+this.#vt.silenceDuration);e.push({start:t,end:1/0});let o=1/0;for(const t of e)if(t.end-t.start>=i){let e=null;if(r>=t.start&&r+i<=t.end?e=r:r<t.start?e=t.start:r>t.end&&(e=t.end-i),null!==e){const t=Math.abs(r-e);t<o&&(o=t,n=e)}}}this.#fo.push({content:e,intendedTimestamp:n,originalTimestamp:e.timestamp||Date.now()})}#xo(e){const t=this.#yo.filter(t=>t.timestamp<=e);this.#yo=this.#yo.filter(t=>t.timestamp>e);const r=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration<=e);this.#fo=this.#fo.filter(t=>t.intendedTimestamp+t.content.duration>e);let i=!1;r.forEach(e=>{rr(e.content),this.#fs+=e.content.id.length,i=!0,this.emit("customPositionExpired",{contentId:e.content.id})}),t.length>0&&t.sort((e,t)=>e.timestamp-t.timestamp).forEach(e=>{const t="music"===e.type?this.#mo:this.#po;if("add"===e.action)t.push(e.payload);else if("remove"===e.action){const r=t.findIndex(t=>t.id===e.payload);if(-1!==r){const[e]=t.splice(r,1);rr(e)}}else if("move"===e.action){const r=e.payload,i=t.findIndex(e=>e.id===r.id);if(-1!==i){const[e]=t.splice(i,1);t.splice(r.newIndex,0,e)}}this.#wo=e.timestamp,this.#fs+=1,i=!0,this.emit("taskExecuted",structuredClone(e))}),i&&this.#go.clear()}#To(e){this.#mo.forEach(e=>rr(e)),this.#po.forEach(e=>rr(e)),this.#fo.forEach(e=>rr(e.content)),this.#yo.forEach(e=>{"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload&&rr(e.payload)});const t=e=>e.map(e=>{sr(e);const t=structuredClone(e);return this._ccBase64ToBlobUrl(t),t});this.#mo=t(e.music),this.#po=t(e.voice),this.#fs=e.seed||0,this.#wo=e.anchorDate||Date.now(),this.#vt={...this.#vt,...e.config||{}},this.#fo=e.custom.map(e=>({...e,content:t([e.content])[0]})),this.#yo=e.tasks.map(e=>"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload?{...e,payload:t([e.payload])[0]}:e)}destroy(e=!0){this.#u||(e&&(this.#mo.forEach(e=>rr(e)),this.#po.forEach(e=>rr(e)),this.#fo.forEach(e=>rr(e.content)),this.#yo.forEach(e=>{"add"===e.action&&e.payload&&"object"==typeof e.payload&&"title"in e.payload&&rr(e.payload)})),this.#mo=[],this.#po=[],this.#fo=[],this.#yo=[],this.#go.clear(),this.emit("destroyed",{timestamp:Date.now()}),this.removeAllListeners(),this.#u=!0)}}const Oi=Pi,$i=()=>"undefined"!=typeof window&&void 0!==window.document,Hi="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null,Fi="undefined"!=typeof document?document:null,zi=["chrome","firefox","ie","edge","safari","opera","yandex","other"];function Bi(){if("undefined"==typeof navigator)return"other";const e=navigator.userAgent;return-1!==e.indexOf("Chrome")?"chrome":-1!==e.indexOf("Firefox")?"firefox":-1!==e.indexOf("MSIE")?"ie":-1!==e.indexOf("Edge")?"edge":-1!==e.indexOf("Safari")?"safari":-1!==e.indexOf("Opera")?"opera":-1!==e.indexOf("YaBrowser")?"yandex":"other"}function Wi(){const e=Hi?.getComputedStyle?(Array.prototype.slice.call(Hi.getComputedStyle(document.documentElement,"")).join("").match(/-(moz|webkit|ms)-/)??["",""])[1]:"";return"moz"===e?"gecko":"webkit"===e?"webkit":"ms"===e?"trident":"other"}function Ui(){const e=!!Hi?.opr&&!!opr.addons||!!Hi?.opera||navigator.userAgent.indexOf(" OPR/")>=0,t="undefined"!=typeof InstallTrigger,r=!!Hi?.HTMLElement&&/constructor/i.test(Hi.HTMLElement)||"[object SafariRemoteNotification]"===(!Hi.safari||"undefined"!=typeof safari&&safari.pushNotification).toString(),i=!!Fi?.documentMode,s=!i&&!!Hi?.StyleMedia,n=!!Hi?.chrome;return{isOpera:e,isFirefox:t,isSafari:r,isIE:i,isEdge:s,isChrome:n,isBlink:(n||e)&&!!Hi?.CSS}}function qi(e=[]){if(!Array.isArray(e))throw new TypeError('The "disable" argument must be an array.');for(const t of e)if(!zi.includes(t))throw new TypeError(`Invalid browser name provided in disable array: ${t}`);const t={chrome:0,firefox:0,ie:0,edge:0,safari:0,opera:0,yandex:0,other:0};t[Bi()]++;const r=Wi();"gecko"===r?e.indexOf("firefox")<0&&t.firefox++:"webkit"===r?(e.indexOf("chrome")<0&&t.chrome++,e.indexOf("safari")<0&&t.safari++,e.indexOf("opera")<0&&t.opera++,e.indexOf("edge")<0&&t.edge++):"trident"===r?e.indexOf("ie")<0&&t.ie++:e.indexOf("other")<0&&t.other++;const i=Ui();return i.isOpera&&e.indexOf("opera")<0&&t.opera++,i.isFirefox&&e.indexOf("firefox")<0&&t.firefox++,i.isSafari&&e.indexOf("safari")<0&&t.safari++,i.isIE&&e.indexOf("ie")<0&&t.ie++,i.isEdge&&e.indexOf("edge")<0&&t.edge++,i.isChrome&&e.indexOf("chrome")<0&&t.chrome++,t}function Vi(e=[]){const t=qi(e);return Object.keys(t).reduce((e,r)=>t[r]>t[e]?r:e)}const Ki=e().EventEmitter,Gi=class extends Ki{#No;#_o;#Ro=null;#jo;#Po;#Oo;#$o;#Ho=new Map([["log",""],["info",""],["warn",""],["error",""],["debug",""],["main_class",""],["sub_class",""],["reset",""],["black",""],["red",""],["green",""],["yellow",""],["blue",""],["magenta",""],["cyan",""],["white",""],["gray",""]]);#Fo=new Map([["log","[_log_LOG_reset_]"],["info","[_info_INFO_reset_]"],["warn","[_warn_WARN_reset_]"],["error","[_error_ERROR_reset_]"],["debug","[_debug_DEBUG_reset_]"]]);constructor({logger:e,id:t,debugMode:r,canEmitLogs:i=!1,useLogColors:s=!1,autoHideId:n=!1}){if(super(),!E(e))throw new TypeError("Logger must be an object that implements the Console interface.");if("string"!=typeof t)throw new TypeError("Logger instance id must be a string.");if("boolean"!=typeof r)throw new TypeError("debugMode must be a boolean.");if("boolean"!=typeof i)throw new TypeError("canEmitLogs must be a boolean.");if("boolean"!=typeof s)throw new TypeError("useLogColors must be a boolean.");if("boolean"!=typeof n)throw new TypeError("autoHideId must be a boolean.");this.#_o=t,this.#No=e,this.#Po=r,this.#jo=i,this.#$o=n,this.#Oo="firefox"!==Vi()&&s,this.log("info","Emit logs of debug mode set to: "+(this.#Po?"ON":"OFF")),this.log("info","Custom logger assigned.")}get logId(){return this.#_o}get logSubId(){if("string"!=typeof this.#Ro)throw new Error('logSubId has not been set yet. Assign a string to "logSubId" before reading it.');return this.#Ro}set logSubId(e){if("string"!=typeof e)throw new TypeError(`logSubId must be a string. Received: ${typeof e}.`);if(null!==this.#Ro)throw new Error(`logSubId is already set to "${this.#Ro}" and cannot be reassigned.`);this.#Ro=e,this.emit("setLogSubId",e)}get canEmitLogs(){return this.#jo}get useLogColors(){return this.#Oo}set useLogColors(e){if("boolean"!=typeof e)throw new TypeError("useLogColors must be a boolean.");this.#Oo=e,this.log("info","Log Colors usage mode set to: "+(this.#Oo?"ON":"OFF")),this.emit("setUseLogColors",e)}get debugMode(){return this.#Po}set debugMode(e){if("boolean"!=typeof e)throw new TypeError("debugMode must be a boolean.");this.#Po=e,this.log("info","Debug mode set to: "+(this.#Po?"ON":"OFF")),this.emit("setDebugMode",e)}_addLogColor(e,t){this.#Ho.set(e,t)}_removeLogColor(e){this.#Ho.delete(e)}_addLogPrefix(e,t){this.#Fo.set(e,t)}_removeLogPrefix(e){this.#Fo.delete(e)}#zo(e){if("string"!=typeof e)return e;let t=e;for(const[e,r]of this.#Fo){const i=new RegExp(`\\:${e}\\:`,"g");t=t.replace(i,r)}for(const[e,r]of this.#Ho){const i=new RegExp(`\\_${e}\\_`,"g");t=t.replace(i,this.#Oo?r:"")}return t}_applyLogFormatting(e){return this.#zo(e)}logClear(){if(this.#Po)return this.#jo&&this.emit("debug:clear"),this.#No.clear?this.#No.clear():console.clear()}logGroupEnd(){if(this.#Po)return this.#jo&&this.emit("debug:groupEnd"),this.#No.groupEnd?this.#No.groupEnd():console.groupEnd()}logLabel(e,t){if(!this.#Po)return;const r=["count","countReset","time","timeEnd","profile","profileEnd","timeStamp"];if(!r.includes(e))throw new TypeError(`Invalid logType. Expected one of: ${r.join(", ")}`);if(void 0!==t&&"string"!=typeof t)throw new TypeError("The label must be a string.");const i=this.#No[e]?this.#No[e]:console[e];if(!i)throw new TypeError(`The log type "${e}" is not supported by the provided logger or console.`);return this.#jo&&this.emit("debug:logLabel",e,t),i(t)}logTimeLabel(e,...t){if(this.#Po)return this.#jo&&this.emit("debug:timeLog",e,...t),this.#No.timeLog?this.#No.timeLog(e,...t):console.timeLog(e,...t)}logAssert(e,...t){if(this.#Po)return this.#jo&&this.emit("debug:assert",e,...t),this.#No.assert?this.#No.assert(e,...t):console.assert(e,...t)}logDir(e,t){if(this.#Po)return this.#jo&&this.emit("debug:dir",e,t),this.#No.dir?this.#No.dir(e,t):console.dir(e,t)}logTable(e,t){if(this.#Po){if(!(void 0===t||Array.isArray(t)&&t.every(e=>"string"==typeof e)))throw new TypeError("Properties must be an array of strings.");return this.#jo&&this.emit("debug:table",e,t),this.#No.table?this.#No.table(e,t):console.table(e,t)}}log(e,t,...r){if(!this.#Po)return;const i=["log","info","warn","error","debug","dirxml","group","groupCollapsed","trace"];if(!i.includes(e))throw new TypeError(`Invalid logType. Expected one of: ${i.join(", ")}`);if("string"!=typeof t)throw new TypeError("The message must be a string.");let s=this.#_o,n=this.#Ro??"",o=t;const a=!this.#$o||"string"!=typeof this.#Ro;s=a?this.#zo(s):"",n&&(n=this.#zo(n)),o=this.#zo(o);const l=`${s}${n?a?` ${n}`:n:""}`,h=this.#No[e]?this.#No[e]:console[e];return h?(this.#jo&&this.emit("debug:log",l,o,...r),h(l,o,...r)):(this.#jo&&this.emit("debug:log",l,o,...r),console.log(l,o,...r))}#Bo(e,t){const[r="",...i]=t;return"string"==typeof r?this.log(e,r,...i):this.log(e,"",r,...i)}toConsole(){return{log:(...e)=>this.#Bo("log",e),info:(...e)=>this.#Bo("info",e),warn:(...e)=>this.#Bo("warn",e),error:(...e)=>this.#Bo("error",e),debug:(...e)=>this.#Bo("debug",e),dirxml:(...e)=>this.#Bo("dirxml",e),group:(...e)=>this.#Bo("group",e),groupCollapsed:(...e)=>this.#Bo("groupCollapsed",e),trace:(...e)=>this.#Bo("trace",e),assert:(e,...t)=>this.logAssert(e,...t),dir:(e,t)=>this.logDir(e,t),table:(e,t)=>this.logTable(e,t),clear:()=>this.logClear(),groupEnd:()=>this.logGroupEnd(),count:e=>this.logLabel("count",e),countReset:e=>this.logLabel("countReset",e),time:e=>this.logLabel("time",e),timeEnd:e=>this.logLabel("timeEnd",e),timeLog:(e,...t)=>this.logTimeLabel(e,...t),timeStamp:e=>this.logLabel("timeStamp",e),profile:e=>this.logLabel("profile",e),profileEnd:e=>this.logLabel("profileEnd",e)}}},Ji=le("BaseMediaAdapter"),Yi=e().EventEmitter;class Xi extends Yi{constructor(){if(new.target===Xi)throw new Error("BaseMediaAdapter is an abstract class and cannot be instantiated directly.");super()}#u=!1;get destroyed(){return this.#u}static getThumbnailUrl(e){if("string"!=typeof e||""===e.trim())throw new TypeError('The "trackId" must be a non-empty string.');return""}static canHandle(e){throw new Error('Method "canHandle" must be implemented by the subclass.')}isReady(){throw Ji(this.#u),new Error('Method "isReady" must be implemented by the subclass.')}isPaused(){throw Ji(this.#u),new Error('Method "isPaused" must be implemented by the subclass.')}isEnded(){throw Ji(this.#u),new Error('Method "isEnded" must be implemented by the subclass.')}async waitIsReady(){throw Ji(this.#u),new Error('Method "waitIsReady" must be implemented by the subclass.')}canHandle(e){return Ji(this.#u),Xi.canHandle(e)}async play(e){throw Ji(this.#u),new Error('Method "play" must be implemented by the subclass.')}async pause(){throw Ji(this.#u),new Error('Method "pause" must be implemented by the subclass.')}async stop(){throw Ji(this.#u),new Error('Method "stop" must be implemented by the subclass.')}async seek(e){throw Ji(this.#u),new Error('Method "seek" must be implemented by the subclass.')}isMuted(){throw Ji(this.#u),new Error('Method "isMuted" must be implemented by the subclass.')}async mute(){throw Ji(this.#u),new Error('Method "mute" must be implemented by the subclass.')}async unMute(){throw Ji(this.#u),new Error('Method "unMute" must be implemented by the subclass.')}getCurrentTime(){throw Ji(this.#u),new Error('Method "getCurrentTime" must be implemented by the subclass.')}getTotalDuration(){throw Ji(this.#u),new Error('Method "getTotalDuration" must be implemented by the subclass.')}getRemainingTime(){throw Ji(this.#u),new Error('Method "getRemainingTime" must be implemented by the subclass.')}getPlaybackPercentage(){throw Ji(this.#u),new Error('Method "getPlaybackPercentage" must be implemented by the subclass.')}getTimeData(){throw Ji(this.#u),new Error('Method "getTimeData" must be implemented by the subclass.')}setVolume(e){throw Ji(this.#u),new Error('Method "setVolume" must be implemented by the subclass.')}getVolume(){throw Ji(this.#u),new Error('Method "getVolume" must be implemented by the subclass.')}async getContentData(){throw Ji(this.#u),new Error('Method "getContentData" must be implemented by the subclass.')}destroy(){this.#u||(this.removeAllListeners(),this.#u=!0,this.emit("destroyed"))}}const Qi=le("TinyMediaPlayer");class Zi extends Gi{static BaseMediaAdapter=Xi;static#do="Unknown Artist";static get unknownArtist(){return Zi.#do}static set unknownArtist(e){if("string"!=typeof e&&"function"!=typeof e)throw new TypeError("unknownArtist must be a string or a function.");Zi.#do=e}static async parseContent(e,t,r,i,s,n){return or(e,t,r,i,s,n,Zi.#do)}#u=!1;get destroyed(){return this.#u}#Wo=new Set;#Uo=new WeakMap;#qo=[];#Vo=-1;#Ko="NONE";#Go=!1;#Jo=!1;#Yo=!1;#Xo=1;#Qo;#Zo;#ea;#ta=!1;#ra;#ia;#sa=null;#na=null;#oa=300;get fadeVolumeSpeed(){return Qi(this.#u),this.#oa}set fadeVolumeSpeed(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("fadeVolumeSpeed must be a number.");if(e<0)throw new RangeError("fadeVolumeSpeed cannot be negative.");this.#oa=e,this.emit("fadeVolumeSpeedChange",this.#oa)}#aa=2e3;get prevClickTimeoutDuration(){return Qi(this.#u),this.#aa}set prevClickTimeoutDuration(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("prevClickTimeoutDuration must be a number.");if(e<0)throw new RangeError("prevClickTimeoutDuration cannot be negative.");this.#aa=e,this.emit("prevClickTimeoutDurationChange",this.#aa)}get repeatCurrentOnPrev(){return Qi(this.#u),this.#ea}set repeatCurrentOnPrev(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("repeatCurrentOnPrev must be a boolean.");this.#ea=e,this.emit("repeatCurrentOnPrevChange",this.#ea)}get smoothPlayPauseVolume(){return Qi(this.#u),this.#ra}set smoothPlayPauseVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("smoothPlayPauseVolume must be a boolean.");this.#ra=e,this.emit("smoothPlayPauseVolumeChange",this.#ra)}get smoothStopVolume(){return Qi(this.#u),this.#ia}set smoothStopVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("smoothStopVolume must be a boolean.");this.#ia=e,this.emit("smoothStopVolumeChange",this.#ia)}constructor(e={}){if(!E(e))throw new TypeError("Options must be a non-null object.");if(super({id:"[_main_class_TinyMediaPlayer_reset_]",logger:e.logger??console,debugMode:e.debugMode??!1,useLogColors:e.useLogColors??!1}),void 0!==e.persistVolume){if("boolean"!=typeof e.persistVolume)throw new TypeError("persistVolume must be a boolean.");this.#Qo=e.persistVolume}else this.#Qo=!1;if(void 0!==e.volumeStorageKey){if("string"!=typeof e.volumeStorageKey)throw new TypeError("volumeStorageKey must be a string.");this.#Zo=e.volumeStorageKey}else this.#Zo="tiny_media_player_volume";if(void 0!==e.repeatCurrentOnPrev){if("boolean"!=typeof e.repeatCurrentOnPrev)throw new TypeError("repeatCurrentOnPrev must be a boolean.");this.#ea=e.repeatCurrentOnPrev}else this.#ea=!1;if(void 0!==e.smoothPlayPauseVolume){if("boolean"!=typeof e.smoothPlayPauseVolume)throw new TypeError("smoothPlayPauseVolume must be a boolean.");this.#ra=e.smoothPlayPauseVolume}else this.#ra=!1;if(void 0!==e.smoothStopVolume){if("boolean"!=typeof e.smoothStopVolume)throw new TypeError("smoothStopVolume must be a boolean.");this.#ia=e.smoothStopVolume}else this.#ia=!1;this.#Qo&&this.#la(),this.log("info","Instance initialized.",{options:e})}#la(){try{if("undefined"!=typeof window&&window.localStorage){const e=window.localStorage.getItem(this.#Zo);if(null!==e){const t=parseFloat(e);!isNaN(t)&&t>=0&&t<=1&&(this.#Xo=t,this.log("info",`Volume loaded from storage: ${this.#Xo}`))}}}catch(e){console.warn("[TinyMediaPlayer] Failed to read volume from localStorage.",e)}}#ha(){try{this.#Qo&&"undefined"!=typeof window&&window.localStorage&&(window.localStorage.setItem(this.#Zo,this.#Xo.toString()),this.log("info",`Volume saved to storage: ${this.#Xo}`))}catch(e){console.warn("[TinyMediaPlayer] Failed to save volume to localStorage.",e)}}_getWeightedRandomIndex(){if(0===this.#qo.length)return-1;if(1===this.#qo.length)return 0;let e=0;for(let t=0;t<this.#qo.length;t++){if(t===this.#Vo)continue;const r=this.#qo[t];e+="number"==typeof r.weight&&r.weight>0?r.weight:1}let t=Math.random()*e;for(let e=0;e<this.#qo.length;e++){if(e===this.#Vo)continue;const r=this.#qo[e],i="number"==typeof r.weight&&r.weight>0?r.weight:1;if(t<i)return e;t-=i}return this.#Vo===this.#qo.length-1?0:this.#qo.length-1}async#ua(e){this.#sa&&this.#sa.abort(),this.#sa=new AbortController;const{signal:t}=this.#sa,r=this.#ca();if(!r)return;const i=r.getVolume(),s=performance.now(),n=this.#oa;return this.log("info",`Starting volume fade: ${i} -> ${e}`),new Promise(o=>{const a=l=>{if(t.aborted)return this.log("info","Volume fade aborted."),o();const h=l-s,u=Math.min(h/n,1),c=i+(e-i)*u,d=Math.max(0,Math.min(1,c));r.setVolume(d),u<1?requestAnimationFrame(a):(r.setVolume(e),this.log("info",`Volume fade completed: ${e}`),o())};requestAnimationFrame(a)})}get playlist(){return Qi(this.#u),[...this.#qo]}set playlist(e){if(Qi(this.#u),!Array.isArray(e))throw new TypeError("Playlist must be an array of MediaContent objects.");e.forEach(e=>sr(e));const t=this.#Jo;let r=null;if(-1!==this.#Vo&&this.#qo.length>0)try{r=this.#ca()}catch(e){}this.#qo=e,this.log("info",`Playlist updated. New size: ${this.#qo.length}`),this.emit("playlistUpdate",this.playlist),0===this.#qo.length?this.#Vo=-1:(this.#Vo>=this.#qo.length||-1===this.#Vo)&&(this.#Vo=0),this.emit("trackChange",this.#Vo),t&&(async()=>{try{r&&await r.stop(),-1!==this.#Vo&&await this.play()}catch(e){this.log("error","Background transition error on playlist update:",e),console.warn("[TinyMediaPlayer] Background transition error on playlist update:",e)}})()}get currentIndex(){return Qi(this.#u),this.#Vo}set currentIndex(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Current index must be a number.");if(e<-1||e>=this.#qo.length&&this.#qo.length>0)throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);if(this.#Vo===e)return;this.log("info",`Index change requested: ${this.#Vo} -> ${e}`);const t=this.#Jo;let r=null;if(-1!==this.#Vo&&this.#qo.length>0)try{r=this.#ca()}catch(e){}this.#Vo=e,this.emit("trackChange",this.#Vo),t&&(async()=>{try{r&&await r.stop(),-1!==this.#Vo&&await this.play()}catch(e){this.log("error","Background transition error on index update:",e),console.warn("[TinyMediaPlayer] Background transition error on index update:",e)}})()}get loopMode(){return Qi(this.#u),this.#Ko}set loopMode(e){Qi(this.#u);const t=["NONE","TRACK","PLAYLIST"];if(!t.includes(e))throw new TypeError(`Loop mode must be one of: ${t.join(", ")}.`);this.#Ko=e,this.log("info",`Loop mode changed to: ${this.#Ko}`),this.emit("loopModeChange",this.#Ko)}get isRandom(){return Qi(this.#u),this.#Go}set isRandom(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("Random mode state must be a boolean.");this.#Go=e,this.log("info",`Random mode: ${this.#Go}`),this.emit("randomModeChange",this.#Go)}get isPlaying(){return Qi(this.#u),this.#Jo}get volume(){return Qi(this.#u),this.#Xo}set volume(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Volume must be a number.");if(e<0||e>1)throw new RangeError("Volume must be tightly constrained between 0.0 and 1.0.");if(this.#sa&&this.#sa.abort(),this.log("info",`Volume changed: ${this.#Xo} -> ${e}`),this.#Xo=e,this.#ha(),this.emit("volumeChange",this.#Xo),-1!==this.#Vo&&this.#qo.length>0)try{const e=this.#ca();e&&e.setVolume(this.#Xo)}catch(e){}}get persistVolume(){return Qi(this.#u),this.#Qo}set persistVolume(e){if(Qi(this.#u),"boolean"!=typeof e)throw new TypeError("Persist volume parameter must be a boolean.");this.#Qo=e,this.log("info",`Persist volume: ${this.#Qo}`),e&&this.#ha()}get volumeStorageKey(){return Qi(this.#u),this.#Zo}set volumeStorageKey(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Volume storage key must be a string.");if(""===e.trim())throw new TypeError("Volume storage key cannot be an empty string.");const t=this.#Zo;this.#Zo=e;try{this.#Qo&&"undefined"!=typeof window&&window.localStorage&&(window.localStorage.removeItem(t),this.#ha())}catch(e){console.warn("[TinyMediaPlayer] Failed to migrate volume storage key.",e)}}get isMuted(){return Qi(this.#u),this.#Yo}async mute(){Qi(this.#u);const e=this.#ca();e&&(await e.mute(),this.#Yo=!0,this.emit("muteChange",this.#Yo),this.log("info","Playback muted successfully."))}async unMute(){Qi(this.#u);const e=this.#ca();e&&(await e.unMute(),this.#Yo=!1,this.emit("muteChange",this.#Yo),this.log("info","Playback unmuted successfully."))}get adapters(){return Array.from(this.#Wo)}get adaptersSize(){return this.#Wo.size}static#da=["timeupdate","ended"];static get defaultAdapterEventNames(){return structuredClone(Zi.#da)}static set defaultAdapterEventNames(e){if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new TypeError("TinyMediaPlayer.defaultAdapterEventNames must be an array of strings.");Zi.#da=[...e]}#ma=new Set(Zi.defaultAdapterEventNames);#pa(e){const t=this.#Uo.get(e);t&&(this.#ma.forEach(r=>{const i=t.get(r);i&&e.off(r,i)}),t.clear(),this.#Uo.delete(e))}registerAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");this.log("info","Registering new adapter:",e);const t=new Map;this.#Uo.set(e,t),this.#ma.forEach(t=>{this.#fa(e,t)}),this.#Wo.add(e)}removeAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");return this.log("info","Removing adapter:",e),this.#pa(e),this.#Wo.delete(e)}destroyAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");this.log("info","Destroying adapter:",e),this.#pa(e);const t=this.#Wo.delete(e);return t&&e.destroy(),t}hasAdapter(e){if(Qi(this.#u),!(e instanceof Xi))throw new TypeError("Adapter must be an instance of BaseMediaAdapter.");return this.#Wo.has(e)}destroyAllAdapters(){Qi(this.#u),this.log("info","Destroying all adapters."),this.#Wo.forEach(e=>{this.#pa(e),e.destroy()}),this.#Wo.clear()}clearAdapters(){Qi(this.#u),this.log("info","Clearing all adapters."),this.#Wo.forEach(e=>this.#pa(e)),this.#Wo.clear()}getMediaAdapter(e){if(!E(e))throw new TypeError("Content must be a valid object.");for(const t of this.#Wo.values())if(t.canHandle(e))return t;return null}#ca(){if(-1===this.#Vo||0===this.#qo.length)return null;const e=this.#qo[this.#Vo],t=this.getMediaAdapter(e);if(t)return t;const r=`No compatible adapter found for content ID: ${e.id}.`;throw this.log("error",r),new Error(r)}addAdapterEvent(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");this.#ma.has(e)||(this.log("info",`Adding adapter event listener: ${e}`),this.#ma.add(e),this.#Wo.forEach(t=>{this.#fa(t,e)}))}removeAdapterEvent(e){if(Qi(this.#u),"string"!=typeof e)throw new TypeError("Event name must be a string.");this.#ma.has(e)&&(this.log("info",`Removing adapter event listener: ${e}`),this.#ma.delete(e),this.#Wo.forEach(t=>{this.#ya(t,e)}))}resetAdapterEvents(){Qi(this.#u);const e=Zi.defaultAdapterEventNames,t=Array.from(this.#ma);for(const r of t)e.includes(r)||this.removeAdapterEvent(r);for(const t of e)this.#ma.has(t)||this.addAdapterEvent(t)}#fa(e,t){const r=this.#Uo.get(e);if(!r)return;const i=(...e)=>{this.#u||("timeupdate"!==t&&this.log("debug",`Adapter event triggered: ${t}`,...e),this.emit(t,...e))};e.on(t,i),r.set(t,i)}#ya(e,t){const r=this.#Uo.get(e);if(!r)return;const i=r.get(t);i&&(e.off(t,i),r.delete(t))}addTrack(e){if(Qi(this.#u),!E(e)||"string"!=typeof e.url)throw new TypeError("Track content must be a valid MediaContent object containing a URL.");const t={id:"",title:"",artist:"",url:"",duration:0,weight:1,...e};sr(t);const r=this.#qo.push(t);return this.log("info",`Track added. New length: ${r}`,t),-1===this.#Vo&&(this.#Vo=0,this.emit("trackChange",this.#Vo)),this.emit("playlistUpdate",this.playlist),r}existsTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");return e>=0&&e<this.#qo.length}getTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);return this.#qo[e]}async removeTrack(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);this.log("info",`Removing track at index: ${e}`),e===this.#Vo?(await this.stop(),this.#qo.splice(e,1),0===this.#qo.length?this.#Vo=-1:this.#Vo>=this.#qo.length&&(this.#Vo=0),this.emit("trackChange",this.#Vo)):(this.#qo.splice(e,1),e<this.#Vo&&(this.#Vo-=1,this.emit("trackChange",this.#Vo))),this.emit("playlistUpdate",this.playlist)}searchTrack(e){if(Qi(this.#u),"string"!=typeof e&&"function"!=typeof e)throw new TypeError("Search query must be a string or a boolean evaluation function.");this.log("info","Searching playlist...",{query:e});const t=[];for(let r=0;r<this.#qo.length;r++){const i=this.#qo[r];let s=!1;if("function"==typeof e)s=Boolean(e(i));else{const t=e.toLowerCase(),r=i.title&&i.title.toLowerCase().includes(t),n=i.artist&&i.artist.toLowerCase().includes(t),o=i.album&&i.album.toLowerCase().includes(t);s=Boolean(r||n||o)}s&&t.push({track:i,index:r})}return this.log("info",`Search completed. Found ${t.length} results.`),t}async clearPlaylist(){Qi(this.#u),this.log("info","Clearing entire playlist."),await this.stop(),this.#qo=[],this.#Vo=-1,this.emit("playlistUpdate",this.playlist),this.emit("trackChange",this.#Vo)}async play(){Qi(this.#u),this.log("info",`Attempting to play track at index: ${this.#Vo}`);const e=this.#ca();if(e){this.#ra?await this.#ua(this.#Xo):e.setVolume(this.#Xo);try{await e.play(this.#qo[this.#Vo]),this.#Yo&&await e.mute(),this.#Jo=!0,this.log("info","Playback started successfully."),this.emit("play",this.#Vo)}catch(e){throw this.log("error","Failed to play track:",e),e}}else this.log("error","Failed to play track:",`Active adapter not found for track at index ${this.#Vo}.`)}async pause(){Qi(this.#u),this.log("info","Attempting to pause playback.");const e=this.#ca();e&&(this.#ra&&await this.#ua(0),await e.pause(),this.#Jo=!1,this.log("info","Playback paused."),this.emit("pause",this.#Vo))}async stop(){Qi(this.#u),this.log("info","Attempting to stop playback.");const e=this.#ca();e&&(this.#ia&&await this.#ua(0),await e.stop(),this.#Jo=!1,this.log("info","Playback stopped."),this.emit("stop",this.#Vo))}async next(){if(Qi(this.#u),0!==this.#qo.length){if(this.log("info","Next track requested."),await this.stop(),"TRACK"===this.#Ko)return this.log("info","Loop mode: TRACK. Repeating current track."),void await this.play();if(this.#Go)this.#Vo=this._getWeightedRandomIndex(),this.log("info",`Random mode: Selected index ${this.#Vo}`);else{let e=this.#Vo+1;if(e>=this.#qo.length){if("PLAYLIST"!==this.#Ko)return void this.log("info","End of playlist reached. Stopping.");e=0,this.log("info","Loop mode: PLAYLIST. Returning to start.")}this.#Vo=e}this.emit("trackChange",this.#Vo),await this.play()}}async prev(){if(Qi(this.#u),0!==this.#qo.length){if(this.#ea&&!this.#ta)return this.log("info",'UX: Repeat current track on first "prev" click.'),this.#ta=!0,this.#na&&clearTimeout(this.#na),this.#na=setTimeout(()=>{this.#ta=!1,this.#na=null},2e3),await this.stop(),void await this.play();if(this.#na&&(clearTimeout(this.#na),this.#na=null),this.#ta=!1,this.log("info","Previous track requested."),await this.stop(),this.#Go)this.#Vo=this._getWeightedRandomIndex(),this.log("info",`Random mode: Selected index ${this.#Vo}`);else{let e=this.#Vo-1;if(e<0){if("PLAYLIST"!==this.#Ko)return void this.log("info","Start of playlist reached. Stopping.");e=this.#qo.length-1,this.log("info","Loop mode: PLAYLIST. Returning to end.")}this.#Vo=e}this.emit("trackChange",this.#Vo),await this.play()}}async skipTo(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Index must be a number.");if(!this.existsTrack(e))throw new RangeError(`Index ${e} is out of bounds for the current playlist.`);this.log("info",`Skipping to index: ${e}`),await this.stop(),this.#Vo=e,this.emit("trackChange",this.#Vo),await this.play()}async seek(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Seek time must be a number in milliseconds.");if(e<0)throw new RangeError("Seek time cannot be negative.");this.log("info",`Seeking to: ${e}ms`);const t=this.#ca();t&&(await t.seek(e),this.emit("seek",e))}async step(e){if(Qi(this.#u),"number"!=typeof e)throw new TypeError("Step amount must be a number in milliseconds.");this.log("info",`Stepping by: ${e}ms`);const t=this.#ca();if(!t)return;let r=t.getCurrentTime()+e;r<0&&(r=0),await this.seek(r)}getCurrentTime(){Qi(this.#u);try{const e=this.#ca();return e?e.getCurrentTime():0}catch{return 0}}getTotalDuration(){Qi(this.#u);try{const e=this.#ca();return e?e.getTotalDuration():0}catch{return 0}}getRemainingTime(){Qi(this.#u);try{const e=this.#ca();return e?e.getRemainingTime():0}catch{return 0}}getPlaybackPercentage(){Qi(this.#u);try{const e=this.#ca();return e?e.getPlaybackPercentage():0}catch{return 0}}get isPaused(){Qi(this.#u);try{const e=this.#ca();return!!e&&e.isPaused()}catch{return!1}}get isEnded(){Qi(this.#u);try{const e=this.#ca();return!e||e.isEnded()}catch{return!0}}async getContentData(){Qi(this.#u);const e={id:"",createdAt:"",artistId:"",artistName:"",description:"",title:"",duration:0,avatar:"",url:""};try{const t=this.#ca();return t?t.getContentData():e}catch{return e}}async waitIsReady(){Qi(this.#u);const e=this.#ca();if(e)return e.waitIsReady()}async destroy(){if(!this.#u){this.log("info","Destroying TinyMediaPlayer instance.");try{this.#Jo&&await this.stop()}catch(e){this.log("error","Non-fatal error during playback termination:",e),console.warn("[TinyMediaPlayer] Non-fatal error during playback termination:",e)}this.#na&&clearTimeout(this.#na),this.#qo=[],this.#Vo=-1,this.#Jo=!1,this.#ta=!1,this.destroyAllAdapters(),this.removeAllListeners(),this.#ma.clear(),this.#u=!0,this.emit("destroyed")}}}const es=Zi,ts=class{#u=!1;get destroyed(){return this.#u}#vt;#ga=[];#wa=new WeakMap;#ba;constructor(e){if(!v(e))throw new TypeError('TinyUploadClicker: "options" must be a valid object.');this.#vt={multiple:!1,accept:"",inputAttributes:{},inputStyles:{display:"none"},onClick:null,onFileLoad:null,...e};const{triggers:t}=e;if(!(Array.isArray(t)||"string"==typeof t||t instanceof HTMLElement))throw new TypeError('TinyUploadClicker: "triggers" is required and must be a string, HTMLElement, or an array of them.');const r=(Array.isArray(this.#vt.triggers)?this.#vt.triggers:[this.#vt.triggers]).map(e=>{if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error(`TinyUploadClicker: No element found for selector "${e}".`);return t}if(!(e instanceof HTMLElement))throw new TypeError("TinyUploadClicker: All triggers must be either strings (selectors) or HTMLElements.");return e});if(void 0!==e.accept&&"string"!=typeof e.accept&&!Array.isArray(e.accept))throw new TypeError('TinyUploadClicker: "accept" must be a string or an array of strings.');if(void 0!==e.onClick&&"function"!=typeof e.onClick&&null!==e.onClick)throw new TypeError('TinyUploadClicker: "onClick" must be a function or null.');if(void 0!==e.onFileLoad&&"function"!=typeof e.onFileLoad&&null!==e.onFileLoad)throw new TypeError('TinyUploadClicker: "onFileLoad" must be a function or null.');if(void 0!==e.inputAttributes&&!v(e.inputAttributes))throw new TypeError('TinyUploadClicker: "inputAttributes" must be an object.');if(void 0!==e.inputStyles&&!v(e.inputStyles))throw new TypeError('TinyUploadClicker: "inputStyles" must be an object.');this.#ba=this.#va.bind(this),this.#ga=r,this.#ga.forEach(e=>{if(!(e instanceof HTMLElement))return;const t=document.createElement("input");t.type="file",this.#vt.multiple&&(t.multiple=!0),"string"==typeof this.#vt.accept?t.accept=this.#vt.accept:Array.isArray(this.#vt.accept)&&(t.accept=this.#vt.accept.join(","));const r=this.#vt.inputAttributes;if(r&&"object"==typeof r)for(const[e,i]of Object.entries(r))t.setAttribute(e,i);Object.assign(t.style,this.#vt.inputStyles||{display:"none"}),t.addEventListener("change",()=>{t.files&&"function"==typeof this.#vt.onFileLoad&&this.#vt.onFileLoad(t.files,e),t.value=""}),document.body.appendChild(t),this.#wa.set(e,t),e.addEventListener("click",this.#ba)})}#va(e){const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const r=this.#wa.get(t);r&&("function"==typeof this.#vt.onClick&&this.#vt.onClick(t),r.click())}destroy(){if(!this.destroyed){for(const e of this.#ga){if(!(e instanceof HTMLElement))return;e.removeEventListener("click",this.#ba);const t=this.#wa.get(e);t&&t.parentNode&&t.remove(),this.#wa.delete(e)}this.#ga=[],this.#u=!0}}};var rs=r(939);const is={header:"\n=== {projectName} ===\n",divider:"\n-----------------------------------------",itemValid:" [✔] {path}",itemInvalid:" [✘] {path}",itemMissing:" Missing: {errorPath}",itemSkipped:" [-] {path} (excluded by null target)",itemPattern:" [✔] {path} (pattern: {pattern})",itemInvalidTarget:" Invalid target: {target} ({reason})",successHeader:"SUCCESS: All exports are correctly mapped.",failureHeader:"FAILURE: {errorCount} export(s) are missing or invalid.",errorLoad:"Error: package.json not loaded in the current directory.",noExports:'[!] No "exports" field found in package.json.',errorNotFound:"Error: package.json not found in the current directory.",errorParse:"Error: Failed to parse package.json. Ensure it is valid JSON.",errorUnexpected:"An unexpected error occurred: {message}"},ss=Object.keys(is),ns=class{#Ea={RESET:"",GREEN:"",RED:"",YELLOW:"",CYAN:"",DIM:""};get COLORS(){return structuredClone(this.#Ea)}set COLORS(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("The provided configuration must be a non-null object.");const t=Object.keys(this.#Ea),r=Object.keys(e);if(t.length!==r.length||!t.every(e=>r.includes(e)))throw new TypeError("The new configuration must contain the exact same keys as the original color set.");const i=e;for(const e of t)if("string"!=typeof i[e])throw new TypeError(`The value for key "${e}" must be a string.`);this.#Ea=structuredClone(e)}#Ta={};#Sa;#xa;#Aa;#Ca=!1;#Ia;#ka;#Da;get packageData(){return structuredClone(this.#Ta)}get packageJsonPath(){return this.#Sa}get rootDir(){return this.#xa}get results(){return structuredClone(this.#Aa)}get started(){return this.#Ca}get projectName(){return this.#Ia}get silent(){return this.#ka}constructor(e,t,r={}){if("string"!=typeof e)throw new TypeError('The "packageJsonPath" argument must be a string.');if("string"!=typeof t)throw new TypeError('The "rootDir" argument must be a string.');this.#Ma(r),this.#Sa=e,this.#xa=t,this.#Aa=[],this.#Ia=r.projectName??"Tiny-Essentials Export Validation",this.#ka=!!r.silent,this.#Da={...is,...r.messages??{}}}#Ma(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError('The "options" argument must be a non-null object.');if(void 0!==e.projectName&&"string"!=typeof e.projectName)throw new TypeError('The "options.projectName" property must be a string.');if(void 0!==e.silent&&"boolean"!=typeof e.silent)throw new TypeError('The "options.silent" property must be a boolean.');if(void 0!==e.messages){if("object"!=typeof e.messages||null===e.messages||Array.isArray(e.messages))throw new TypeError('The "options.messages" property must be a non-null object.');const t=e.messages;for(const e of ss)if("string"!=typeof t[e])throw new TypeError(`The "options.messages.${e}" property must be a string.`)}}#La(e,t){if("string"!=typeof e)throw new TypeError("The template must be a string.");if("object"!=typeof t||null===t)throw new TypeError("The context must be a non-null object.");const r=t;return e.replace(/{(\w+)}/g,(e,t)=>{const i=r[t];return void 0!==i?String(i):e})}#Na(e,t,r={}){if(this.#ka)return;const i=["error","warning","success","info","dim","cyan"];if(!i.includes(e))throw new TypeError(`Invalid log type: "${e}". Valid types are: ${i.join(", ")}`);if("string"!=typeof t)throw new TypeError("The templateKey must be a string.");if("object"!=typeof r||null===r)throw new TypeError("The context must be a non-null object.");const s=this.#Da[t]??t,n=this.#La(s,{...r,projectName:this.#Ia});switch(e){case"error":console.error(`${this.#Ea.RED}${n}${this.#Ea.RESET}`);break;case"warning":console.log(`${this.#Ea.YELLOW}${n}${this.#Ea.RESET}`);break;case"success":console.log(`${this.#Ea.GREEN}${n}${this.#Ea.RESET}`);break;case"cyan":console.log(`${this.#Ea.CYAN}${n}${this.#Ea.RESET}`);break;case"dim":console.log(`${this.#Ea.DIM}${n}${this.#Ea.RESET}`);break;default:console.log(n)}}async execCommandTester(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError('The "actions" argument must be a non-null object.');if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))throw new TypeError('The "args" argument must be a string array.');const r=t[2],i=Object.keys(e);if(r)"function"==typeof e[r]?(this.#Na("cyan",`> Executing: ${r}`),await e[r]()):(this.#Na("error","errorUnexpected",{message:`Unknown argument: "${r}"`}),this.#Na("dim",`Valid arguments are: ${i.join(", ")}`));else{this.#Na("cyan","header"),this.#Na("dim","Running all registered commands...");for(const t of i)this.#Na("cyan",`> Executing: ${t}`),await e[t]()}}async start(){if(!this.#Ca){this.#Ca=!0;try{const e=await(0,rs.readFile)(this.#Sa,"utf-8"),t=JSON.parse(e);if("object"!=typeof t||null===t)throw this.#Ca=!1,new TypeError('The "packageData" argument must be a non-null object.');this.#Ta=t}catch(e){throw this.#Ca=!1,e}}}async validate(){if(!this.#Ca)return this.#Na("error","errorLoad"),!1;const e=this.#Ta.exports;if(null==e)return this.#Na("warning","noExports"),!0;this.#Aa=[];try{"object"!=typeof e||Array.isArray(e)||this.#_a(e),await this.#Ra(e,"exports",!0)}catch(e){throw e instanceof Error&&(e instanceof SyntaxError?this.#Na("error","errorParse"):"code"in e&&"ENOENT"===e.code?this.#Na("error","errorNotFound"):this.#Na("error","errorUnexpected",{message:e.message})),e}return this.#ja()}#_a(e){const t=Object.keys(e),r=t.filter(e=>e.startsWith(".")).length;if(0!==r&&r!==t.length)throw new TypeError('The "exports" field cannot mix subpath keys ("./x") with condition keys ("import").')}#Pa(e,t){return 0===e.length?"EMPTY_KEY":"."===e||e.startsWith("./")?t?null:"NESTED_SUBPATH_KEY":e.startsWith(".")?"INVALID_SUBPATH_KEY":e.includes(",")||e.includes("/")||e.includes("\\")?"INVALID_CONDITION":null}async#Ra(e,t,r=!1){if("string"!=typeof t)throw new TypeError('The "currentKey" argument must be a string.');if(null!==e)if("string"!=typeof e){if(!Array.isArray(e)){if("object"==typeof e){const i=e,s=Object.keys(i);if(0===s.length)return void this.#Aa.push({path:t,valid:!1,kind:"invalid",reason:"EMPTY_OBJECT"});for(const e of s){const s=this.#Pa(e,r);null===s?await this.#Ra(i[e],`${t} -> ${e}`):this.#Aa.push({path:`${t} -> ${e}`,valid:!1,kind:"invalid",errorPath:e,reason:s})}return}throw new TypeError('The "node" argument must be a string, an array, or a non-null object.')}if(0===e.length)return void this.#Aa.push({path:t,valid:!1,kind:"invalid",reason:"EMPTY_ARRAY"});for(let r=0;r<e.length;r+=1)await this.#Ra(e[r],`${t}[${r}]`)}else await this.#Oa(e,t);else this.#Aa.push({path:t,valid:!0,kind:"null"})}async#Oa(e,t){const r=this.#$a(e);null===r?e.includes("*")?await this.#Ha(e,t):await this.#Fa(e,t):this.#Aa.push({path:t,valid:!1,kind:"invalid",errorPath:e,reason:r})}#$a(e){if(0===e.length)return"EMPTY_TARGET";if(e.includes("\\"))return"INVALID_SEGMENT";if(e.includes("?")||e.includes("#"))return"INVALID_CHARACTER";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(e))return"URL_SCHEME_NOT_ALLOWED";if(!e.startsWith("./"))return"TARGET_NOT_RELATIVE";if(e.includes("**"))return"INVALID_PATTERN";const t=e.slice(2).split("/");for(const e of t){const t=this.#za(e).toLowerCase();if(0===t.length)return"INVALID_SEGMENT";if("."===t||".."===t||"node_modules"===t)return"INVALID_SEGMENT"}return null}#za(e){try{return decodeURIComponent(e)}catch{return e}}#Ba(e){const t=e.split("*").map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`)}async#Ha(e,r){const i=e.lastIndexOf("/"),s=0===i?".":e.slice(0,i),n=e.slice(i+1),o=s.includes("*")?s.slice(0,s.indexOf("*")).replace(/\/[^/]*$/,"")||".":s;let a;try{a=await(0,rs.readdir)((0,t().resolve)(this.#xa,o))}catch{return void this.#Aa.push({path:r,valid:!1,kind:"invalid",errorPath:e,reason:"DIRECTORY_NOT_FOUND"})}const l=this.#Ba(n),h=a.some(e=>l.test(e));this.#Aa.push({path:r,valid:h,kind:h?"pattern":"invalid",errorPath:e,reason:h?void 0:"PATTERN_NO_MATCH"})}async#Fa(e,r){if("string"!=typeof e)throw new TypeError('The "relativePath" argument must be a string.');if("string"!=typeof r)throw new TypeError('The "context" argument must be a string.');const i=(0,t().resolve)(this.#xa,e);try{if(!(await(0,rs.stat)(i)).isFile())return void this.#Aa.push({path:r,valid:!1,kind:"invalid",errorPath:e,reason:"NOT_A_FILE"});this.#Aa.push({path:r,valid:!0,kind:"file"})}catch{this.#Aa.push({path:r,valid:!1,kind:"invalid",errorPath:e,reason:"FILE_NOT_FOUND"})}}#ja(){this.#Na("cyan","header");let e=0;for(const t of this.#Aa)"null"!==t.kind?t.valid?this.#Na("success","pattern"===t.kind?"itemPattern":"itemValid",{path:t.path,pattern:t.errorPath??""}):(this.#Na("error","itemInvalid",{path:t.path}),"FILE_NOT_FOUND"===t.reason?this.#Na("dim","itemMissing",{errorPath:t.errorPath}):this.#Na("dim","itemInvalidTarget",{target:t.errorPath??t.path,reason:t.reason??"UNKNOWN"}),e++):this.#Na("dim","itemSkipped",{path:t.path});return this.#Na("cyan","divider"),0===e?(this.#Na("success","successHeader"),!0):(this.#Na("error","failureHeader",{errorCount:e}),!1)}},os=(e,t,r)=>{if(null===e||"string"!=typeof e&&!(e instanceof RegExp))throw new TypeError("The searchValue must be a string or a RegExp.");if("function"!=typeof t)throw new TypeError("The replaceValue must be a function.");if("object"!=typeof r||null===r)throw new TypeError("The errorConfig must be an object.");if("string"!=typeof r.pathPatternErrorMsg)throw new TypeError("The errorConfig.pathPatternErrorMsg property must be a string.");return i=>{if("string"!=typeof i)throw new TypeError(r.pathPatternErrorMsg);let s=!1;const n=[],o=i.replace(e,(e,...r)=>t(n,e,...r)),a=new RegExp(`^${o}$`);return{regex:a,paramNames:n,exec:e=>{const t={},r=e.match(a);return s=!0,r?(n.forEach((e,i)=>{t[e]=decodeURIComponent(r[i+1])}),{params:t,match:!0}):{params:t,match:!1}}}}},as=os(/:([^/]+)/g,(e,t,r)=>(e.push(r),"([^/]+)"),{pathPatternErrorMsg:'The argument must be a string (e.g., "/user/:id")'}),ls=le("TinyRouter"),{q:hs,N:us}=o,cs=class extends Gi{static SegmentExtractor=a;#Wa=[];#Ua;#qa;#Ca=!1;#Va;#Ka;#Kn=[];#Ga;#Ja=-1;#i=new ae;#hr=!1;constructor(e={}){if("object"!=typeof e||null===e)throw new TypeError("Options must be a non-null object.");if(void 0!==e.detectHistoryChange&&"boolean"!=typeof e.detectHistoryChange)throw new TypeError("detectHistoryChange must be a boolean.");if(void 0!==e.onRouteChanged&&"function"!=typeof e.onRouteChanged)throw new TypeError("onRouteChanged must be a function.");if(void 0!==e.onRouteNotFound&&"function"!=typeof e.onRouteNotFound)throw new TypeError("onRouteNotFound must be a function.");if(void 0!==e.historyLimit&&(!Number.isInteger(e.historyLimit)||e.historyLimit<-1))throw new TypeError("historyLimit must be an integer and greater than or equal to -1.");super({id:"[_main_class_TinyRouter_reset_]",logger:e.logger??console,debugMode:e.debugMode??!1,useLogColors:e.useLogColors??!1}),this.#Ua=e.onRouteChanged||(()=>{}),this.#qa=e.onRouteNotFound||(()=>{}),this.#Ka=e.detectHistoryChange??!0,this.#Ja=-1,this.#Ga=e.historyLimit??0,this.#Va=this.#Ya.bind(this)}get isDestroyed(){return this.#hr}get historyIndex(){return ls(this.#hr),this.#Ja}get historyLimit(){return ls(this.#hr),this.#Ga}get detectHistoryChange(){return ls(this.#hr),this.#Ka}set detectHistoryChange(e){if(ls(this.#hr),"boolean"!=typeof e)throw new TypeError("detectHistoryChange must be a boolean.");this.#Ka=e}get onRouteChanged(){return ls(this.#hr),this.#Ua}set onRouteChanged(e){if(ls(this.#hr),"function"!=typeof e)throw new TypeError("onRouteChanged must be a function.");this.#Ua=e}get onRouteNotFound(){return ls(this.#hr),this.#qa}set onRouteNotFound(e){if(ls(this.#hr),"function"!=typeof e)throw new TypeError("onRouteNotFound must be a function.");this.#qa=e}get started(){return ls(this.#hr),this.#Ca}get size(){return ls(this.#hr),this.#Wa.length}get routes(){return ls(this.#hr),this.#Wa.map(e=>e.segmentExtractor.pattern??"")}get history(){return ls(this.#hr),this.#Kn.map(e=>({...e}))}set history(e){if(ls(this.#hr),!Array.isArray(e))throw new TypeError("History data must be an array.");for(const t of e){if("object"!=typeof t||null===t)throw new TypeError("Each history entry must be an object.");if("string"!=typeof t.path)throw new TypeError('Each history entry must have a string "path" property.');if("number"!=typeof t.timestamp)throw new TypeError('Each history entry must have a number "timestamp" property.')}this.#Kn=e.map(e=>({...e})),this.log("info","History has been successfully imported.")}add(e,t){ls(this.#hr);let r={};if("string"==typeof e)r=us(e),r.pattern=e;else{if("object"!=typeof e||null===e)throw new TypeError('The first argument must be a string (e.g., "/user/:id") or an object of SegmentExtractor maker.');if("function"==typeof e.callback){const t=e;t.callback(t.pattern)}else{const t=e;r=hs(t.searchValue,t.replaceValue,t.errorConfig)(t.pattern)}r.pattern=e.pattern}if("function"!=typeof t)throw new TypeError("The callback must be a function.");if(this.has(r.pattern))throw new Error(`Route with pattern "${r.pattern}" is already registered.`);this.#Wa.push({segmentExtractor:r,callback:t}),this.emit("RouteAdded",r.pattern),this.log("info",`New route registered: ${r.pattern}`)}remove(e){if(ls(this.#hr),"string"!=typeof e)throw new TypeError("pathPattern must be a string.");const t=this.#Wa.length;this.#Wa=this.#Wa.filter(t=>t.segmentExtractor.pattern!==e),this.#Wa.length===t?this.log("warn",`Attempted to remove non-existent route: ${e}`):(this.emit("RouteRemoved",e),this.log("info",`Route removed: ${e}`))}has(e){if(ls(this.#hr),"string"!=typeof e)throw new TypeError("pathPattern must be a string.");return this.#Wa.some(t=>t.segmentExtractor.pattern===e)}async navigate(e,t={}){ls(this.#hr),window.location.pathname+window.location.search!==e&&(window.history.pushState(t,"",e),await this.#i.enqueue(()=>this.#Ya()),this.log("info",`Navigated to: ${e}`))}start(){return this.#Ca?new Promise((e,t)=>t(new Error("Router has already been started."))):(this.#Va=()=>{const e=window.location.pathname;if(0!==this.#Ga){const t=this.#Kn.findIndex(t=>t.path===e);-1!==t&&(this.#Ja=t)}return this.#Ya()},window.addEventListener("popstate",this.#Va),this.#Ca=!0,this.#i.enqueue(()=>new Promise((e,t)=>{let r;try{ls(this.#hr)}catch(e){r=e}if(r)return t(r);this.#Ya().then(()=>{this.emit("RouterStarted"),this.log("info","Router started successfully."),e()}).catch(t)})))}stop(){ls(this.#hr),window.removeEventListener("popstate",this.#Va),this.#Ca=!1,this.clearAll(),this.emit("RouterStopped"),this.log("info","Router stopped and event listeners removed.")}async go(e){if(ls(this.#hr),!this.#Ca)return this.log("warn","Attempted to navigate while the router is stopped."),!1;if(!Number.isInteger(e))throw new TypeError('The "delta" parameter must be an integer.');if(0!==this.#Ga){const t=this.#Ja+e;if(t>=0&&t<this.#Kn.length){const e=this.#Kn[t].path;return window.history.pushState(null,"",e),await this.#i.enqueue(()=>this.#Ya()),!0}return!1}if(!this.#Ka)return window.history.go(e),this.log("info",`Navigation command: go(${e}) (detection disabled)`),!0;const t=window.location.pathname+window.location.search;return this.#i.enqueue(()=>new Promise(r=>{const i=()=>{window.removeEventListener("popstate",i);const e=window.location.pathname+window.location.search;r(t!==e)};window.addEventListener("popstate",i),setTimeout(()=>{window.removeEventListener("popstate",i);const e=window.location.pathname+window.location.search;r(t!==e)},100),window.history.go(e),this.log("info",`Navigation command: go(${e})`)}))}async back(){return this.go(-1)}async forward(){return this.go(1)}#Xa(e){ls(this.#hr),0!==this.#Ga&&(this.#Ja>=0&&this.#Kn[this.#Ja].path===e||(this.#Ja>=0&&(this.#Kn=this.#Kn.slice(0,this.#Ja+1)),this.#Kn.push({path:e,timestamp:Date.now()}),this.#Ja++,this.#Ga>0&&this.#Kn.length>this.#Ga&&(this.#Kn.shift(),this.#Ja--),this.emit("HistoryRecorded",{...this.#Kn[this.#Ja]})))}async#Ya(){ls(this.#hr);const e=window.location.pathname,t=window.location.search,r=new URLSearchParams(t);for(const t of this.#Wa){const{params:i,match:s}=t.segmentExtractor.exec(e);if(s){const s={path:e,params:i,query:r};return this.#Xa(e),this.emit("BeforeRouteChanged",s),await t.callback(s),this.#Ua(s),this.emit("AfterRouteChanged",s),void this.log("info",`Route matched: ${e}`)}}const i={path:e,query:r};this.#qa(i),this.emit("RouteNotFound",i),this.log("warn",`No route matched the current URL: ${e}`)}removeHistoryEntry(e){if(ls(this.#hr),!Number.isInteger(e))throw new TypeError("The index must be an integer.");if(e<0||e>=this.#Kn.length)throw new RangeError("The provided index is out of bounds.");this.#Kn.splice(e,1),this.emit("HistoryEntryRemoved",e),this.log("info",`History entry at index ${e} was removed.`)}clearHistory(){ls(this.#hr),this.#Kn=[],this.emit("HistoryCleared"),this.log("info","Navigation history has been cleared.")}clear(){ls(this.#hr),this.#Wa=[],this.emit("RoutesCleared"),this.log("info","All routes have been cleared.")}clearAll(){ls(this.#hr),this.clear(),this.clearHistory()}destroy(){this.#hr||(this.stop(),this.#hr=!0)}},ds=e().EventEmitter;class ms extends ds{static#Qa=new Set;static get activeInstances(){return Array.from(ms.#Qa)}static get activeInstancesSize(){return ms.#Qa.size}constructor(){super()}#Za=new Map;#el=3e5;get ttl(){return this.#el}set ttl(e){if("number"!=typeof e)throw new TypeError("The TTL value must be a number.");if(e<0)throw new RangeError("The TTL value cannot be negative.");this.#el=e}get size(){return this.#Za.size}has(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");return this.purgeExpired(!0),this.#Za.has(e)}delete(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0);const t=this.#Za.delete(e);if(t){const t={key:e};this.emit("delete",t)}return t}set(e,t){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0),ms.#Qa.has(this)||ms.#Qa.add(this),this.#Za.set(e,{data:t,timestamp:Date.now()});const r={key:e,data:t};this.emit("set",r)}get(e){if("string"!=typeof e)throw new TypeError("The cache key must be a string.");this.purgeExpired(!0);const t=this.#Za.get(e);return t?t.data:null}get[Symbol.toStringTag](){return"TinyMapCache"}keys(){return this.purgeExpired(!0),this.#tl().map(([e])=>e).values()}values(){return this.purgeExpired(!0),this.#tl().map(([,e])=>e).values()}entries(){return this.purgeExpired(!0),this.#tl().values()}[Symbol.iterator](){return this.entries()}forEach(e,t){if("function"!=typeof e)throw new TypeError("The callback must be a function.");this.purgeExpired(!0);for(const[r,i]of this.#tl())e.call(t,i,r,this)}#tl(){const e=[];for(const[t,r]of this.#Za.entries())e.push([t,r.data]);return e}purgeExpired(e=!1){const t=Date.now();let r=0;for(const[e,i]of this.#Za.entries())if(t-i.timestamp>this.#el){this.#Za.delete(e),r++;const t={key:e,data:i.data};this.emit("expire",t)}if(r>0){const e={count:r};this.emit("purge",e)}this.#Za.size<1&&ms.#Qa.delete(this),e&&ms.#Qa.forEach(e=>{e!==this&&e.purgeExpired(!1)})}clear(){ms.#Qa.delete(this),this.#Za.clear(),this.emit("clear")}}const ps=ms;class fs{#rl=0;#il=0;#sl=0;#nl=null;constructor(e){if("string"!=typeof e)throw new TypeError("[TinyVersion] Expected version to be a string, received type: "+typeof e);const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/),r=e=>{"string"==typeof e[1]&&(this.#rl=parseInt(e[1],10)),"string"==typeof e[2]&&(this.#il=parseInt(e[2],10)),"string"==typeof e[3]&&(this.#sl=parseInt(e[3],10)),"string"==typeof e[4]&&(this.#nl=e[4])};if(t)r(t);else{const t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(t)r(t);else{const t=e.match(/^(\d+)\.(\d+)$/);if(t)r(t);else{const t=e.match(/^(\d+)$/);if(!t)throw new Error(`[TinyVersion] Invalid version format: "${e}". Expected format: "X.Y.Z" or "X.Y.Z-tag".`);r(t)}}}}get major(){return this.#rl}get minor(){return this.#il}get patch(){return this.#sl}get tag(){return this.#nl}isGreaterThan(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return this.#rl!==e.major?this.#rl>e.major:this.#il!==e.minor?this.#il>e.minor:this.#sl!==e.patch?this.#sl>e.patch:null===this.#nl&&null!==e.tag||(null===this.#nl||null!==e.tag)&&(null!==this.#nl||null!==e.tag)&&(this.#nl??"")>(e.tag??"")}isEqualTo(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return this.#rl===e.major&&this.#il===e.minor&&this.#sl===e.patch&&this.#nl===e.tag}isLessThan(e){if(!(e instanceof fs))throw new TypeError("[TinyVersion] Comparison target must be an instance of TinyVersion. Received: "+typeof e);return!this.isGreaterThan(e)&&!this.isEqualTo(e)}toString(){const e=`${this.#rl}.${this.#il}.${this.#sl}`;return this.#nl?`${e}-${this.#nl}`:e}}const ys=fs,gs=le("TinyPlugin"),ws=(e,t)=>t instanceof Set?t.has("*")||t.has(e):t.indexOf("*")>-1||t.indexOf(e)>-1;async function bs(e,t,r,i,s,n={name:"RSASSA-PKCS1-v1_5"}){if("string"!=typeof e||0===e.length)throw new TypeError("pluginId must be a non-empty string.");if(!Array.isArray(t)||t.some(e=>"string"!=typeof e))throw new TypeError("authors must be an array of strings.");if(!Array.isArray(r)||r.some(e=>"string"!=typeof e))throw new TypeError("categories must be an array of strings.");if(!Array.isArray(i)||i.some(e=>"string"!=typeof e))throw new TypeError("tags must be an array of strings.");if(!(s instanceof CryptoKey))throw new TypeError("privateKey must be a valid CryptoKey instance.");const o={id:e,authors:[...t].sort(),categories:[...r].sort(),tags:[...i].sort()},a=JSON.stringify(o),l=(new TextEncoder).encode(a);try{return await crypto.subtle.sign(n,s,l)}catch(e){throw new Error(`Failed to sign plugin identity: ${e instanceof Error?e.message:"Unknown error"}`)}}const vs=(e,t,r,i)=>{if("string"!=typeof e)throw new TypeError("Security Error: Cryptographic mode enabled, but pluginId is missing.");if(!Array.isArray(t))throw new TypeError("Security Error: Cryptographic mode enabled, but authors is missing.");if(!t.every(e=>"string"==typeof e))throw new TypeError("Security Error: Cryptographic mode enabled, but authors is invalid.");return JSON.stringify({id:e,authors:[...t].sort(),categories:[...r].sort(),tags:[...i].sort()})},Es=(e,t,r)=>{const i=(e,t)=>{if(!Array.isArray(t)||!t.every(e=>"string"==typeof e||"symbol"==typeof e))throw new TypeError(`The ${e} of sandbox blacklist must be an array of strings.`)};if(v(r)&&v(e?.sandboxBlacklist)){const{get:t,set:s}=e.sandboxBlacklist;void 0!==t&&(i("get",t),t.forEach(e=>r.get.add(e))),void 0!==s&&(i("set",s),s.forEach(e=>r.set.add(e)))}if(v(e?.accessControl)){const{mode:r,whitelist:s,blacklist:n,publicKey:o,cryptoAlgorithm:a,importAlgorithm:l,importKeyFormat:h}=e.accessControl;if("none"!==r&&"whitelist"!==r&&"blacklist"!==r&&"cryptographic"!==r)throw new TypeError('accessControl.mode must be "none", "whitelist", "blacklist", or "cryptographic".');if("cryptographic"===r&&"string"!=typeof o)throw new TypeError("In cryptographic mode, accessControl.publicKey must be a string (PEM format).");v(s)&&(void 0!==s.ids&&(i("whitelist ids",s.ids),s.ids.forEach(e=>t.whitelist.ids.add(e))),void 0!==s.authors&&(i("whistlist authors",s.authors),s.authors.forEach(e=>t.whitelist.authors.add(e))),void 0!==s.categories&&(i("whistlist categories",s.categories),s.categories.forEach(e=>t.whitelist.categories.add(e))),void 0!==s.tags&&(i("whistlist tags",s.tags),s.tags.forEach(e=>t.whitelist.tags.add(e)))),v(n)&&(void 0!==n.ids&&(i("blacklist ids",n.ids),n.ids.forEach(e=>t.blacklist.ids.add(e))),void 0!==n.authors&&(i("blacklist authors",n.authors),n.authors.forEach(e=>t.blacklist.authors.add(e))),void 0!==n.categories&&(i("blacklist categories",n.categories),n.categories.forEach(e=>t.blacklist.categories.add(e))),void 0!==n.tags&&(i("blacklist tags",n.tags),n.tags.forEach(e=>t.blacklist.tags.add(e)))),"string"==typeof r&&(t.mode=r),"string"==typeof o&&(t.publicKey=o),void 0!==a&&(t.cryptoAlgorithm=a),void 0!==l&&(t.importAlgorithm=l),void 0!==h&&(t.importKeyFormat=h)}},Ts=e=>{const t=globalThis.atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r.buffer},Ss=async(e,t,r,i,s,n,o)=>{const{publicKey:a,cryptoAlgorithm:l,importKeyFormat:h,importAlgorithm:u}=e,c=vs(r,i,s,n);try{if("string"!=typeof a)throw new TypeError("Security Error: Cryptographic mode enabled, but public key is missing.");if(!("string"==typeof o||o instanceof ArrayBuffer||o instanceof Uint8Array))throw new TypeError("Security Error: Cryptographic mode enabled, but signature is invalid (must be string, ArrayBuffer, or Uint8Array).");const e=(new TextEncoder).encode(c);let i;i="spki"===h||"pkcs8"===h?(e=>{const t=e.replace(/(-----(BEGIN|END) [^-]+-----)/g,"").replace(/\s+/g,"");return Ts(t)})(a):"string"==typeof a?Ts(a):a;const s="string"==typeof o?Ts(o):o,n=await crypto.subtle.importKey(h,i,u,!1,["verify"]),d=await crypto.subtle.verify(l,n,s,e);return d&&t.add(r),d}catch(e){return console.error(e),!1}},xs=(e,t,r,i,s,n,o,a)=>{if("cryptographic"===e)return a.has(t);if("whitelist"===e){const e=ws(t,n.ids),o=r.some(e=>ws(e,n.authors)),a=i.some(e=>ws(e,n.categories)),l=s.some(e=>ws(e,n.tags));return e||o||a||l}if("blacklist"===e){const e=ws(t,o.ids),n=r.some(e=>ws(e,o.authors)),a=i.some(e=>ws(e,o.categories)),l=s.some(e=>ws(e,o.tags));return!(e||n||a||l)}return!0},As=()=>({mode:"none",importKeyFormat:"spki",importAlgorithm:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},cryptoAlgorithm:{name:"RSASSA-PKCS1-v1_5"},publicKey:null,whitelist:{ids:new Set,authors:new Set,categories:new Set,tags:new Set},blacklist:{ids:new Set,authors:new Set,categories:new Set,tags:new Set}}),Cs=(e,t,r,i,s,n,o)=>{const a=[...i],l=[...s],h=t??{get:[],set:[]},u=[...n??[],...h.get],c=[...u,...h.set,...o??[]];return v(r)&&(u.forEach(e=>r.get.add(e)),c.forEach(e=>r.set.add(e))),new Proxy(e,{get(e,t){if(l.includes(t)||l.includes("*")){const r=Reflect.get(e,t,e);return"function"==typeof r?r.bind(e):r}throw new Error(`Security Error: Access to property "${String(t)}" is denied by the sandbox.`)},set(e,t,r){if(a.includes(t)||a.includes("*"))return Reflect.set(e,t,r);throw new Error("Security Error: Cannot modify read-only properties on the plugin sandbox.")},setPrototypeOf(){throw new Error("Security Error: Prototype manipulation is forbidden.")}})};class Is extends Gi{#ol=!1;#al=new Set;#ll=As();get isReady(){return this.#ol}get accessControlWhitelist(){return Object.freeze({ids:Object.freeze([...this.#ll.whitelist.ids]),authors:Object.freeze([...this.#ll.whitelist.authors]),categories:Object.freeze([...this.#ll.whitelist.categories]),tags:Object.freeze([...this.#ll.whitelist.tags])})}get accessControlBlacklist(){return Object.freeze({ids:Object.freeze([...this.#ll.blacklist.ids]),authors:Object.freeze([...this.#ll.blacklist.authors]),categories:Object.freeze([...this.#ll.blacklist.categories]),tags:Object.freeze([...this.#ll.blacklist.tags])})}get accessControlMode(){return this.#ll.mode}constructor(e){super(e?.logCfg??{id:"[_main_class_TinyPluginLayer_reset_]",logger:console,autoHideId:!0,debugMode:!1,useLogColors:!1}),Es(e??{},this.#ll)}_startLayer(e,t,...r){if(this.#ol)throw new Error("TinyPluginLayer: The layer has already been initialized.");return this.logSubId=e.logSubId,"function"==typeof t&&t(...r),this.#ol=!0,this}canAccessLayer(e,t,r,i){const{mode:s,whitelist:n,blacklist:o}=this.#ll;return xs(s,e,t,r,i,n,o,this.#al)}async verifyPluginSignature(e,t,r,i,s){return Ss(this.#ll,this.#al,e,t,r,i,s)}_createSandbox(e,t){return Cs(this,null,null,[...e],["isReady","accessControlMode","accessControlWhitelist","accessControlBlacklist","verifyPluginSignature","canAccessLayer",...t])}}class ks extends Gi{static#hl=Is;static get TinyPluginLayer(){return ks.#hl}static#ul="pluginsDestroyed";#cl={get:new Set,set:new Set};#ll=As();#al=new Set;static get pluginsDestroyEventName(){return ks.pluginsDestroyEventName}static set pluginsDestroyEventName(e){if("string"!=typeof e)throw new TypeError("pluginsDestroyEventName must be a string.");ks.pluginsDestroyEventName=e}#dl=new Map;get sandboxBlacklist(){return Object.freeze({set:Object.freeze([...this.#cl.set]),get:Object.freeze([...this.#cl.get])})}get plugins(){return Object.fromEntries(this.#dl)}get pluginsSize(){return this.#dl.size}get accessControlWhitelist(){return Object.freeze({ids:Object.freeze([...this.#ll.whitelist.ids]),authors:Object.freeze([...this.#ll.whitelist.authors]),categories:Object.freeze([...this.#ll.whitelist.categories]),tags:Object.freeze([...this.#ll.whitelist.tags])})}get accessControlBlacklist(){return Object.freeze({ids:Object.freeze([...this.#ll.blacklist.ids]),authors:Object.freeze([...this.#ll.blacklist.authors]),categories:Object.freeze([...this.#ll.blacklist.categories]),tags:Object.freeze([...this.#ll.blacklist.tags])})}get accessControlMode(){return this.#ll.mode}constructor(e){super(e.logCfg),Es(e,this.#ll,this.#cl)}canAccessEngine(e,t,r,i){const{mode:s,whitelist:n,blacklist:o}=this.#ll;return xs(s,e,t,r,i,n,o,this.#al)}async verifyPluginSignature(e,t,r,i,s){return Ss(this.#ll,this.#al,e,t,r,i,s)}_addPlugin(e){if(!(e instanceof Ds))throw new TypeError("The provided plugin must be an instance of TinyPlugin.");if(!this.canAccessEngine(e.id,e.authors,e.categories,e.tags))throw new Error(`Security Error: Access to the core is denied for plugin "${e.id}" based on current access control rules.`);this.#dl.set(e.id,e)}installPlugin(e,...t){return Ds._addModuleToCore(this,e,...t)}hasPlugin(e){return this.#dl.has("string"==typeof e?e:e.id)}getPlugin(e){const t=this.#dl.get(e);return t&&!t.isDestroyed?t:void 0}_getPlugin(e,t){if(!(t instanceof Ds))throw new TypeError("The provided external plugin must be an instance of TinyPlugin.");const r=this.#dl.get(e);if(r&&!r.isDestroyed){if(!r.layer.canAccessLayer(t.id,t.authors,t.categories,t.tags))throw new Error(`Security Error: Access to the plugin "${e}" is denied for plugin "${t.id}" based on current plugin access control rules.`);return r}}destroyPlugins(){this.#al.clear(),this.#dl.forEach(e=>e.destroy()),this.emit(ks.#ul)}}class Ds extends Gi{static#ml={id:"[_main_class_TinyPlugin_reset_]",autoHideId:!0,logger:console,debugMode:!1,canEmitLogs:!1,useLogColors:!0};static get logCfg(){return{...Ds.#ml}}static set logCfg(e){this.#ml=e}static _addModuleToCore(e,t,...r){if(!(e instanceof ks))throw new TypeError("The provided engine must be an instance of TinyPluginCore.");const i=new Ds({engine:e,installer:t,logCfg:{...Ds.#ml,debugMode:e.debugMode}},...r);if(i._startPlugin(),e.hasPlugin(i))throw new Error(`A plugin with the name "${i.id}" is already registered.`);return e._addPlugin(i),i}#cl={get:new Set,set:new Set};#pl="";#fl="";#yl=new Set;#gl=new Set;#wl=new Set;#bl=new Set;#ee=null;#vl;#El;#wn;#ol=!1;#Tl=null;#hr=!1;#Sl=new Set;#xl=new Set;get isDestroyed(){return this.#hr}get plugins(){return gs(this.#hr),Object.keys(this.#vl.plugins)}get pluginsSize(){return gs(this.#hr),this.#vl.pluginsSize}getPlugin(e){return gs(this.#hr),this.#vl._getPlugin(e,this)}hasPlugin(e){return gs(this.#hr),this.#vl.hasPlugin(e)}get isReady(){return gs(this.#hr),this.#ol}get id(){if(gs(this.#hr),0===this.#pl.length)throw new Error("Plugin id is not set.");return this.#pl}set id(e){if(gs(this.#hr),0!==this.#pl.length)throw new Error("Id is already set.");if("string"!=typeof e)throw new TypeError("Id must be a string.");if(0===e.length)throw new TypeError("Id cannot be empty.");this.#pl=e,this.logSubId=`${this.#vl.logId} [_sub_class_${e}_reset_]`}get description(){if(gs(this.#hr),0===this.#fl.length)throw new Error("Plugin description is not set.");return this.#fl}set description(e){if(gs(this.#hr),0!==this.#fl.length)throw new Error("Description is already set.");if("string"!=typeof e)throw new TypeError("Description must be a string.");if(0===e.length)throw new TypeError("Description cannot be empty.");this.#fl=e}get authors(){if(gs(this.#hr),0===this.#yl.size)throw new Error("Plugin authors is not set.");return Object.freeze([...this.#yl])}set authors(e){if(gs(this.#hr),0!==this.#yl.size)throw new Error("Authors is already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Authors must be a array of non-empty strings.");if(0===e.length)throw new TypeError("Authors cannot be empty.");e.forEach(e=>this.#yl.add(e))}get contributors(){if(gs(this.#hr),0===this.#gl.size)throw new Error("Plugin contributors is not set.");return Object.freeze([...this.#gl])}set contributors(e){if(gs(this.#hr),0!==this.#gl.size)throw new Error("Authors is already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Authors must be a array of non-empty strings.");if(0===e.length)throw new TypeError("Authors cannot be empty.");e.forEach(e=>this.#gl.add(e))}get categories(){if(gs(this.#hr),0===this.#wl.size)throw new Error("Plugin categories are not set.");return Object.freeze([...this.#wl])}set categories(e){if(gs(this.#hr),0!==this.#wl.size)throw new Error("Categories are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Categories must be an array of non-empty strings.");if(0===e.length)throw new TypeError("Categories cannot be empty.");e.forEach(e=>this.#wl.add(e))}get tags(){if(gs(this.#hr),0===this.#bl.size)throw new Error("Plugin tags are not set.");return Object.freeze([...this.#bl])}set tags(e){if(gs(this.#hr),0!==this.#bl.size)throw new Error("Tags are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("Tags must be an array of non-empty strings.");if(0===e.length)throw new TypeError("Tags cannot be empty.");e.forEach(e=>this.#bl.add(e))}get allowedSets(){return gs(this.#hr),[...this.#xl]}set allowedSets(e){if(gs(this.#hr),0!==this.#xl.size||this.#ol)throw new Error("AllowedSets are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("AllowedSets must be an array of non-empty strings.");if(0===e.length)throw new TypeError("AllowedSets cannot be empty.");e.forEach(e=>this.#xl.add(e))}get allowedGets(){return gs(this.#hr),[...this.#Sl]}set allowedGets(e){if(gs(this.#hr),0!==this.#Sl.size||this.#ol)throw new Error("AllowedGets are already set.");if(!Array.isArray(e)||!e.every(e=>"string"==typeof e&&0!==e.trim().length))throw new TypeError("AllowedGets must be an array of non-empty strings.");if(0===e.length)throw new TypeError("AllowedGets cannot be empty.");e.forEach(e=>this.#Sl.add(e))}get version(){if(gs(this.#hr),!this.#ee)throw new Error("Plugin version is not set.");return this.#ee.toString()}set version(e){if(gs(this.#hr),this.#ee)throw new Error("Version is already set.");if("string"!=typeof e)throw new TypeError("Version must be a string.");if(0===e.length)throw new TypeError("Version cannot be empty.");this.#ee=new ys(e)}get tinyVersion(){if(gs(this.#hr),!this.#ee)throw new Error("Plugin version is not set.");return this.#ee}get layer(){if(gs(this.#hr),null===this.#Tl)throw new Error("Plugin layer is not set.");return this.#Tl._createSandbox([...this.#xl],[...this.#Sl])}get engine(){if(gs(this.#hr),!this.#vl.canAccessEngine(this.#pl,[...this.#yl],[...this.#wl],[...this.#bl]))throw new Error(`Security Error: Access to the engine is denied for plugin "${this.id}" based on current access control rules.`);const e=this.#cl;return new Proxy(this.#vl,{get(t,r){if(e.get.has(r))throw new Error(`Security Error: Access to property "${String(r)}" is denied by the sandbox.`);const i=Reflect.get(t,r,t);return"function"==typeof i?i.bind(t):i},set(t,r,i){if(e.set.has(r))throw new Error("Security Error: Cannot modify read-only properties on the plugin sandbox.");return Reflect.set(t,r,i)},setPrototypeOf(){throw new Error("Security Error: Prototype manipulation is forbidden.")}})}get options(){return gs(this.#hr),this.#wn}get engineBlacklist(){return gs(this.#hr),this.#vl.sandboxBlacklist}constructor({engine:e,logCfg:t,installer:r},...i){super(t),this.#vl=e,this.#El=r,this.#wn=i}#Al(){const e=["id","version","description","authors","contributors","categories","tags","allowedGets","allowedSets"];return Cs(this,this.#vl.sandboxBlacklist,this.#cl,e,[...e,"tinyVersion","isReady","layer","options","engine","engineBlacklist","isDestroyed","pluginsSize","plugins","hasPlugin","getPlugin","log","logClear","logGroupEnd","logLabel","logTimeLabel","logAssert","logDir","logTable","toConsole","isDestroyed"],["getPlugin","_getPlugin","plugins","installPlugin","_addPlugin","destroyPlugins"],["accessControlMode","accessControlWhitelist","accessControlBlacklist","verifyPluginSignature","canAccessEngine"])}_startPlugin(){if(gs(this.#hr),this.#ol)throw new Error("Plugin is already ready.");this.#wn&&Object.freeze(this.#wn);const e=this.#Al();try{if(this.#Tl=this.#El(e,...this.#wn),!(this.#Tl instanceof Is))throw new TypeError("Plugin layer is not a valid TinyPluginLayer instance.");if(this.#Tl.debugMode=this.debugMode,this.#Tl.isReady||this.#Tl._startLayer(this),0===this.#pl.length)throw new Error("Plugin id is not set.");if(0===this.#fl.length)throw new Error("Plugin description is not set.");if(0===this.#yl.size)throw new Error("Plugin authors are not set.");if(0===this.#gl.size)throw new Error("Plugin contributors are not set.");if(0===this.#wl.size)throw new Error("Plugin categories are not set.");if(0===this.#bl.size)throw new Error("Plugin tags are not set.");if(!this.#ee)throw new Error("Plugin version is not set.");this.#ol=!0}catch(e){throw this.emit("error",e),this.destroy(),new Error(`Plugin initialization failed: ${e instanceof Error?e.message:"Unknown Error"}`)}}destroy(){this.#hr||(this.emit("destroyed"),this.#Tl?.emit("destroyed"),this.#hr=!0)}}const Ms=Object.freeze({NOTIFICATION:"notification",DATA:"data",SYNC:"sync",COMMAND:"command",UNKNOWN:"unknown"});class Ls{static PUSH_TYPE=Ms;static#Cl=Object.freeze(["actions","badge"]);static toBrowser(e,t={}){if(null!==e&&("object"!=typeof e||Array.isArray(e)))throw new TypeError("[TinyNotificationAdapter] toBrowser: notification must be a non-null object.");if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("[TinyNotificationAdapter] toBrowser: overrides must be a non-null object.");const{title:r,...i}=e??{},s={};for(const[e,t]of Object.entries(i))Ls.#Cl.includes(e)||void 0!==t&&(s[e]=t);return"auto"!==s.dir&&"ltr"!==s.dir&&"rtl"!==s.dir&&delete s.dir,!0===s.renotify&&"string"!=typeof s.tag&&delete s.renotify,{title:"string"==typeof r&&""!==r?r:"Notification",options:{...s,...t}}}static toServiceWorker(e,t={}){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("[TinyNotificationAdapter] toServiceWorker: notification must be a non-null object.");if("object"!=typeof t||null===t||Array.isArray(t))throw new TypeError("[TinyNotificationAdapter] toServiceWorker: overrides must be a non-null object.");const{title:r="Notification",options:i={}}=e,s={...i,...t};return{title:r,body:"string"==typeof s.body?s.body:"",options:s}}}const Ns=Ls,_s=async()=>{if(!("Notification"in window))throw new Error("Notification API is not supported in this browser.");return"granted"===Notification.permission?"granted":"denied"===Notification.permission?"denied":await Notification.requestPermission()},Rs=le("TinyServiceWorker"),js=(e,t)=>{if(!("serviceWorker"in navigator)||!navigator.serviceWorker.controller)throw new Error("Service Worker is not available or not controlling the page.");return navigator.serviceWorker.controller.postMessage(e,t??[])};class Ps extends ks{static postMessage=js;static#Il=Ms;static get PUSH_TYPE(){return Ps.#Il}static#kl(e){if("string"!=typeof e||""===e.trim())throw new TypeError("The event type must be a non-empty string.");if(e.startsWith("sw:"))throw new TypeError(`The event type "${e}" is reserved for internal PWA lifecycle management and cannot be used for Service Worker messaging.`)}static#Dl(e){if("string"!=typeof e||""===e.trim())throw new TypeError("The event name must be a non-empty string.")}static async waitForReady(){return navigator.serviceWorker.ready}#Ml=null;#pl;#Ll;#ee;#ol=!1;#Nl=!1;#_l=null;#Rl=null;#jl="browser";#Pl=new Map;#Ol=new Map;#$l=null;#Hl=null;#Fl=null;#zl=new(e().EventEmitter);#hr=!1;#Bl=new Set;get pushEvents(){return this.#zl}get isReady(){return this.#ol}get isFailed(){return this.#Nl}get isDestroyed(){return this.#hr}#Wl(){this.emit("sw:NoSwControllerWarn"),this.log("warn","No active controller to receive message.")}get isSwAvailable(){return Rs(this.#hr),"serviceWorker"in navigator&&!!navigator.serviceWorker.controller}get id(){return Rs(this.#hr),this.#pl}get swUrl(){return Rs(this.#hr),this.#Ll}get version(){return Rs(this.#hr),this.#ee}get registration(){return Rs(this.#hr),this.#Ml}#Ul=new Set;get eventListeners(){return Rs(this.#hr),Array.from(this.#Ul)}get displayMode(){return Rs(this.#hr),this.#jl}#ql=!0;get autoNotifyPush(){return Rs(this.#hr),this.#ql}set autoNotifyPush(e){if(Rs(this.#hr),"boolean"!=typeof e)throw new TypeError("autoNotifyPush must be a boolean.");this.#ql=e}get eventBlacklist(){return Rs(this.#hr),Array.from(this.#Bl)}addToEventBlacklist(e){Rs(this.#hr),Ps.#Dl(e),this.#Bl.add(e)}removeFromEventBlacklist(e){return Rs(this.#hr),Ps.#Dl(e),this.#Bl.delete(e)}hasInEventBlacklist(e){return Rs(this.#hr),Ps.#Dl(e),this.#Bl.has(e)}clearEventBlacklist(){Rs(this.#hr),this.#Bl.clear()}constructor(e){if(Array.isArray(e)||"object"!=typeof e||null===e)throw new TypeError('The "options" argument must be a non-null object.');const{id:t,swUrl:r,version:i,logger:s,debugMode:n,useLogColors:o}=e;if("string"!=typeof t||""===t.trim())throw new TypeError('The "id" parameter must be a non-empty string.');if("string"!=typeof r&&!(r instanceof URL))throw new TypeError('The "swUrl" parameter must be a string or URL.');if("string"!=typeof i)throw new TypeError('The "version" parameter must be a string.');super({logCfg:{id:"[_sub_class_TinyServiceWorker_reset_]",logger:s??console,debugMode:n??!1,useLogColors:o??!1}}),this.#pl=t,this.#Ll=r,this.#ee=i,this.#Vl()}#Vl(){const e=window.matchMedia("(display-mode: standalone)").matches;document.referrer.startsWith("android-app://")?this.#jl="twa":navigator.standalone||e?this.#jl="standalone":this.#jl="browser",this.emit("sw:DisplayModeChanged",{displayMode:this.#jl}),this.log("info",`DISPLAY_MODE_CHANGED: ${this.#jl}`)}#Kl(){this.#$l=()=>this.#Vl(),window.matchMedia("(display-mode: standalone)").addEventListener("change",this.#$l),this.#Hl=e=>{this.#Rl=e,this.emit("sw:BeforeInstallPrompt",{event:e}),this.log("info","beforeinstallprompt event fired.")},window.addEventListener("beforeinstallprompt",this.#Hl),this.#Fl=()=>{this.#Rl=null,this.emit("sw:AppInstalled"),this.log("info","PWA was installed")},window.addEventListener("appinstalled",this.#Fl)}async promptInstallation(){if(Rs(this.#hr),!this.#Rl)throw new Error("Cannot show installation prompt: beforeinstallprompt event has not fired.");this.#Rl.prompt();const{outcome:e}=await this.#Rl.userChoice;this.log("info",`User installation choice: ${e}`),this.#Rl=null}async waitForReady(){if(Rs(this.#hr),this.#Nl)throw new Error("Service Worker registration failed. Cannot wait for ready state.");if(!this.#ol||!navigator.serviceWorker.controller)return new Promise((e,t)=>{const r=()=>{this.#ol&&navigator.serviceWorker.controller&&(s(),e())},i=e=>{s(),t(e instanceof Error?e:new Error(String(e)))},s=()=>{navigator.serviceWorker.removeEventListener("controllerchange",r),this.off("sw:RegistrationFailed",i)};navigator.serviceWorker.addEventListener("controllerchange",r),this.on("sw:RegistrationFailed",i),this.#ol&&navigator.serviceWorker.controller&&(s(),e())})}async registerSync(e){if(Rs(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError("[TinyServiceWorker] registerSync: tag must be a non-empty string.");const t=await Ps.waitForReady();if(!t.sync)throw new Error("[TinyServiceWorker] registerSync: Background Sync API is not supported in this browser.");try{await t.sync.register(e),this.log("info",`Sync tag registered: ${e}`)}catch(t){throw this.log("error",`Failed to register sync tag "${e}":`,t),t}}async requestNotificationPermission(){Rs(this.#hr);try{const e=await _s();return"granted"===e?(this.emit("sw:NotificationPermissionChanged",{permission:"granted"}),e):"denied"===e?(this.log("warn","Notification permission was denied by the user."),this.emit("sw:NotificationPermissionChanged",{permission:"denied"}),e):(this.log("info",`Notification permission status: ${e}`),this.emit("sw:NotificationPermissionChanged",{permission:e}),e)}catch(e){throw this.log("error","Error requesting notification permission:",e),e}}#Gl(e,t){const r=!0===e.notificationShown,i=e.notification??null,s=(e={})=>{if(!("Notification"in window))return this.log("warn","Push received, but the Notification API is not supported."),null;const t=Ns.toBrowser(i,e),r=new Notification(t.title,t.options),s=e=>{const r=Ns.toServiceWorker(t);this.#Jl(e,r,!1)};return r.onclick=()=>s("sw:NotificationClicked"),r.onclose=()=>s("sw:NotificationClosed"),r};!r&&"browser"===this.displayMode&&this.#ql&&s(),this.#zl.emit(e.topic??"push",{data:{...e,notificationShown:r},event:t,notificationShown:r,showNotification:s})}async register(e){if(Rs(this.#hr),void 0!==e&&(Array.isArray(e)||"object"!=typeof e||null===e))throw new TypeError('The "options" argument must be a non-null object.');if("serviceWorker"in navigator)try{const t=`${this.#pl}_sw_version`,r=localStorage.getItem(t);r!==this.#ee&&(this.log("warn",`Version mismatch detected: ${r} -> ${this.#ee}. Signaling update...`),this.emit("sw:VersionUpdateAvailable"),this.#Jl("sw:PrepareUpdate"),localStorage.setItem(t,this.#ee));const i=new URL(this.#Ll,location.origin);i.searchParams.set("v",this.#ee),this.debugMode&&i.searchParams.set("t",Date.now().toString()),this.#Ml=await navigator.serviceWorker.register(i.toString(),e),navigator.serviceWorker.addEventListener("controllerchange",e=>{this.emit("sw:NewVersionReady",{event:e}),this.log("info","New Service Worker is now in control.")}),this.#_l=e=>{const t=e.data;if(!Array.isArray(t)&&"object"==typeof t&&null!==t&&"string"==typeof t.type)if(this.#Bl.has(t.type))this.log("warn",`Ignored blacklisted event: ${t.type}`);else if(void 0===t.data||!Array.isArray(t.data)&&"object"==typeof t.data&&null!==t.data)if("sw:PushReceived"!==t.type){if("sw:ApiResponse"===t.type){if("string"!=typeof t.correlationId)return void this.log("error",'Received message with missing or invalid "correlationId" string.');const e=this.#Pl.get(t.correlationId);return void(e&&(clearTimeout(e.timer),this.#Pl.delete(t.correlationId),t.error?e.reject(new Error(t.error)):e.resolve(t.data)))}if(!0===t.isApi){if("string"!=typeof t.correlationId)return void this.log("error",'Received message with missing or invalid "correlationId" string.');const e=this.#Ol.get(t.type);if(!e)return void js({correlationId:t.correlationId,type:"sw:ApiResponse",error:`No API handler registered for type: ${t.type}`});try{const r=e=>js({correlationId:t.correlationId,type:"sw:ApiResponse",data:e}),i=e({data:t.data,correlationId:t.correlationId});i instanceof Promise?i.then(r):r(i)}catch(e){js({correlationId:t.correlationId,type:"sw:ApiResponse",error:e instanceof Error?e.message:String(e)})}return}this.emit(t.type,{data:t.data,event:e})}else this.#Gl(t.data,e)},navigator.serviceWorker.addEventListener("message",this.#_l),this.#Kl(),this.#ol=!0,this.log("info","Registered successfully.")}catch(e){this.#Nl=!0,this.log("error","Registration error:",e)}else this.log("warn","Service Worker is not supported in this browser.")}async unregister(){if(Rs(this.#hr),!this.#Ml)return this.log("warn","No active ServiceWorkerRegistration found to unregister."),this.destroy(),!1;try{const e=await this.#Ml.unregister();return e?this.log("info","Service Worker unregistered successfully."):this.log("warn","The unregister() method returned false (the worker might already be inactive)."),this.destroy(),e}catch(e){throw this.log("error","Error during Service Worker unregistration:",e),e}}#Jl(e,t,r=!1){if(Rs(this.#hr),"string"!=typeof e)throw new TypeError("Payload.type must be a string.");if("boolean"!=typeof r)throw new TypeError('The "strictMode" argument must be a boolean.');if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError("Payload.data must be a non-null object.");return r&&Ps.#kl(e),"serviceWorker"in navigator&&navigator.serviceWorker.controller?(navigator.serviceWorker.controller.postMessage({type:e,data:t}),!0):(this.#Wl(),!1)}offApi(e){if("string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');return this.#Ol.delete(e)}onApi(e,t){if("string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');if("function"!=typeof t)throw new TypeError("Callback must be a function.");this.#Ol.set(e,t)}async emitApi(e,t,r=1e4){if(Rs(this.#hr),"string"!=typeof e||""===e.trim())throw new TypeError('The "type" argument must be a non-empty string.');if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError('The "data" argument must be a non-null object.');if("number"!=typeof r)throw new TypeError('The "timeout" argument must be a number.');if(!Number.isFinite(r)||r<0)throw new RangeError('The "timeout" argument must be a finite number greater than or equal to 0.');const i=crypto.randomUUID();return new Promise((s,n)=>{const o=setTimeout(()=>{this.#Pl.has(i)&&(this.#Pl.delete(i),n(new Error(`API request timeout: ${e} (ID: ${i})`)))},r);this.#Pl.set(i,{resolve:s,reject:n,timer:o}),js({type:e,data:t,correlationId:i,isApi:!0})})}emitMessage(e,t){return this.#Jl(e,t,!0)}postMessage(e){if(Rs(this.#hr),Array.isArray(e)||"object"!=typeof e||null===e)throw new TypeError("Payload must be an object.");if("string"!=typeof e.type)throw new TypeError("Payload.type must be a string.");if(void 0!==e.data&&(Array.isArray(e.data)||"object"!=typeof e.data||null===e.data))throw new TypeError("Payload.data must be a non-null object.");Ps.#kl(e.type),"serviceWorker"in navigator&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(e):this.#Wl()}addEventListener(e){if(Rs(this.#hr),"function"!=typeof e)throw new TypeError("The callback must be a function.");"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",e),this.#Ul.add(e)):this.#Wl()}removeEventListener(e){if(Rs(this.#hr),"function"!=typeof e)throw new TypeError("The callback must be a function.");return"serviceWorker"in navigator?(navigator.serviceWorker.removeEventListener("message",e),this.#Ul.delete(e)):(this.#Wl(),!1)}destroy(){if(!this.#hr){if("serviceWorker"in navigator){this.#_l&&(navigator.serviceWorker.removeEventListener("message",this.#_l),this.#_l=null);for(const e of this.#Ul)navigator.serviceWorker.removeEventListener("message",e);this.#Ul.clear()}this.#$l&&(window.matchMedia("(display-mode: standalone)").removeEventListener("change",this.#$l),this.#$l=null),this.#Hl&&(window.removeEventListener("beforeinstallprompt",this.#Hl),this.#Hl=null),this.#Fl&&(window.removeEventListener("appinstalled",this.#Fl),this.#Fl=null),this.removeAllListeners(),this.#zl.removeAllListeners(),this.#Ml=null,this.#Rl=null,this.destroyPlugins(),this.#hr=!0,this.log("info",`[${this.#pl}] Destroyed successfully.`)}}}const Os=Ps,$s=R(),Hs=j();class Fs{#Yl=!1;get isolationMode(){return this.#Yl}static#Xl=!0;static get defaultIsDeep(){return Fs.#Xl}static set defaultIsDeep(e){if("boolean"!=typeof e)throw new TypeError("The defaultIsDeep property must be a boolean.");Fs.#Xl=e}constructor(e={isolationMode:!1}){if("object"!=typeof e||null===e)throw new TypeError("Options must be a non-null object.");if(void 0!==e.isolationMode&&"boolean"!=typeof e.isolationMode)throw new TypeError('The property "isolationMode" must be a boolean.');this.#Yl=!!e.isolationMode,this.#Yl&&(this.#dl=Fs.#Ql.map(e=>({...e})))}static _createObjectPlugin(e){if("string"!=typeof e)throw new TypeError("Id must be a string.");return{id:e,canHandle:e=>null!==e&&"object"==typeof e,clone:(e,t,r)=>{const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t?r.clone(e[s],t):e[s]);return i}}}static#Ql=[];static validatePlugin(e){if("function"!=typeof e?.canHandle||"function"!=typeof e?.clone)throw new TypeError("Each plugin must implement the required interface: canHandle(item) and clone(item, cloner).");if("string"!=typeof e?.id)throw new TypeError("Each plugin must implement the required interface: the plugin id string.")}static get plugins(){return Fs.#Ql.map(e=>({...e}))}static get size(){return Fs.#Ql.length}static get ids(){return Fs.#Ql.map(e=>e.id)}static set plugins(e){if(!Array.isArray(e))throw new TypeError("The defaultPlugins property must be an array.");Fs.#Ql=e.map(e=>(Fs.validatePlugin(e),{...e}))}static addPlugin(e,t="start",r=0){if(Fs.validatePlugin(e),Fs.hasPlugin(e.id))throw new TypeError(`A plugin with the ID "${e.id}" already exists in the global registry.`);const i={...e};if("start"===t)Fs.#Ql.unshift(i);else if("end"===t)Fs.#Ql.push(i);else{if("index"!==t)throw new TypeError('Position must be "start", "end", or "index".');if(!Number.isInteger(r)||r<0)throw new TypeError('When position is "index", the index must be a non-negative integer.');Fs.#Ql.splice(r,0,i)}}static hasPlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");return Fs.#Ql.some(t=>t.id===e)}static removePlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");const t=Fs.#Ql.findIndex(t=>t.id===e);return-1!==t&&(Fs.#Ql.splice(t,1),!0)}static filterPlugins(e){if("function"!=typeof e)throw new TypeError("Predicate must be a function.");Fs.#Ql=Fs.#Ql.filter(t=>!e({...t}))}static updatePlugin(e,t){if(e<0||e>=Fs.#Ql.length)throw new RangeError("Index out of bounds.");Fs.validatePlugin(t),Fs.#Ql[e]={...t}}static reorderPlugins(e){Fs.#Ql=Fs.#Ql.sort(e?(t,r)=>e({...t},{...r}):void 0)}#dl=[];get size(){return this.#dl.length}get ids(){return this.#dl.map(e=>e.id)}get plugins(){return this.#dl.map(e=>({...e}))}set plugins(e){if(!Array.isArray(e))throw new TypeError("The plugins property must be an array.");this.#dl=e.map(e=>(Fs.validatePlugin(e),{...e}))}addPlugin(e,t="start",r=0){if(Fs.validatePlugin(e),this.hasPlugin(e.id))throw new TypeError(`A plugin with the ID "${e.id}" already exists in this instance.`);const i={...e};if("start"===t)this.#dl.unshift(i);else if("end"===t)this.#dl.push(i);else{if("index"!==t)throw new TypeError('Position must be "start", "end", or "index".');if(!Number.isInteger(r)||r<0)throw new TypeError('When position is "index", the index must be a non-negative integer.');this.#dl.splice(r,0,i)}}hasPlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");return this.#dl.some(t=>t.id===e)}removePlugin(e){if("string"!=typeof e)throw new TypeError("The ID must be a string.");const t=this.#dl.findIndex(t=>t.id===e);return-1!==t&&(this.#dl.splice(t,1),!0)}filterPlugins(e){if("function"!=typeof e)throw new TypeError("Predicate must be a function.");this.#dl=this.#dl.filter(t=>!e({...t}))}updatePlugin(e,t){if(e<0||e>=this.#dl.length)throw new RangeError("Index out of bounds.");Fs.validatePlugin(t),this.#dl[e]={...t}}reorderPlugins(e){this.#dl=this.#dl.sort(e?(t,r)=>e({...t},{...r}):void 0)}static clone(e,t=Fs.#Xl){for(const r of Fs.#Ql)if(r.canHandle(e))return r.clone(e,t,Fs);return e}clone(e,t=Fs.#Xl){for(const r of this.#dl)if(r.canHandle(e))return r.clone(e,t,this);if(!this.#Yl)for(const r of Fs.#Ql)if(r.canHandle(e))return r.clone(e,t,this);return e}}Fs.plugins=Hs.filter(e=>$s[e]).map(e=>({id:e,canHandle:$s[e].validator,clone:$s[e].cloner}));const zs=Fs,Bs={100:{name:"Continue",summary:"",description:""},101:{name:"Switching Protocols",summary:"",description:""},102:{name:"Processing",summary:"",description:""},103:{name:"Early Hints",summary:"",description:""},200:{name:"OK",summary:"",description:""},201:{name:"Created",summary:"",description:""},202:{name:"Accepted",summary:"",description:""},203:{name:"Non-Authoritative Information",summary:"",description:""},204:{name:"No Content",summary:"",description:""},205:{name:"Reset Content",summary:"",description:""},206:{name:"Partial Content",summary:"",description:""},207:{name:"Multi-Status",summary:"",description:""},208:{name:"Already Reported",summary:"",description:""},226:{name:"IM Used",summary:"",description:""},300:{name:"Multiple Choices",summary:"",description:""},301:{name:"Moved Permanently",summary:"",description:""},302:{name:"Found",summary:"",description:""},303:{name:"See Other",summary:"",description:""},304:{name:"Not Modified",summary:"",description:""},305:{name:"Use Proxy",summary:"",description:""},306:{name:"Unused",summary:"",description:""},307:{name:"Temporary Redirect",summary:"",description:""},308:{name:"Permanent Redirect",summary:"",description:""},400:{name:"Bad Request",summary:"",description:""},401:{name:"Unauthorized",summary:"",description:""},402:{name:"Payment Required",summary:"",description:""},403:{name:"Forbidden",summary:"",description:""},404:{name:"Not Found",summary:"",description:""},405:{name:"Method Not Allowed",summary:"",description:""},406:{name:"Not Acceptable",summary:"",description:""},407:{name:"Proxy Authentication Required",summary:"",description:""},408:{name:"Request Timeout",summary:"",description:""},409:{name:"Conflict",summary:"",description:""},410:{name:"Gone",summary:"",description:""},411:{name:"Length Required",summary:"",description:""},412:{name:"Precondition Failed",summary:"",description:""},413:{name:"Content Too Large",summary:"",description:""},414:{name:"URI Too Long",summary:"",description:""},415:{name:"Unsupported Media Type",summary:"",description:""},416:{name:"Range Not Satisfiable",summary:"",description:""},417:{name:"Expectation Failed",summary:"",description:""},418:{name:"I'm a teapot",summary:"",description:""},421:{name:"Misdirected Request",summary:"",description:""},422:{name:"Unprocessable Content",summary:"",description:""},423:{name:"Locked",summary:"",description:""},424:{name:"Failed Dependency",summary:"",description:""},425:{name:"Too Early",summary:"",description:""},426:{name:"Upgrade Required",summary:"",description:""},428:{name:"Precondition Required",summary:"",description:""},429:{name:"Too Many Requests",summary:"",description:""},431:{name:"Request Header Fields Too Large",summary:"",description:""},451:{name:"Unavailable For Legal Reasons",summary:"",description:""},500:{name:"Internal Server Error",summary:"",description:""},501:{name:"Not Implemented",summary:"",description:""},502:{name:"Bad Gateway",summary:"",description:""},503:{name:"Service Unavailable",summary:"",description:""},504:{name:"Gateway Timeout",summary:"",description:""},505:{name:"HTTP Version Not Supported",summary:"",description:""},506:{name:"Variant Also Negotiates",summary:"",description:""},507:{name:"Insufficient Storage",summary:"",description:""},508:{name:"Loop Detected",summary:"",description:""},510:{name:"Not Extended",summary:"",description:""},511:{name:"Network Authentication Required",summary:"",description:""}};class Ws{static#Zl=Bs;static codeIs=Object.freeze({info:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=100&&e<=199},success:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=200&&e<=299},redirect:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=300&&e<=399},clientError:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=400&&e<=499},serverError:e=>{if("number"!=typeof e||Number.isNaN(e))throw new TypeError("The status code must be a valid number.");return e>=500&&e<=599}});static get defaultRequestCodes(){return structuredClone(Ws.#Zl)}static set defaultRequestCodes(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("The value must be a non-null object.");for(const[t,r]of Object.entries(e)){if(Number.isNaN(Number(t)))throw new TypeError(`Invalid key: "${t}". Status code keys must be numeric.`);if("object"!=typeof r||null===r||Array.isArray(r))throw new TypeError(`The value for status code ${t} must be an object.`);if("string"!=typeof r.name)throw new TypeError(`Property 'name' in status ${t} must be a string.`);if("string"!=typeof r.summary)throw new TypeError(`Property 'summary' in status ${t} must be a string.`);if("string"!=typeof r.description)throw new TypeError(`Property 'description' in status ${t} must be a string.`)}Ws.#Zl=structuredClone(e)}#eh=new Set;#th;#rh="en";constructor(e,t={}){if(!v(t))throw new TypeError("Initial responses must be an object.");if(this.#th=new e({defaultLocale:"en",mode:"local",strict:!1,acceptNullResults:!0}),!(this.#th instanceof ui))throw new TypeError('The "i18" must be an instance of TinyI18.');this.#th.loadLocaleLocal(this.#rh,{});for(const e in Ws.#Zl){const t=Ws.#Zl[e];this.addResponse(Number(e),t)}for(const e in t){const r=t[e];this.addResponse(Number(e),r)}}#ih(e,t){if("object"!=typeof t||null===t)throw new TypeError("Response must be a non-null object.");if("string"!=typeof t.name)throw new TypeError('The "name" property must be a string.');if("string"!=typeof t.summary)throw new TypeError('The "summary" property must be a string.');if("string"!=typeof t.description)throw new TypeError('The "description" property must be a string.');if(this.#th.get(String(e)))throw new Error(`Response with ID ${e} already exists in the registry.`)}addResponse(e,t,r=this.#rh){this.#ih(e,t),this.#eh.add(e),this.#th.loadLocaleLocal(r,{[e]:{name:t.name,summary:t.summary,description:t.description}})}get(e,t={},r=this.#rh){const i=this.#th.get(`${e}.name`,t,{locale:r}),s=this.#th.get(`${e}.summary`,t,{locale:r}),n=this.#th.get(`${e}.description`,t,{locale:r});return"string"!=typeof i||"string"!=typeof s||"string"!=typeof n?null:{name:i,summary:s,description:n}}has(e){return!!this.#th.get(String(e))}getAll(){const e={};return this.#eh.forEach(t=>{const r=this.get(t);r&&(e[t]=r)}),e}}const Us=Ws,qs=class extends Us{constructor(e){super(di,e)}},Vs="(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";function Ks(){return new RegExp(`^${Vs}\\.${Vs}\\.${Vs}\\.${Vs}$`)}function Gs(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(t??Ks()).test(e)}function Js(){return new RegExp(`\\b${Vs}(?:\\.${Vs}){3}\\b`,"g")}function Ys(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(t??Js())??[]}const Xs="[0-9a-fA-F]{1,4}",Qs=`((${Xs}:){7}${Xs}|(${Xs}:){1,7}:|(${Xs}:){1,6}:${Xs}|(${Xs}:){1,5}(:${Xs}){1,2}|(${Xs}:){1,4}(:${Xs}){1,3}|(${Xs}:){1,3}(:${Xs}){1,4}|(${Xs}:){1,2}(:${Xs}){1,5}|${Xs}:((:${Xs}){1,6})|:((:${Xs}){1,7}|:))`;function Zs(){return new RegExp(`^${Qs}$`)}function en(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(t??Zs()).test(e)}function tn(){return new RegExp(`\\b${Qs}\\b`,"g")}function rn(e,t){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(t??tn())??[]}const sn=(e={})=>{(e=>{if(void 0!==e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be an object.");if(void 0!==e.protocol&&"string"!=typeof e.protocol)throw new TypeError('The "protocol" property must be a string.');if(void 0!==e.subDomain&&"string"!=typeof e.subDomain)throw new TypeError('The "subDomain" property must be a string.');if(void 0!==e.subDomainOptional&&"boolean"!=typeof e.subDomainOptional)throw new TypeError('The "subDomainOptional" property must be a boolean.');if(void 0!==e.nameMaxLength&&(!Array.isArray(e.nameMaxLength)||2!==e.nameMaxLength.length||"number"!=typeof e.nameMaxLength[0]||"number"!=typeof e.nameMaxLength[1]))throw new TypeError('The "nameMaxLength" property must be an array of two numbers.');if(void 0!==e.topLevelDomainLength&&(!Array.isArray(e.topLevelDomainLength)||2!==e.topLevelDomainLength.length||"number"!=typeof e.topLevelDomainLength[0]||"number"!=typeof e.topLevelDomainLength[1]))throw new TypeError('The "topLevelDomainLength" property must be an array of two numbers.')}})(e);const{protocol:t="https?",subDomain:r="",subDomainOptional:i=!0,nameMaxLength:s=[1,256],topLevelDomainLength:n=[1,6]}=e;return`${t}:\\/\\/${r?`(${r}\\.)${i?"?":""}`:""}[-a-zA-Z0-9@:%._\\+~#=]{${String(s[0])},${String(s[1])}}\\.[a-zA-Z0-9()]{${String(n[0])},${String(n[1])}}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)`};function nn(e){return new RegExp(`^${sn(e)}$`)}function on(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(r??nn(t)).test(e)}function an(e){return new RegExp(`\\b${sn(e)}\\b`,"g")}function ln(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(r??an(t))??[]}const hn=(e={})=>{(e=>{if(void 0===e)return;if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be an object.");const t=(e,t)=>{if(void 0!==e){if(!Array.isArray(e))throw new TypeError(`${t} must be an array.`);for(let r=0;r<e.length;r++)if("string"!=typeof e[r])throw new TypeError(`All elements in ${t} must be strings.`)}};if(t(e.blacklistDomains,"blacklistDomains"),t(e.whitelistDomains,"whitelistDomains"),t(e.blacklistUsernames,"blacklistUsernames"),t(e.whitelistUsernames,"whitelistUsernames"),void 0!==e.customValidator&&"function"!=typeof e.customValidator)throw new TypeError("customValidator must be a function.")})(e);const{validName:t="[a-zA-Z0-9._%+-]+",validDomain:r="[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"}=e;return`${t}@${r}`};function un(e){return new RegExp(`^${hn(e)}$`)}function cn(e,t={}){if("function"==typeof t.customValidator&&!t.customValidator(e))return!1;const[r,i]=e.split("@");return!(Array.isArray(t.whitelistDomains)&&t.whitelistDomains.length>0&&!t.whitelistDomains.includes(i)||Array.isArray(t.whitelistUsernames)&&t.whitelistUsernames.length>0&&!t.whitelistUsernames.includes(r)||Array.isArray(t.blacklistDomains)&&t.blacklistDomains.length>0&&t.blacklistDomains.includes(i)||Array.isArray(t.blacklistUsernames)&&t.blacklistUsernames.length>0&&t.blacklistUsernames.includes(r))}function dn(e,t={},r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return!!(r??un(t)).test(e)&&cn(e,t)}function mn(e){return new RegExp(`\\b${hn(e)}\\b`,"g")}function pn(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return e.match(r??mn(t))?.filter(e=>cn(e,t))??[]}const fn=e=>String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yn=(e,t)=>{if(null!=t&&"function"!=typeof t&&"lowercase"!==t&&"uppercase"!==t)throw new TypeError('The "transform" property must be a function, "lowercase", or "uppercase".');return"function"==typeof t?t(e):"lowercase"===t?e.toLowerCase():"uppercase"===t?e.toUpperCase():e},gn=({validValues:e="[a-zA-Z0-9_]",length:t=[3,20]}={})=>{if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "validValues" property must be a string.');if(void 0!==t){if(!Array.isArray(t)||"number"!=typeof t[0]||"number"!=typeof t[1])throw new TypeError('The "length" property must be an array of two numbers.');if(t[0]>t[1])throw new RangeError("The minimum length (length[0]) cannot be greater than the maximum length (length[1]).");if(t[0]<0)throw new RangeError("The length cannot be negative.")}return`(?:${e}){${String(t[0])},${String(t[1])}}`};function wn(e){return`${function({prefix:e,start:t}={}){if(void 0!==t&&"string"!=typeof t)throw new TypeError('The "start" property must be a string.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "prefix" property must be a string.');return`${t??""}${e?fn(e):""}`}(e)}${gn(e)}${function({domain:e,domainPattern:t,end:r}={}){if(void 0!==r&&"string"!=typeof r)throw new TypeError('The "end" property must be a string.');if(void 0!==e&&"string"!=typeof e)throw new TypeError('The "domain" property must be a string.');if(void 0!==t&&"string"!=typeof t)throw new TypeError('The "domainPattern" property must be a string.');return t?`(?:${t})${r??""}`:e?`(?:${fn(e)})${r??""}`:r??""}(e)}`}const bn=e=>{if(void 0===e)return;const t=Array.isArray(e)?e:[e];for(const e of t)if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("Options must be a plain object or an array of plain objects.")};function vn(e){if(bn(e),Array.isArray(e)){const t=e.map(wn).join("|");return new RegExp(`^(?:${t})$`)}return new RegExp(`^${wn(e)}$`)}function En(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");return(r??vn(t)).test(e)}function Tn(e){bn(e);const t=Array.isArray(e)?e[0]:e,r=t?.prefix||t?.start,i=r?"(?:^|(?<=\\W))":"\\b",s=r?"(?=\\W|$)":"\\b";if(Array.isArray(e)){const t=e.map(wn).join("|");return new RegExp(`${i}(?:${t})${s}`,"g")}return new RegExp(`${i}${wn(e)}${s}`,"g")}function Sn(e,t,r){if("string"!=typeof e)throw new TypeError("The input must be a string.");const i=e.match(r??Tn(t));if(!i)return[];const s=Array.isArray(t)?t[0]?.transform:t?.transform;return s?i.map(e=>yn(e,s)):i}const xn=class{#sh;#nh=[];#oh=!1;#ah;#lh="";constructor(e){const t=e.tagName;if("string"!=typeof t)throw new TypeError("The tagName must be a string.");if(/[<>\s]/.test(t))throw new TypeError("The tagName must be a single word without spaces or < > characters.");if(this.#sh=t,e.attributes){if(!Array.isArray(e.attributes))throw new TypeError("The attributes property must be an array of strings.");for(const t of e.attributes)if("string"!=typeof t||/[<>\s]/.test(t))throw new TypeError("Each attribute name must be a single word string without spaces or < > characters.");this.#nh=e.attributes}if("boolean"!=typeof e.captureAllAttributes)throw new TypeError("captureAllAttributes must be a boolean.");this.#ah=e.captureAllAttributes,this.freeMode=e.freeMode??!1,this.contentPattern=e.contentPattern||(this.#oh?"[\\s\\S]*?":".*?")}get tagName(){return this.#sh}get attributes(){return[...this.#nh]}get freeMode(){return this.#oh}set freeMode(e){if("boolean"!=typeof e)throw new TypeError("freeMode must be a boolean.");this.#oh=e}get captureAllAttributes(){return this.#ah}get contentPattern(){return this.#lh}set contentPattern(e){if("string"!=typeof e)throw new TypeError("contentPattern must be a string.");this.#lh=e}toString(){let e=`<${this.#sh}`;if(this.#ah)e+="([^>]*)";else{for(const t of this.#nh)e+=`(?=[^>]*?\\s+${t}(?:=(?:["']([^"']*)["']|([^"'>\\s]+)))?(?=\\s|>|\\/))`;e+="[^>]*"}return e+=`>(${this.#lh})</${this.#sh}>`,e}toRegExp(e="g"){return new RegExp(this.toString(),e)}parse(e){const t=this.toRegExp("g"),r=[];let i;for(;null!==(i=t.exec(e));){const e={};let t="";if(this.#ah){const r=i[1]||"";t=i[2]||"";const s=/([^\s=]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s"'>]+)))?/g;let n;for(;null!==(n=s.exec(r));){const t=n[1],r=n[2]??n[3]??n[4]??!0;e[t]=r}}else{for(let t=0;t<this.#nh.length;t++){const r=this.#nh[t],s=i[2*t+1],n=i[2*t+2];e[r]=s??n??!0}t=i[2*this.#nh.length+1]||""}r.push({attributes:e,child:t})}return r}},An=le("TinyUriParser"),Cn=class{static buildParserPair(e,t,r,i){return Object.freeze([e,t,t=>({type:e,data:r(t)}),i])}#hr=!1;get isDestroyed(){return this.#hr}#hh;get parsers(){return An(this.#hr),Array.from(this.#hh).map(e=>[...e])}get size(){return An(this.#hr),this.#hh.size}constructor(...e){for(const[t,r]of e.entries()){if(!Array.isArray(r))throw new TypeError(`Parser at index ${t} must be an array representing a ParserPair.`);if(4!==r.length)throw new TypeError(`Parser at index ${t} must contain exactly 4 elements.`);if("string"!=typeof r[0])throw new TypeError(`The first element of the parser at index ${t} must be a string (Type).`);if("function"!=typeof r[1])throw new TypeError(`The second element of the parser at index ${t} must be a function (ParseChecker).`);if("function"!=typeof r[2])throw new TypeError(`The third element of the parser at index ${t} must be a function (ParserCallback).`);if("function"!=typeof r[3])throw new TypeError(`The fourth element of the parser at index ${t} must be a function (StringifyCallback).`)}this.#hh=new Set(e)}parse(e){if(An(this.#hr),"string"!=typeof e)throw new TypeError("The input must be a string.");for(const t of this.#hh)if(t[1](e))return t[2](e);throw new Error(`Unable to determine the protocol for the provided URI: ${e}`)}stringify(e){if(An(this.#hr),!v(e)||"string"!=typeof e.type)throw new TypeError('The input must be a valid ParsedUri object with a "type" property.');for(const t of this.#hh){const[r,,,i]=t;if(r===e.type&&"function"==typeof i){const t=i(e.data);if("string"==typeof t)return t}}throw new Error(`No reconstructor found for the parsed type: ${e.type}`)}destroy(){this.#hr||(this.#hh.clear(),this.#hr=!0)}},In=le("TinyBrowserMonitor"),kn=e().EventEmitter;class Dn extends kn{static#uh=["connectivity","quality","battery","device","cpu","gpu","performance","resource","paint","navigation","layout-shift","lcp","longtask","memory-usage","fps","window","screen"];static get VALID_SYSTEMS(){return Object.freeze([...Dn.#uh])}#hr=!1;#ch=new Set;#dh={isOnline:navigator.onLine};#mh=null;#ph;#fh;#yh={usedJSHeapSize:0,totalJSHeapSize:0,jsHeapSizeLimit:0,enabled:!!performance.memory};#gh={downlink:0,rtt:0,effectiveType:"unknown",saveData:!1,enabled:!!navigator.connection};#wh=[];#bh={level:1,charging:!0,chargingTime:0,dischargingTime:0,enabled:!1};#vh={memory:0,cpu:{logicalCores:0},gpu:{vendor:"unknown",renderer:"unknown"},enabled:!!navigator.deviceMemory};#Eh={fps:60,timestamp:performance.now()};#Th=null;#Sh={paint:{firstPaint:0,firstContentfulPaint:0},navigation:null,layoutShift:0,lcp:0,fps:this.#Eh,longTasks:[]};#xh={width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio};#Ah={width:window.screen.width,height:window.screen.height,availWidth:window.screen.availWidth,availHeight:window.screen.availHeight,colorDepth:window.screen.colorDepth,pixelDepth:window.screen.pixelDepth,orientation:window.screen.orientation?.type||"unknown"};#Ch;#Ih=[];constructor(e={}){super();const{resourceLimit:t=1e3,systems:r=[],memoryIntervalMs:i=100,fpsIntervalMs:s=1e3}=e;if("number"!=typeof t||t<-1)throw new TypeError("The resourceLimit must be a number greater than or equal to -1.");if("number"!=typeof i||i<16)throw new TypeError("The memoryIntervalMs must be a number greater than or equal to 16.");if("number"!=typeof s||s<0)throw new TypeError("The fpsIntervalMs must be a number greater than or equal to 0.");if(!Array.isArray(r))throw new TypeError("The systems option must be an array.");for(const e of r)if(!Dn.#uh.includes(e))throw new TypeError(`Invalid system identifier: "${e}". Must be one of: ${Dn.#uh.join(", ")}`);this.#Ch=t,this.#ph=i,this.#fh=s,this.#ch=0===r.length?new Set(Dn.#uh):new Set(r),this.#kh(),this.#Dh()}#kh(){this.#ch.has("connectivity")&&this.#Mh(),this.#ch.has("quality")&&this.#Lh(),this.#ch.has("battery")&&this.#Nh(),this.#ch.has("memory-usage")&&this.#_h(),this.#ch.has("fps")&&this.#Rh(),this.#ch.has("window")&&this.#jh(),this.#ch.has("screen")&&this.#Ph(),(this.#ch.has("device")||this.#ch.has("cpu")||this.#ch.has("gpu"))&&this.#Oh();const e=this.#ch.has("performance"),t=["resource","paint","navigation","layout-shift","lcp","longtask"].some(e=>this.#ch.has(e));(e||t)&&this.#$h(e)}get isDestroyed(){return this.#hr}get connectivity(){return In(this.#hr),Object.freeze({...this.#dh})}get quality(){return In(this.#hr),Object.freeze({...this.#gh})}get resources(){return In(this.#hr),Object.freeze(this.#wh.map(e=>Object.freeze({...e})))}get battery(){return In(this.#hr),Object.freeze({...this.#bh})}get windowMetrics(){return In(this.#hr),Object.freeze({...this.#xh})}get screenMetrics(){return In(this.#hr),Object.freeze({...this.#Ah})}get device(){return In(this.#hr),Object.freeze({...this.#vh})}get fps(){return In(this.#hr),Object.freeze({...this.#Eh})}get performance(){return In(this.#hr),Object.freeze({...this.#Sh,paint:Object.freeze({...this.#Sh.paint}),fps:Object.freeze({...this.#Sh.fps}),navigation:this.#Sh.navigation?Object.freeze({...this.#Sh.navigation}):null})}get memoryUsage(){return In(this.#hr),Object.freeze({...this.#yh})}get enabledSystems(){return In(this.#hr),Object.freeze([...this.#ch])}has(e){if(In(this.#hr),"string"!=typeof e)throw new TypeError("The system identifier must be a string.");return this.#ch.has(e)}get size(){return In(this.#hr),this.#ch.size}getFormattedMemoryUsage(e,t=this.#yh){In(this.#hr);const r=["bytes","KB","MB","GB"];if("string"!=typeof e||!r.includes(e))throw new TypeError(`Invalid format: "${e}". Must be one of: ${r.join(", ")}`);if("object"!=typeof t||null===t)throw new TypeError("The memoryUsage argument must be a non-null object.");const i=["usedJSHeapSize","totalJSHeapSize","jsHeapSizeLimit"];for(const e of i)if("number"!=typeof t[e]||Number.isNaN(t[e]))throw new TypeError(`Invalid memoryUsage: Property "${e}" must be a valid number.`);const s={bytes:1,KB:1024,MB:Math.pow(1024,2),GB:Math.pow(1024,3)}[e],n=e=>e/s;return{used:n(t.usedJSHeapSize),total:n(t.totalJSHeapSize),limit:n(t.jsHeapSizeLimit)}}#jh(){window.addEventListener("resize",this.#Hh),this.#Fh()}#Fh(){this.#xh={width:window.innerWidth,height:window.innerHeight,devicePixelRatio:window.devicePixelRatio}}#Ph(){this.#Ah={width:window.screen.width,height:window.screen.height,availWidth:window.screen.availWidth,availHeight:window.screen.availHeight,colorDepth:window.screen.colorDepth,pixelDepth:window.screen.pixelDepth,orientation:window.screen.orientation?.type||"unknown"}}#Hh=()=>{this.#Fh(),this.emit("WindowResize",Object.freeze({...this.#xh}))};#Mh(){window.addEventListener("online",this.#zh),window.addEventListener("offline",this.#zh),navigator.connection&&navigator.connection.addEventListener("change",this.#zh)}#Rh(){let e=0,t=performance.now();const r=i=>{e++,i-t>=this.#fh&&(this.#Eh={fps:Math.round(1e3*e/(i-t)),timestamp:i},e=0,t=i,this.emit("FPS",Object.freeze({...this.#Eh}))),this.#Th=requestAnimationFrame(r)};this.#Th=requestAnimationFrame(r)}#Oh(){this.#vh={memory:0,cpu:{logicalCores:0},gpu:{vendor:"unknown",renderer:"unknown"},enabled:!1};let e=!1;if(this.#ch.has("device")&&("number"==typeof navigator.deviceMemory&&(this.#vh.memory=navigator.deviceMemory,e=!0),this.#ch.has("cpu")&&"number"==typeof navigator.hardwareConcurrency&&(this.#vh.cpu.logicalCores=navigator.hardwareConcurrency,e=!0),this.#ch.has("gpu")))try{const t=document.createElement("canvas"),r=t.getContext("webgl")||t.getContext("experimental-webgl");if(r instanceof WebGLRenderingContext){const t=r.getExtension("WEBGL_debug_renderer_info");t&&(this.#vh.gpu.vendor=r.getParameter(t.UNMASKED_VENDOR_WEBGL)||"unknown",this.#vh.gpu.renderer=r.getParameter(t.UNMASKED_RENDERER_WEBGL)||"unknown",e=!0)}}catch(e){console.warn("TinyBrowserMonitor: GPU retrieval failed.",e)}this.#vh.enabled=e}async#Nh(){if(navigator.getBattery)try{const e=await navigator.getBattery();this.#bh.enabled=!0;const t=()=>{this.#bh={level:e.level,charging:e.charging,chargingTime:e.chargingTime,dischargingTime:e.dischargingTime,enabled:!0},this.emit("BatteryUpdated",Object.freeze({...this.#bh})),this.#Dh()};e.addEventListener("levelchange",t),e.addEventListener("chargingchange",t),e.addEventListener("chargingtimechange",t),e.addEventListener("dischargingtimechange",t),t()}catch(e){console.warn("Battery Status API failed to initialize:",e)}}#_h(){if(performance.memory){const e=()=>{const e=performance.memory;e&&(this.#yh={usedJSHeapSize:e.usedJSHeapSize,totalJSHeapSize:e.totalJSHeapSize,jsHeapSizeLimit:e.jsHeapSizeLimit,enabled:!0},this.emit("MemoryUsage",Object.freeze({...this.#yh})))};this.#mh=setInterval(e,this.#ph),e()}}#$h(e=!1){const t=[{key:"resource",type:"resource",callback:this.#Bh.bind(this)},{key:"paint",type:"paint",callback:this.#Wh.bind(this)},{key:"navigation",type:"navigation",callback:this.#Uh.bind(this)},{key:"layout-shift",type:"layout-shift",callback:this.#qh.bind(this)},{key:"lcp",type:"largest-contentful-paint",callback:this.#Vh.bind(this)},{key:"longtask",type:"longtask",callback:this.#Kh.bind(this)}];for(const r of t)if(e||this.#ch.has(r.key))try{const e=new PerformanceObserver(r.callback);e.observe({type:r.type,buffered:!0}),this.#Ih.push(e)}catch(e){console.error(e)}}#Bh(e){const t=e.getEntries(),r=new Ai(this.#wh.map(e=>({...e})),{idKey:"name"});t.forEach(e=>{this.#wh.push({name:e.name,duration:e.duration,entryType:e.entryType})}),this.#Ch>0&&this.#wh.length>this.#Ch&&this.#wh.splice(0,this.#wh.length-this.#Ch);const i=r.compare(this.#wh);for(const e of i)this.emit("Resource"+("added"===e.status?"Added":"deleted"===e.status?"Deleted":"Edited"),e.oldItem,e.item);this.#Dh()}#Wh(e){e.getEntries().forEach(e=>{"first-paint"===e.name?this.#Sh.paint.firstPaint=e.startTime:"first-contentful-paint"===e.name&&(this.#Sh.paint.firstContentfulPaint=e.startTime)}),this.emit("PaintUpdated",Object.freeze({...this.#Sh.paint})),this.#Dh()}#Uh(e){const t=e.getEntries()[0];t&&(this.#Sh.navigation={ttfb:t.responseStart-t.requestStart,domContentLoaded:t.domContentLoadedEventEnd-t.startTime,loadEvent:t.loadEventEnd-t.startTime}),this.emit("NavigationUpdated",Object.freeze({...this.#Sh.navigation})),this.#Dh()}#qh(e){e.getEntries().forEach(e=>{const t=e;t.hadRecentInput||(this.#Sh.layoutShift+=t.value)}),this.emit("LayoutShiftUpdated",{layoutShift:this.#Sh.layoutShift}),this.#Dh()}#Vh(e){const t=e.getEntries().pop();t&&(this.#Sh.lcp=t.startTime),this.emit("LcpUpdated",{lcp:this.#Sh.lcp}),this.#Dh()}#Kh(e){e.getEntries().forEach(e=>{this.#Sh.longTasks.push(e.duration)}),this.emit("LongTaskUpdated",{lcp:[...this.#Sh.longTasks]}),this.#Dh()}#zh=e=>{this.#ch.has("connectivity")&&this.#Gh(),this.#ch.has("quality")&&this.#Lh(),this.#Dh(e)};#Gh(){this.#dh={isOnline:navigator.onLine},this.emit("ConnectivityUpdated",{...this.#dh})}#Lh(){if(navigator.connection){const{downlink:e,rtt:t,effectiveType:r,saveData:i}=navigator.connection;this.#gh={downlink:"number"==typeof e?e:0,rtt:"number"==typeof t?t:0,effectiveType:"string"==typeof r?r:"unknown",saveData:"boolean"==typeof i&&i,enabled:!0}}}#Dh(e){this.#Jh();const t={connectivity:Object.freeze({...this.#dh}),quality:Object.freeze({...this.#gh}),resources:Object.freeze(this.#wh.map(e=>Object.freeze({...e}))),battery:Object.freeze({...this.#bh}),device:Object.freeze({...this.#vh}),performance:this.performance,memoryUsage:Object.freeze({...this.#yh}),windowMetrics:Object.freeze({...this.#xh}),screenMetrics:Object.freeze({...this.#Ah}),event:e};this.emit("NetworkUpdated",t)}#Jh(){if("boolean"!=typeof this.#dh.isOnline)throw new TypeError("Internal Error: Connectivity status is invalid.");if("number"!=typeof this.#gh.downlink)throw new TypeError("Internal Error: Quality metrics are invalid.")}destroy(){this.#hr||(this.#ch.has("connectivity")&&(window.removeEventListener("online",this.#zh),window.removeEventListener("offline",this.#zh)),this.#ch.has("window")&&window.removeEventListener("resize",this.#Hh),this.#ch.has("quality")&&navigator.connection&&navigator.connection.removeEventListener("change",this.#zh),this.#ch.has("performance")&&(this.#Ih.forEach(e=>e.disconnect()),this.#Ih=[]),this.#mh&&clearInterval(this.#mh),this.#Th&&cancelAnimationFrame(this.#Th),this.removeAllListeners(),this.#hr=!0,this.emit("Destroyed"))}}const Mn=Dn,Ln=le("TinyThrottledApi"),Nn=e().EventEmitter,_n=class extends Nn{static TinyTimeout=Dr;#Yh=0;#Xh;#i=new ae;#Qh;#Zh;#eu=100;#tu=5e3;#hr=!1;#ru=!1;constructor(e,t,r=null){if(super(),"number"!=typeof e||e<=0)throw new TypeError("Concurrency limit must be a positive number.");if("function"!=typeof t)throw new TypeError("API must be a function.");if(null!=r&&!(r instanceof Dr))throw new TypeError("timeoutInstance must be a TinyTimeout instance.");this.#Xh=e,this.#Qh=t,this.#Zh=r??null}async exec(...e){Ln(this.#hr);const t=crypto.randomUUID();if(this.#Yh<this.#Xh){this.#Yh++,this.emit("ExecTask",t);const r=await this.#iu(...e);return this.emit("TaskEnded",t),r}return this.#i.enqueue(async()=>{this.emit("WaitingTask",t);const r=()=>Cr(()=>this.#Yh<this.#Xh),i=async()=>{this.#Zh&&await new Promise(e=>{this.#Zh?this.#Zh.set("api_throttle",e,this.#eu,this.#tu):e(void 0)})};this.#ru?(await i(),await r()):(await r(),await i()),this.#Yh++,this.emit("ExecTask",t);const s=await this.#iu(...e);return this.emit("TaskEnded",t),s},void 0,t)}destroy(){this.#hr||(this.removeAllListeners(),this.#hr=!0,this.emit("Destroyed"))}async#iu(...e){try{const t=this.#Qh;return await t(...e)}finally{this.#Yh--}}get isDestroyed(){return this.#hr}get queue(){return Ln(this.#hr),this.#i}get api(){return Ln(this.#hr),this.#Qh}get concurrencyLimit(){return Ln(this.#hr),this.#Xh}set concurrencyLimit(e){if(Ln(this.#hr),"number"!=typeof e||e<=0)throw new TypeError("Concurrency limit must be a positive number.");this.#Xh=e,this.emit("SetConcurrencyLimit",e)}get timeoutInstance(){return Ln(this.#hr),this.#Zh}get timeoutValue(){return Ln(this.#hr),this.#eu}set timeoutValue(e){if(Ln(this.#hr),"number"!=typeof e)throw new TypeError("Timeout value must be a number.");if(e<0)throw new RangeError("Timeout value cannot be negative.");this.#eu=e,this.emit("SetTimeoutValue",e)}get timeoutLimit(){return Ln(this.#hr),this.#tu}get timeoutFirst(){return this.#ru}set timeoutFirst(e){if("boolean"!=typeof e)throw new TypeError("timeoutFirst must be a boolean.");this.#ru=e}set timeoutLimit(e){if(Ln(this.#hr),"number"!=typeof e)throw new TypeError("Timeout limit must be a number.");if(e<0)throw new RangeError("Timeout limit cannot be negative.");this.#tu=e,this.emit("SetTimeoutLimit",e)}get activeCount(){return Ln(this.#hr),this.#Yh}get queuedCount(){return Ln(this.#hr),this.#i.getQueuedIds().length}},Rn=(e,t=!0)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("GLOB pattern must be a string or an array of strings.");if(Array.isArray(e)&&!e.every(e=>"string"==typeof e))throw new TypeError("All elements in the GLOB array must be strings.");if("boolean"!=typeof t)throw new TypeError("Strict mode must be a boolean.");const r=Array.isArray(e)?e.join(""):e,i=["^"];let s=0,n=!1,o=!1;for(;s<r.length;){const e=r[s];if("\\"===e){const e=r[s+1]||"";i.push("\\"+e),s+=2;continue}if(o)"]"===e?(o=!1,i.push("]")):"!"===e&&"["===r[s-1]?i.push("^"):i.push(e),s++;else{switch(e){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":i.push("\\"+e);break;case"?":i.push("[^/]");break;case"[":o=!0,i.push(e);break;case"]":i.push("\\]");break;case"{":n=!0,i.push("(");break;case"}":n?(n=!1,i.push(")")):i.push("\\}");break;case",":i.push(n?"|":"\\,");break;case"*":let t=1;for(;"*"===r[s+1];)t++,s++;t>1?i.push(".*"):i.push("[^/]*");break;default:i.push(e)}s++}}if(t){if(o)throw new SyntaxError('Unmatched bracket "[" in GLOB pattern.');if(n)throw new SyntaxError('Unmatched brace "{" in GLOB pattern.')}return i.push("$"),i},jn=(e,t="",r=!0)=>{if("string"!=typeof t)throw new TypeError("RegExp flags must be a string.");return new RegExp(Rn(e,r).join(""),t)},Pn=e=>{if(!(e instanceof RegExp||"string"==typeof e||Array.isArray(e)&&e.every(e=>"string"==typeof e)))throw new TypeError("Argument must be a RegExp instance or string stuff.");let t="string"==typeof e?e:Array.isArray(e)?e.join(""):e.source;const r=[];t.startsWith("^")&&(t=t.slice(1)),t.endsWith("$")&&(t=t.slice(0,-1));let i=0;for(;i<t.length;){const e=t[i];if("\\"===e){const e=t[i+1]||"";r.push(e),i+=2;continue}if("."!==e||"*"!==t[i+1]){if("["===e){if("[^/]*"===t.slice(i,i+5)){r.push("*"),i+=5;continue}if("[^/]"===t.slice(i,i+4)){r.push("?"),i+=4;continue}if("^"===t[i+1]){r.push("[!"),i+=2;continue}}"("!==e?"|"!==e?")"!==e?(r.push(e),i++):(r.push("}"),i++):(r.push(","),i++):(r.push("{"),i++)}else r.push("**"),i+=2}return r},On=e=>{try{return Rn(e,!0),!0}catch(e){if(e instanceof SyntaxError)return!1;throw e}},$n=le("TinyWebWorker");class Hn extends ks{static#kl(e){if(e.startsWith("ww:"))throw new TypeError(`The event type "${e}" is reserved for internal Web Worker lifecycle management.`)}#su=null;#pl;#nu;#ou;#ol=!1;#hr=!1;#Pl=new Map;#Ol=new Map;#_l=null;#au=null;get isReady(){return this.#ol}get isDestroyed(){return this.#hr}get worker(){return $n(this.#hr),this.#su}constructor({id:e,workerUrl:t,workerOptions:r={},logger:i,debugMode:s,useLogColors:n}){if(super({logCfg:{id:"[_sub_class_TinyWebWorker_reset_]",logger:i??console,debugMode:s??!1,useLogColors:n??!1}}),"string"!=typeof e||""===e.trim())throw new TypeError('The "id" parameter must be a non-empty string.');if("string"!=typeof t&&!(t instanceof URL))throw new TypeError('The "workerUrl" parameter must be a string or URL.');this.#pl=e,this.#nu=t,this.#ou=r}async init(){if($n(this.#hr),this.#su)throw new Error("Worker is already initialized.");return new Promise((e,t)=>{try{this.#su=new Worker(this.#nu,this.#ou)}catch(e){return this.log("error","Failed to instantiate Worker:",e),t(e)}this.#_l=t=>{const r=t.data;if(Array.isArray(r)||"object"!=typeof r||null===r)return;if("string"!=typeof r.type)return;if("ww:EngineReady"===r.type)return this.#ol=!0,super.emit("ww:Started"),void e();const i=r.type,s=r.data,n=r.correlationId,o=r.isApi;if("ww:ApiResponse"===i){if("string"!=typeof n)return;const e=this.#Pl.get(n);return void(e&&(clearTimeout(e.timer),this.#Pl.delete(n),r.error?e.reject(new Error(r.error)):e.resolve(s)))}if(!0===o){if("string"!=typeof n)return;const e=this.#Ol.get(i);if(!e)return void this.#su?.postMessage({correlationId:n,type:"ww:ApiResponse",error:`No API handler registered in Main Thread for type: ${i}`});try{const t=e=>this.#su?.postMessage({correlationId:n,type:"ww:ApiResponse",data:e}),r=e({data:s,correlationId:n});r instanceof Promise?r.then(t).catch(e=>{this.#su?.postMessage({correlationId:n,type:"ww:ApiResponse",error:e instanceof Error?e.message:String(e)})}):t(r)}catch(e){this.#su?.postMessage({correlationId:n,type:"ww:ApiResponse",error:e instanceof Error?e.message:String(e)})}return}super.emit(i,{data:s,event:t})},this.#au=e=>{this.log("error",`Worker Error [${this.#pl}]:`,e.message),super.emit("ww:Error",{error:e}),t(new Error(`Web Worker [${this.#pl}] failed to start: ${e.message||"unknown error"}`))},this.#su.addEventListener("message",this.#_l),this.#su.addEventListener("error",this.#au)})}#Jl(e,t,r=!1){if($n(this.#hr),!this.#su)throw new Error("Worker is not initialized.");if("string"!=typeof e)throw new TypeError("Payload.type must be a string.");if(void 0!==t&&(Array.isArray(t)||"object"!=typeof t||null===t))throw new TypeError("Payload.data must be a non-null object.");r&&Hn.#kl(e),this.#su.postMessage({type:e,data:t})}emitMessage(e,t){this.#Jl(e,t,!0)}onApi(e,t){if("function"!=typeof t)throw new TypeError("Callback must be a function.");this.#Ol.set(e,t)}offApi(e){return this.#Ol.delete(e)}async emitApi(e,t,r=1e4){if($n(this.#hr),!this.#su)throw new Error("Worker is not initialized.");const i=crypto.randomUUID();return new Promise((s,n)=>{const o=setTimeout(()=>{this.#Pl.has(i)&&(this.#Pl.delete(i),n(new Error(`API request timeout: ${e} (ID: ${i})`)))},r);this.#Pl.set(i,{resolve:s,reject:n,timer:o}),this.#su?.postMessage({type:e,data:t,correlationId:i,isApi:!0})})}terminate(){this.#hr||(this.#su&&(this.#_l&&this.#su.removeEventListener("message",this.#_l),this.#au&&this.#su.removeEventListener("error",this.#au),this.#su.terminate(),this.log("info",`Web Worker [${this.#pl}] terminated.`)),this.#su=null,this.#_l=null,this.#au=null,this.#ol=!1,super.emit("ww:Terminated"))}destroy(){this.#hr||(this.terminate(),this.removeAllListeners(),this.destroyPlugins(),this.#hr=!0,this.log("info",`[${this.#pl}] Destroyed successfully.`))}}const Fn=Hn,zn=Object.freeze({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:64,O_EXCL:128,O_TRUNC:512,O_APPEND:1024}),Bn=(Object.freeze({OWNER_READ:256,OWNER_WRITE:128,OWNER_EXECUTE:64,GROUP_READ:32,GROUP_WRITE:16,GROUP_EXECUTE:8,OTHER_READ:4,OTHER_WRITE:2,OTHER_EXECUTE:1,SETUID:2048,SETGID:1024,STICKY:512}),Object.freeze({FILE:32768,DIRECTORY:16384,SYMBOLIC_LINK:40960})),Wn=Object.freeze(["utf8","utf-8","base64","hex"]),Un=(e,t,r,i="")=>{const s=i.length>0?`, ${i}`:"",n=new Error(`${e}: ${t} '${r}'${s}`);return n.code=e,n.errno=e,n.syscall=t,n.path=r,n},qn=(e,t,r,i="ENOTDIR")=>{if("undefined"!=typeof DOMException&&e instanceof DOMException)switch(e.name){case"NotFoundError":return Un("ENOENT",t,r);case"TypeMismatchError":return Un(i,t,r);case"InvalidModificationError":return Un("ENOTEMPTY",t,r);case"NoModificationAllowedError":return Un("EBUSY",t,r);case"NotAllowedError":return Un("EACCES",t,r);default:return Un("EIO",t,r,e.message)}return e instanceof Error?e:new Error(String(e))},Vn=(e,t)=>{if("string"!=typeof e)throw new TypeError(`The "${t}" argument must be of type string. Received ${null===e?"null":typeof e}`);if(0===e.length)throw Un("ENOENT","open",e,"path must not be empty");if(e.includes("\0"))throw new TypeError('The "path" argument must not contain null bytes');return e},Kn=(e,t)=>{if(null===e||"object"!=typeof e||Array.isArray(e)){const r=null===e?"null":Array.isArray(e)?"Array":typeof e;throw new TypeError(`The "options" argument must be of type object. Received ${r} in ${t}()`)}return e},Gn=(e,t)=>{if(null==e)return null;if("string"!=typeof e||!Wn.includes(e))throw new TypeError(`The "encoding" option must be one of ${Wn.join(", ")}. Received ${String(e)} in ${t}()`);return e},Jn=(e,t)=>{if("number"!=typeof e||!Number.isInteger(e))throw new TypeError(`The "${t}" argument must be an integer`);if(e<0)throw new RangeError(`The "${t}" argument must not be negative`);return e};class Yn{#wn;constructor(e){this.#wn=Object.freeze({...e})}get path(){return this.#wn.path}get name(){return this.#wn.name}get size(){return"directory"===this.#wn.kind?0:this.#wn.size}get mode(){return this.#wn.mode}get uid(){return this.#wn.uid}get gid(){return this.#wn.gid}get ino(){return this.#wn.ino}get nlink(){return 1}get atimeMs(){return this.#wn.atimeMs}get mtimeMs(){return this.#wn.mtimeMs}get birthtimeMs(){return this.#wn.birthtimeMs}get atime(){return new Date(this.#wn.atimeMs)}get mtime(){return new Date(this.#wn.mtimeMs)}get ctime(){return new Date(this.#wn.mtimeMs)}get birthtime(){return new Date(this.#wn.birthtimeMs)}isFile(){return"file"===this.#wn.kind}isDirectory(){return"directory"===this.#wn.kind}isSymbolicLink(){return"symbolic-link"===this.#wn.kind}isBlockDevice(){return!1}isCharacterDevice(){return!1}isFIFO(){return!1}isSocket(){return!1}get modeWithType(){return(this.isDirectory()?Bn.DIRECTORY:Bn.FILE)|this.#wn.mode}}class Xn{#eo;#lu;constructor(e,t){this.#eo=e,this.#lu=t}get name(){return this.#eo}isFile(){return"file"===this.#lu}isDirectory(){return"directory"===this.#lu}isSymbolicLink(){return"symbolic-link"===this.#lu}isBlockDevice(){return!1}isCharacterDevice(){return!1}isFIFO(){return!1}isSocket(){return!1}}class Qn{#hu;#uu;#cu;#du;constructor(e,t,r){this.#hu=e,this.#uu=t,this.#cu=r,this.#du=!1}get path(){return this.#uu}get flags(){return this.#cu}get closed(){return this.#du}async readFile(e){return this.#mu(),this.#hu.readFile(this.#uu,e)}async writeFile(e,t){return this.#mu(),this.#hu.writeFile(this.#uu,e,t)}async appendFile(e,t){return this.#mu(),this.#hu.appendFile(this.#uu,e,t)}async stat(){return this.#mu(),this.#hu.stat(this.#uu)}async truncate(e){return this.#mu(),this.#hu.truncate(this.#uu,e)}async close(){this.#du=!0}#mu(){if(this.#du)throw Un("EBADF","read",this.#uu,"file handle is closed")}}const Zn=e=>{const t=[];for(const r of e.split("/"))0!==r.length&&"."!==r&&(".."!==r?t.push(r):t.pop());return t},eo=class{#pu=new Map;#fu;#yu;#gu;constructor(e={}){const{cwd:t="/",umask:r=18,identity:i}=Kn(e,"constructor");this.#fu="string"==typeof t?t:"/",this.#yu="number"==typeof r?r:18,this.#gu={uid:i?.uid??0,gid:i?.gid??0,groups:i?.groups??[]}}static get capabilities(){return Object.freeze({permissions:!1,ownership:!1,symlinks:!1,timestamps:!1,atomicRename:!1,seekableHandles:!1})}get cwd(){return this.#fu}get umask(){return this.#yu}get identity(){return this.#gu}async _readFile(e){throw this.#wu("readFile",e)}async _writeFile(e,t,r){throw this.#wu("writeFile",e)}async _readdir(e){throw this.#wu("readdir",e)}async _mkdir(e,t){throw this.#wu("mkdir",e)}async _rm(e,t){throw this.#wu("rm",e)}async _stat(e){throw this.#wu("stat",e)}async _rename(e,t){throw this.#wu("rename",e)}async _copyFile(e,t,r){throw this.#wu("copyFile",e)}async _readMetadata(e){return this.#pu.get(e)??{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null}}async _writeMetadata(e,t){this.#pu.set(e,t)}async readFile(e,t={}){const r=Vn(e,"path"),{encoding:i}=Kn(t,"readFile"),s=Gn(i,"readFile");return((e,t)=>null===t?e:"base64"===t?(e=>{let t="";for(const r of e)t+=String.fromCharCode(r);return btoa(t)})(e):"hex"===t?(e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""))(e):new TextDecoder("utf-8").decode(e))(await this._readFile(r),s)}async writeFile(e,t,r={}){const i=Vn(e,"path"),{encoding:s,append:n,mode:o}=Kn(r,"writeFile"),a=((e,t)=>{if("string"==typeof e)return"base64"===t?(e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r})(e):"hex"===t?(e=>{if(e.length%2!=0)throw new TypeError('The "hex" encoded string must have an even length');const t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(2*r,2*r+2),16);return t})(e):(new TextEncoder).encode(e);if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new TypeError('The "data" argument must be a string, an ArrayBuffer or an ArrayBufferView')})(t,Gn(s,"writeFile")),l=await this.exists(i);if(await this._writeFile(i,a,{append:!0===n,mode:"number"==typeof o?o:void 0}),!l){const e="number"==typeof o?o:438;await this._writeMetadata(i,{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null,mode:e&~this.#yu,uid:this.#gu.uid,gid:this.#gu.gid,birthtimeMs:Date.now(),mtimeMs:Date.now(),atimeMs:Date.now()})}}async appendFile(e,t,r={}){const i=Vn(e,"path"),s=Kn(r,"appendFile");return this.writeFile(i,t,{...s,append:!0})}async readdir(e,t={}){const r=Vn(e,"path"),{withFileTypes:i,recursive:s}=Kn(t,"readdir"),n=await this._readdir(r),o=[];for(const e of n)if(o.push(!0===i?new Xn(e.name,e.kind):e.name),!0===s&&"directory"===e.kind){const s=`${r.replace(/\/$/,"")}/${e.name}`,n=await this.readdir(s,t);for(const t of n){const r="string"==typeof t?t:t.name;o.push(!0===i?new Xn(`${e.name}/${r}`,"file"):`${e.name}/${r}`)}}return o}async mkdir(e,t={}){const r=Vn(e,"path"),{recursive:i,mode:s}=Kn(t,"mkdir");await this._mkdir(r,{recursive:!0===i});const n="number"==typeof s?s:511;return await this._writeMetadata(r,{mode:null,uid:null,gid:null,atimeMs:null,mtimeMs:null,birthtimeMs:null,mode:n&~this.#yu,uid:this.#gu.uid,gid:this.#gu.gid,birthtimeMs:Date.now(),mtimeMs:Date.now(),atimeMs:Date.now()}),!0===i?r:void 0}async rm(e,t={}){const r=Vn(e,"path"),{recursive:i,force:s}=Kn(t,"rm");await this._rm(r,{recursive:!0===i,force:!0===s}),this.#pu.delete(r)}async unlink(e){const t=Vn(e,"path"),r=await this.__stat(t);if(r?.isDirectory())throw Un("EISDIR","unlink",t);await this.rm(t,{force:!1})}async rmdir(e,t={}){const r=Vn(e,"path"),{recursive:i}=Kn(t,"rmdir");await this.rm(r,{recursive:!0===i})}async rename(e,t){const r=Vn(e,"oldPath"),i=Vn(t,"newPath");await this._rename(r,i);const s=await this._readMetadata(r);await this._writeMetadata(i,s),this.#pu.delete(r)}async copyFile(e,t,r=0){const i=Vn(e,"sourcePath"),s=Vn(t,"destinationPath"),n="number"==typeof r?r:0;await this._copyFile(i,s,n);const o=await this._readMetadata(i);await this._writeMetadata(s,o)}async __stat(e,t={}){const r=Vn(e,"path"),{throwIfNoEntry:i}=Kn(t,"stat"),s=await this._stat(r);if(void 0===s){if(!1===i)return;throw Un("ENOENT","stat",r)}const n=await this._readMetadata(r),o="directory"===s.kind?511:438;return new Yn({path:r,name:s.name,kind:s.kind,size:s.size,mode:n.mode??o,uid:n.uid??0,gid:n.gid??0,atimeMs:n.atimeMs??s.mtimeMs,mtimeMs:n.mtimeMs??s.mtimeMs,birthtimeMs:n.birthtimeMs??s.mtimeMs,ino:0})}async stat(e,t={}){const r=Vn(e,"path"),i=await this.__stat(r,t);if(void 0===i)throw Un("ENOENT","stat",r);return i}async lstat(e,t={}){return this.stat(e,t)}async access(e,t=zn.F_OK){const r=Vn(e,"path");if("number"!=typeof t||!Number.isInteger(t))throw new TypeError('The "mode" argument must be an integer');const i=await this.__stat(r);if(t===zn.F_OK)return;if(!i)throw Un("ENOENT","access",r);const s=this.#bu(i.uid,i.gid),n=i.mode>>s&7;if(t&zn.R_OK&&!(4&n))throw Un("EACCES","access",r);if(t&zn.W_OK&&!(2&n))throw Un("EACCES","access",r);if(t&zn.X_OK&&!(1&n))throw Un("EACCES","access",r)}async chmod(e,t){const r=Vn(e,"path"),i=((e,t)=>{if("number"!=typeof e||!Number.isInteger(e))throw new TypeError(`The "${t}" argument must be an integer`);if(e<0||e>4095)throw new RangeError(`The "${t}" argument must be between 0o0000 and 0o7777`);return e})(t,"mode"),s=await this._readMetadata(r);await this._writeMetadata(r,{...s,mode:i})}async chown(e,t,r){const i=Vn(e,"path"),s=Jn(t,"uid"),n=void 0===r?s:Jn(r,"gid"),o=await this._readMetadata(i);await this._writeMetadata(i,{...o,uid:s,gid:n})}async utimes(e,t,r){const i=Vn(e,"path"),s=Jn(t,"atimeMs"),n=void 0===r?s:Jn(r,"mtimeMs"),o=await this._readMetadata(i);await this._writeMetadata(i,{...o,atimeMs:s,mtimeMs:n})}async truncate(e,t=0){const r=Vn(e,"path"),i=Jn(t,"length"),s=await this.readFile(r),n=new Uint8Array(i);n.set(s.subarray(0,i)),await this.writeFile(r,n)}async realpath(e){const t=Vn(e,"path");return await this.__stat(t),`/${Zn(t).join("/")}`}async open(e,t="r"){const r=Vn(e,"path");if("string"!=typeof t)throw new TypeError('The "flags" argument must be of type string');return t.includes("w")?await this.writeFile(r,new Uint8Array(0)):t.includes("a")?await this.writeFile(r,new Uint8Array(0),{append:!0}):await this.__stat(r),new Qn(this,r,t)}async exists(e){return void 0!==await this.__stat(e,{throwIfNoEntry:!1})}#wu(e,t){return Un("ENOSYS",e,t,`${e}() is not implemented by ${this.constructor.name}`)}#bu(e,t){return e===this.#gu.uid?6:t===this.#gu.gid||this.#gu.groups.includes(t)?3:0}},to=class extends eo{#vu;constructor(e={}){super(e),this.#vu=e.root??null}static get capabilities(){return Object.freeze({permissions:!1,ownership:!1,symlinks:!1,timestamps:!1,atomicRename:!1,seekableHandles:!1})}async _resolveRoot(){if(null!==this.#vu)return this.#vu;if("undefined"==typeof navigator||"function"!=typeof navigator.storage?.getDirectory)throw Un("ENOSYS","getDirectory","/","OPFS is not available in this environment");return this.#vu=await navigator.storage.getDirectory(),this.#vu}async#Eu(e,t,r,i){let s=await this._resolveRoot();for(const n of e)try{s=await s.getDirectoryHandle(n,{create:t})}catch(e){throw qn(e,r,i)}return s}async#Tu(e,t){const r=Zn(e),i=r.pop();if(void 0===i)throw Un("EINVAL",t,e,"the root has no parent");return{parent:await this.#Eu(r,!1,t,e),name:i}}async#Su(e,t){const r=[];try{for await(const[t,i]of e.entries())r.push({name:t,kind:i.kind})}catch(e){throw qn(e,"readdir",t)}return r.sort((e,t)=>e.name.localeCompare(t.name))}async#xu(e,t){for await(const[r,i]of e.entries()){if("directory"===i.kind){const e=await t.getDirectoryHandle(r,{create:!0});await this.#xu(i,e);continue}const e=i,s=await e.getFile(),n=await t.getFileHandle(r,{create:!0}),o=await n.createWritable();await o.write(await s.arrayBuffer()),await o.close()}}async _readFile(e){const{parent:t,name:r}=await this.#Tu(e,"readFile");try{const e=await t.getFileHandle(r),i=await e.getFile();return new Uint8Array(await i.arrayBuffer())}catch(t){throw qn(t,"readFile",e,"EISDIR")}}async _writeFile(e,t,r){const{parent:i,name:s}=await this.#Tu(e,"writeFile"),n=t;try{const e=await i.getFileHandle(s,{create:!0}),t=await e.createWritable({keepExistingData:!0===r.append});if(!0===r.append){const r=await e.getFile();await t.write({type:"write",position:r.size,data:n})}else await t.write(n);await t.close()}catch(t){throw qn(t,"writeFile",e)}}async _readdir(e){const t=await this.#Eu(Zn(e),!1,"readdir",e);return this.#Su(t,e)}async _mkdir(e,t){const r=Zn(e);if(0===r.length){if(!0===t.recursive)return;throw Un("EEXIST","mkdir",e)}if(!0===t.recursive)return void await this.#Eu(r,!0,"mkdir",e);const{parent:i,name:s}=await this.#Tu(e,"mkdir");if((await this.#Su(i,e)).some(e=>e.name===s))throw Un("EEXIST","mkdir",e);try{await i.getDirectoryHandle(s,{create:!0})}catch(t){throw qn(t,"mkdir",e)}}async _rm(e,t){const{parent:r,name:i}=await this.#Tu(e,"rm"),s=(await this.#Su(r,e)).find(e=>e.name===i);if(void 0===s){if(!0===t.force)return;throw Un("ENOENT","rm",e)}if("directory"===s.kind&&!0!==t.recursive){const t=await r.getDirectoryHandle(i);if((await this.#Su(t,e)).length>0)throw Un("ENOTEMPTY","rm",e)}try{await r.removeEntry(i,{recursive:!0===t.recursive})}catch(t){throw qn(t,"rm",e)}}async _stat(e){const t=Zn(e);if(0===t.length)return{name:"/",kind:"directory",size:0,mtimeMs:Date.now()};const r=t.pop(),i=await this.#Eu(t,!1,"stat",e),s=(await this.#Su(i,e)).find(e=>e.name===r);if(void 0===s)return;if("directory"===s.kind)return{name:r,kind:"directory",size:0,mtimeMs:Date.now()};const n=await i.getFileHandle(r),o=await n.getFile();return{name:r,kind:"file",size:o.size,mtimeMs:o.lastModified}}async _rename(e,t){const r=await this._stat(e);if(void 0===r)throw Un("ENOENT","rename",e);if("directory"===r.kind){const r=await this.#Eu(Zn(e),!1,"rename",e),i=await this.#Eu(Zn(t),!0,"rename",t);await this.#xu(r,i)}else{const r=await this._readFile(e);await this._writeFile(t,r,{append:!1})}await this._rm(e,{recursive:!0,force:!0})}async _copyFile(e,t){const r=await this._readFile(e);await this._writeFile(t,r,{append:!1})}},ro="tiny-fs";class io extends to{#Au;#Cu;#Iu=null;constructor(e={}){super(e);const t=(e=>{if(void 0===e)return{name:ro,options:{}};if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError('The "bucket" option must be of type object');const{name:t,durability:r,persisted:i,quota:s,expires:n}=e;if(void 0!==t&&("string"!=typeof t||0===t.length))throw new TypeError('The "bucket.name" option must be a non-empty string');if(void 0!==r&&"strict"!==r&&"relaxed"!==r)throw new TypeError('The "bucket.durability" option must be "strict" or "relaxed"');if(void 0!==i&&"boolean"!=typeof i)throw new TypeError('The "bucket.persisted" option must be of type boolean');if(void 0!==s){if(!Number.isInteger(s))throw new TypeError('The "bucket.quota" option must be an integer');if(s<0)throw new RangeError('The "bucket.quota" option must not be negative')}if(void 0!==n){if(!Number.isInteger(n))throw new TypeError('The "bucket.expires" option must be an integer');if(n<0)throw new RangeError('The "bucket.expires" option must not be negative')}return{name:t??ro,options:{durability:r,persisted:i,quota:s,expires:n}}})(e.bucket);this.#Au=t.name,this.#Cu=t.options}static get isSupported(){return"undefined"!=typeof navigator&&"object"==typeof navigator.storageBuckets&&null!==navigator.storageBuckets}static async listBuckets(){return io.#ku("keys"),navigator.storageBuckets.keys()}static async deleteBucket(e){if("string"!=typeof e||0===e.length)throw new TypeError('The "name" argument must be a non-empty string');return io.#ku("delete"),navigator.storageBuckets.delete(e)}get bucketName(){return this.#Au}async _resolveRoot(){if(null!==this.#Iu)return this.#Iu;io.#ku("open");const e=await navigator.storageBuckets.open(this.#Au,this.#Cu);return this.#Iu=await e.getDirectory(),this.#Iu}static#ku(e){if(!io.isSupported)throw Un("ENOSYS",e,"/","the Storage Buckets API is not available in this environment")}}const so=io;function no(e,t="value"){if("string"!=typeof e||0===e.length)throw new TypeError(`The "${t}" argument must be a non-empty string.`)}class oo{#Du;#Mu;#Lu=new ae;#Nu=new ae;#xr=null;#_u=!1;constructor({storeName:e,openDatabase:t}){if(no(e,"storeName"),"function"!=typeof t)throw new TypeError('The "openDatabase" option must be a function.');this.#Du=e,this.#Mu=t}get storeName(){return this.#Du}get isReady(){return this.#_u}get[Symbol.toStringTag](){return this.constructor.name}hydrate(){return this.#xr??=this.#To(),this.#xr}_action(e){return this.#Nu.enqueue(e)}_write(e){return this.#Lu.enqueue(e)}async _persist(e){const t=await this.#Mu();await new Promise((r,i)=>{const s=t.transaction(this.#Du,"readwrite").objectStore(this.#Du).put(e);s.onsuccess=()=>r(void 0),s.onerror=()=>i(s.error)})}async _remove(e){const t=await this.#Mu();await new Promise((r,i)=>{const s=t.transaction(this.#Du,"readwrite").objectStore(this.#Du).delete(e);s.onsuccess=()=>r(void 0),s.onerror=()=>i(s.error)})}async _clear(){const e=await this.#Mu();await new Promise((t,r)=>{const i=e.transaction(this.#Du,"readwrite").objectStore(this.#Du).clear();i.onsuccess=()=>t(void 0),i.onerror=()=>r(i.error)})}async#To(){const e=await this.#Mu(),t=await oo.#Ru(e,this.#Du);this._load(t),this.#_u=!0}_load(e){throw new Error(`The "_load" method of "${this.constructor.name}" is not implemented.`)}static#Ru(e,t){return new Promise((r,i)=>{const s=e.transaction(t,"readonly").objectStore(t).getAll();s.onsuccess=()=>r(s.result),s.onerror=()=>i(s.error)})}}class ao extends oo{#ju;#Za=new Set;constructor({storeName:e,openDatabase:t,validate:r=null}){if(super({storeName:e,openDatabase:t}),null!==r&&"function"!=typeof r)throw new TypeError('The "validate" option must be a function or null.');this.#ju=r}get size(){return this.#Za.size}async has(e){no(e),this.#Pu(e),await this.hydrate();let t=!1;return await this._action(async()=>{t=this.#Za.has(e)}),t}async add(e){no(e),this.#Pu(e),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Za.has(e)||(await this._write(()=>this._persist({value:e,timestamp:Date.now()})),this.#Za.add(e),t=!0)}),t}async delete(e){no(e),this.#Pu(e),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Za.has(e)&&(await this._write(()=>this._remove(e)),this.#Za.delete(e),t=!0)}),t}async clear(){await this.hydrate(),await this._action(async()=>{await this._write(()=>this._clear()),this.#Za.clear()})}async toArray(){return await this.hydrate(),[...this.#Za]}async toJSON(){return this.toArray()}async*values(){await this.hydrate();for(const e of[...this.#Za])yield e}keys(){return this.values()}async*entries(){for await(const e of this.values())yield[e,e]}[Symbol.asyncIterator](){return this.values()}async forEach(e,t){if("function"!=typeof e)throw new TypeError('The "callbackFn" argument must be a function.');await this.hydrate();for(const r of[...this.#Za])e.call(t,r,r,this)}async union(...e){await this.hydrate();const t=new Set(this.#Za);for(const r of e){const e=await ao.#Ou(r);for(const r of e)t.add(r)}return t}async intersection(e){const t=await ao.#Ou(e);await this.hydrate();const r=new Set;for(const e of this.#Za)t.has(e)&&r.add(e);return r}async difference(e){const t=await ao.#Ou(e);await this.hydrate();const r=new Set;for(const e of this.#Za)t.has(e)||r.add(e);return r}async symmetricDifference(e){const t=await ao.#Ou(e);await this.hydrate();const r=new Set;for(const e of this.#Za)t.has(e)||r.add(e);for(const e of t)this.#Za.has(e)||r.add(e);return r}async isSubsetOf(e){const t=await ao.#Ou(e);await this.hydrate();for(const e of this.#Za)if(!t.has(e))return!1;return!0}async isSupersetOf(e){const t=await ao.#Ou(e);await this.hydrate();for(const e of t)if(!this.#Za.has(e))return!1;return!0}async isDisjointFrom(e){const t=await ao.#Ou(e);await this.hydrate();for(const e of this.#Za)if(t.has(e))return!1;return!0}_load(e){for(const t of e.sort((e,t)=>e.timestamp-t.timestamp))this.#Za.add(t.value)}static async#Ou(e){if(e instanceof ao)return new Set(await e.toArray());if(e instanceof Set)return new Set(e);if(Array.isArray(e))return new Set(e);throw new TypeError('The "other" argument must be a TinySetDb, a Set, or an Array.')}#Pu(e){if(null!==this.#ju&&!this.#ju(e))throw new TypeError(`The value is rejected by the "${this.storeName}" table validator.`)}}class lo extends oo{#ju;#Za=new Map;constructor({storeName:e,openDatabase:t,validate:r=null}){if(super({storeName:e,openDatabase:t}),null!==r&&"function"!=typeof r)throw new TypeError('The "validate" option must be a function or null.');this.#ju=r}get size(){return this.#Za.size}async has(e){no(e,"key"),await this.hydrate();let t=!1;return await this._action(async()=>{t=this.#Za.has(e)}),t}async get(e){let t;return no(e,"key"),await this.hydrate(),await this._action(async()=>{t=this.#Za.get(e)}),t}async set(e,t){return no(e,"key"),this.#Pu(e,t),await this.hydrate(),await this._action(async()=>{await this._write(()=>this._persist({key:e,value:t,timestamp:Date.now()})),this.#Za.set(e,t)}),this}async delete(e){no(e,"key"),await this.hydrate();let t=!1;return await this._action(async()=>{this.#Za.has(e)&&(await this._write(()=>this._remove(e)),this.#Za.delete(e),t=!0)}),t}async clear(){await this.hydrate(),await this._action(async()=>{await this._write(()=>this._clear()),this.#Za.clear()})}async toArray(){return await this.hydrate(),[...this.#Za.entries()]}async toJSON(){return this.toArray()}async*keys(){await this.hydrate();for(const e of[...this.#Za.keys()])yield e}async*values(){await this.hydrate();for(const e of[...this.#Za.values()])yield e}async*entries(){await this.hydrate();for(const e of[...this.#Za.entries()])yield e}[Symbol.asyncIterator](){return this.entries()}async forEach(e,t){if("function"!=typeof e)throw new TypeError('The "callbackFn" argument must be a function.');await this.hydrate();for(const[r,i]of[...this.#Za])e.call(t,i,r,this)}_load(e){for(const t of e.sort((e,t)=>e.timestamp-t.timestamp))this.#Za.set(t.key,t.value)}#Pu(e,t){if(null!==this.#ju&&!this.#ju(e,t))throw new TypeError(`The entry is rejected by the "${this.storeName}" table validator.`)}}class ho{#eo;#ee;#$u=new Map;#Hu;#xr;constructor(e,t){if(no(e,"name"),!Array.isArray(t)||0===t.length)throw new TypeError('The "migrations" argument must be a non-empty array.');this.#eo=e,this.#ee=t.length;const r=t.map((e,t)=>ho.#Fu(e,t)),i=ho.#zu(r);this.#Hu=ho.#Mu(e,r);for(const e of i.values()){const t={storeName:e.name,validate:e.validate,openDatabase:()=>this.#Hu};"map"===e.type?this.#$u.set(e.name,new lo(t)):this.#$u.set(e.name,new ao(t))}this.#xr=this.#Hu.then(()=>Promise.all([...this.#$u.values()].map(e=>e.hydrate())).then(()=>{})),this.#xr.catch(()=>{})}get name(){return this.#eo}get version(){return this.#ee}get tableNames(){return[...this.#$u.keys()]}get ready(){return this.#xr}tableSet(e){no(e,"tableName");const t=this.#$u.get(e);if(void 0===t)throw new RangeError(`The "${e}" table is not declared in this database.`);if(!(t instanceof ao))throw new Error(`The "${e}" table is not a Set instance.`);return t}tableMap(e){no(e,"tableName");const t=this.#$u.get(e);if(void 0===t)throw new RangeError(`The "${e}" table is not declared in this database.`);if(!(t instanceof lo))throw new Error(`The "${e}" table is not a Map instance.`);return t}has(e){return no(e,"tableName"),this.#$u.has(e)}async close(){(await this.#Hu).close()}static#Bu(e){if("string"==typeof e)return{name:e,type:"set",validate:null};if("object"!=typeof e||null===e)throw new TypeError('Each table must be a string or an object with a "name" property.');const{name:t,type:r,validate:i=null}=e;if(no(t,"table.name"),"set"!==r&&"map"!==r)throw new TypeError(`The "type" option of the "${t}" table must be "set" or "map".`);if(null!==i&&"function"!=typeof i)throw new TypeError(`The "validate" option of the "${t}" table must be a function.`);return{name:t,type:r,validate:i}}static#Mu(e,t){return new Promise((r,i)=>{if("undefined"==typeof indexedDB)return void i(new ReferenceError("IndexedDB is not available in the current environment."));const s=indexedDB.open(e,t.length);s.onupgradeneeded=e=>{try{for(let r=e.oldVersion+1;r<=t.length;r+=1)ho.#Wu(s.result,t[r-1])}catch(e){i(e),s.transaction?.abort()}},s.onsuccess=()=>{const e=s.result;e.onversionchange=()=>e.close(),r(e)},s.onerror=()=>i(s.error)})}static#Wu(e,t){for(const r of t.delete)e.objectStoreNames.contains(r)&&e.deleteObjectStore(r);for(const r of t.create)e.createObjectStore(r.name,{keyPath:"map"===r.type?"key":"value"})}static#Fu(e,t){if("object"!=typeof e||null===e)throw new TypeError(`The migration at index ${t} must be an object.`);const{create:r=[],delete:i=[]}=e;if(!Array.isArray(r))throw new TypeError(`The "create" list of the migration at index ${t} must be an array.`);if(!Array.isArray(i))throw new TypeError(`The "delete" list of the migration at index ${t} must be an array.`);for(const e of i)no(e,`migrations[${t}].delete[]`);return{create:r.map(e=>ho.#Bu(e)),delete:[...i]}}static#zu(e){const t=new Map;for(const r of e){for(const e of r.delete)t.delete(e);for(const e of r.create){if(t.has(e.name))throw new Error(`The "${e.name}" table is created twice.`);t.set(e.name,e)}}return t}}class uo{static#Il=Ms;static get PUSH_TYPE(){return uo.#Il}static#Uu=null;static#qu=null;static isSupported(){return"undefined"!=typeof globalThis&&"serviceWorker"in navigator&&"PushManager"in globalThis&&"Notification"in globalThis}static get permission(){return uo.isSupported()?Notification.permission:"denied"}static async requestPermission(){if(!uo.isSupported())throw new Error("[TinyPushManager] Push API is not supported in this browser.");return await _s()}static decodeVapidKey(e){if("string"!=typeof e||""===e)throw new TypeError("[TinyPushManager] decodeVapidKey: base64 must be a non-empty string.");if(uo.#qu===e&&uo.#Uu)return uo.#Uu;const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t),i=Uint8Array.from(r,e=>e.charCodeAt(0));return uo.#Uu=i,uo.#qu=e,i}#Ml;#Vu;#Ku;#Gu;#An;#Ju={status:"unsubscribed",subscription:null,error:null};constructor(e){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError("[TinyPushManager] constructor: options must be a non-null object.");const{registration:t,vapidPublicKey:r,endpoints:i={},fetch:s,onChange:n}=e;if("object"!=typeof t||null===t)throw new TypeError("[TinyPushManager] constructor: options.registration is required.");if("string"!=typeof r||""===r)throw new TypeError("[TinyPushManager] constructor: options.vapidPublicKey is required.");if(void 0!==i.subscribe&&"string"!=typeof i.subscribe)throw new TypeError("[TinyPushManager] constructor: endpoints.subscribe must be a string.");if(void 0!==i.unsubscribe&&"string"!=typeof i.unsubscribe)throw new TypeError("[TinyPushManager] constructor: endpoints.unsubscribe must be a string.");if(void 0!==n&&"function"!=typeof n)throw new TypeError("[TinyPushManager] constructor: onChange must be a function.");this.#Ml=t,this.#Vu=r,this.#Ku=i,this.#Gu=s??globalThis.fetch.bind(globalThis),this.#An=n??null}get state(){return Object.freeze({...this.#Ju})}async getSubscription(){return uo.isSupported()?this.#Ml.pushManager.getSubscription():null}async subscribe(e={}){if(!uo.isSupported())throw new Error("[TinyPushManager] Push API is not supported in this browser.");this.#Yu({status:"pending",error:null});const t=await uo.requestPermission();if("granted"!==t)throw this.#Yu({status:"denied",subscription:null}),new Error(`[TinyPushManager] Notification permission was not granted: ${t}.`);const r=await this.getSubscription()??await this.#Ml.pushManager.subscribe({...e,userVisibleOnly:!0,applicationServerKey:uo.decodeVapidKey(this.#Vu)});return await this.#Xu(r),this.#Yu({status:"subscribed",subscription:r,error:null}),r}async unsubscribe(){const e=await this.getSubscription();return e?(this.#Ku.unsubscribe&&await this.#Gu(this.#Ku.unsubscribe,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoint:e.endpoint})}).catch(()=>{}),await e.unsubscribe(),this.#Yu({status:"unsubscribed",subscription:null,error:null}),!0):(this.#Yu({status:"unsubscribed",subscription:null}),!1)}async syncWithServer(){const e=await this.getSubscription();return e?(await this.#Xu(e),this.#Yu({status:"subscribed",subscription:e,error:null}),e):null}async#Xu(e){if(!this.#Ku.subscribe)return;const t=await this.#Gu(this.#Ku.subscribe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.toJSON())});if(!t.ok)throw new Error(`[TinyPushManager] Failed to upload subscription: ${t.status}.`)}#Yu(e){this.#Ju={...this.#Ju,...e},this.#An?.(this.state)}}const co=uo,mo=class{#Qu;#Zu=0;#ec=0;#tc=0;#rc=0;#ic=0;#sc=0;constructor(e=0){if("number"!=typeof e||Number.isNaN(e)||e<0)throw new RangeError('The "total" argument must be a positive number.');this.#Qu=e}get total(){return this.#Qu}set total(e){if("number"!=typeof e||Number.isNaN(e)||e<0)throw new RangeError('The "total" value must be a positive number.');this.#Qu=e}get loaded(){return this.#Zu}get remaining(){return this.#Qu>0?Math.max(0,this.#Qu-this.#Zu):0}get percent(){return this.#Qu>0?Math.min(100,this.#Zu/this.#Qu*100):0}get rate(){return this.#sc}get chunks(){return this.#ec}get elapsed(){return 0===this.#tc?0:performance.now()-this.#tc}get eta(){return this.#sc<=0||this.#Qu<=0?0:this.remaining/this.#sc*1e3}start(){return this.#tc=performance.now(),this.#rc=this.#tc,this}push(e){if("number"!=typeof e||Number.isNaN(e)||e<0)throw new RangeError('The "bytes" argument must be a positive number.');const t=performance.now();this.#Zu+=e,this.#ec+=1;const r=t-this.#rc;if(r>0){const e=(this.#Zu-this.#ic)/r*1e3;this.#sc=0===this.#sc?e:.7*this.#sc+.3*e}return this.#rc=t,this.#ic=this.#Zu,this}reset(){return this.#Zu=0,this.#ec=0,this.#sc=0,this.#ic=0,this.#tc=0,this.#rc=0,this}snapshot(){return{loaded:this.#Zu,total:this.#Qu,remaining:this.remaining,percent:this.percent,rate:this.#sc,elapsed:this.elapsed,eta:this.eta,chunks:this.#ec}}};function po(e){if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}class fo{static Strategy=Object.freeze({AUTO:"auto",MANUAL:"manual",TTL:"ttl"});static#Qa=new Set;static#nc=new Map;#oc=0;#ac=new Map;#lc=new Map;#hc;#uc;#el;#cc;#dc;#mc=0;#pc=0;#fc=null;#u=!1;get misses(){return this.#pc}get ignoreSearch(){return this.#dc}get strategy(){return this.#cc}get ttl(){return this.#el}get maxItems(){return this.#hc}get maxBytes(){return this.#uc}get evictions(){return this.#oc}constructor(e={}){if(!po(e))throw new TypeError('The "options" argument must be a plain object.');const{maxItems:t=1/0,maxBytes:r=1/0,ttl:i=0,strategy:s=fo.Strategy.MANUAL,ignoreSearch:n=!1,sweepInterval:o=0}=e;if("number"!=typeof t||Number.isNaN(t)||t<1)throw new RangeError('The "maxItems" option must be a positive number.');if(t!==1/0&&!Number.isInteger(t))throw new RangeError('The "maxItems" option must be an integer or Infinity.');if("number"!=typeof r||Number.isNaN(r)||r<0)throw new RangeError('The "maxBytes" option must be a positive number.');if("number"!=typeof i||Number.isNaN(i)||i<0)throw new RangeError('The "ttl" option must be a positive number.');if(!Object.values(fo.Strategy).includes(s))throw new TypeError(`Unknown cache strategy: ${s}`);if("boolean"!=typeof n)throw new TypeError('The "ignoreSearch" option must be a boolean.');if("number"!=typeof o||Number.isNaN(o)||o<0)throw new RangeError('The "sweepInterval" option must be a positive number.');this.#hc=t,this.#uc=r,this.#el=i,this.#cc=s,this.#dc=n,fo.#Qa.add(this),o>0&&(this.#fc=setInterval(()=>this.prune(),o),"function"==typeof this.#fc.unref&&this.#fc.unref())}static get registry(){return Array.from(fo.#nc,([e,t])=>({key:e,...t}))}static get instances(){return Array.from(fo.#Qa)}static get size(){return fo.#nc.size}static get bytes(){let e=0;for(const t of fo.#nc.values())e+=t.size;return e}static has(e,t=!1){return fo.#nc.has(fo.#yc(e,t))}static clear(){for(const e of fo.#nc.values())URL.revokeObjectURL(e.objectUrl);fo.#nc.clear()}static destroyAll(){for(const e of Array.from(fo.#Qa))e.destroy()}get size(){return this.#ac.size}get links(){return this.#lc.size}get bytes(){let e=0;for(const t of this.#ac.values())e+=t.size;return e}get destroyed(){return this.#u}get stats(){let e=0;for(const t of this.#ac.values())e+=t.refs;return{size:this.#ac.size,bytes:this.bytes,refs:e,hits:this.#mc,misses:this.#pc,evictions:this.#oc,links:this.#lc.size,instances:fo.#Qa.size,blobs:fo.#nc.size}}entries(){return this.#gc(),Array.from(this.#ac.values(),e=>({...e,metadata:{...e.metadata}}))}set(e,t,r=!1,i={},s=null){if(this.#gc(),!(t instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');if("boolean"!=typeof r)throw new TypeError('The "pinned" argument must be a boolean.');if(!po(i))throw new TypeError('The "metadata" argument must be a plain object.');if(null!==s&&"string"!=typeof s)throw new TypeError('The "parent" argument must be a string or null.');const n=this.#wc(e);this.#bc(n,!1);const o=fo.#vc(n,t),a=Date.now(),l={key:n,url:e,blob:t,objectUrl:o.objectUrl,size:t.size,type:t.type,refs:0,createdAt:a,lastAccess:a,expiresAt:this.#el>0?a+this.#el:0,pinned:Boolean(r),parent:s,metadata:{...i}};return this.#ac.set(n,l),null!==s&&this.#Ec(s,n),this.#Tc(),l}get(e){this.#gc();const t=this.#wc(e),r=this.#ac.get(t);return r?this.#Sc(r)?(this.delete(t),this.#pc+=1,null):(r.lastAccess=Date.now(),this.#mc+=1,r):(this.#pc+=1,null)}has(e){this.#gc();const t=this.#ac.get(this.#wc(e));return void 0!==t&&!this.#Sc(t)}acquire(e){this.#gc();const t=this.get(e);return t?(t.refs+=1,t):null}release(e){this.#gc();const t=this.#wc(e),r=this.#ac.get(t);return!!r&&(r.refs=Math.max(0,r.refs-1),0===r.refs&&this.#cc===fo.Strategy.AUTO&&this.delete(t),!0)}delete(e){return this.#gc(),this.#bc(this.#wc(e),!0)}children(e){return Array.from(this.#lc.get(this.#wc(e))??[])}#bc(e,t){if("string"!=typeof e)throw new TypeError('The "key" argument must be a string.');if("boolean"!=typeof t)throw new TypeError('The "cascade" argument must be a boolean.');const r=this.#ac.get(e);if(!r)return!1;if(this.#ac.delete(e),fo.#xc(e),this.#lc.delete(e),null===r.parent)return!0;const i=this.#lc.get(r.parent);if(!i)return!0;if(i.delete(e),i.size>0)return!0;this.#lc.delete(r.parent);const s=this.#ac.get(r.parent);return t&&s&&0===s.refs&&this.#bc(r.parent,!0),!0}#Ec(e,t){if("string"!=typeof e)throw new TypeError('The "parent" argument must be a string.');if("string"!=typeof t)throw new TypeError('The "child" argument must be a string.');let r=this.#lc.get(e);r||(r=new Set,this.#lc.set(e,r)),r.add(t)}peek(e){if(this.#gc(),"string"!=typeof e)throw new TypeError('The "url" argument must be a string.');const t=this.#ac.get(this.#wc(e));return!t||this.#Sc(t)?null:t}pin(e,t=!0){if(this.#gc(),"boolean"!=typeof t)throw new TypeError('The "value" argument must be a boolean.');const r=this.#ac.get(this.#wc(e));return!!r&&(r.pinned=t,!0)}prune(){this.#gc();const e=[];for(const[t,r]of this.#ac)this.#Sc(r)&&e.push(t);let t=0;for(const r of e)this.#bc(r,!0)&&(t+=1);return t}clear(){this.#gc();for(const e of Array.from(this.#ac.keys()))this.#ac.delete(e),fo.#xc(e);this.#lc.clear()}destroy(){this.#u||(this.#fc&&(clearInterval(this.#fc),this.#fc=null),this.clear(),fo.#Qa.delete(this),this.#u=!0)}#Tc(){if(this.#ac.size<=this.#hc&&this.bytes<=this.#uc)return;const e=Array.from(this.#ac.values()).filter(e=>!e.pinned&&0===e.refs&&!this.#lc.has(e.key)).sort((e,t)=>e.lastAccess-t.lastAccess);let t=this.bytes,r=this.#ac.size;for(const i of e){if(r<=this.#hc&&t<=this.#uc)break;this.delete(i.key),this.#oc+=1,t-=i.size,r-=1}}#Sc(e){if(null===e||"object"!=typeof e)throw new TypeError('The "entry" argument must be a MediaCacheEntry.');return e.expiresAt>0&&Date.now()>=e.expiresAt}#wc(e){return fo.#yc(e,this.#dc)}#gc(){if(this.#u)throw new Error("Cannot use a destroyed media cache.")}static#yc(e,t){if("string"!=typeof e)throw new TypeError('The "url" argument must be a string.');if("boolean"!=typeof t)throw new TypeError('The "ignoreSearch" argument must be a boolean.');if(!t)return e;const r=e.split("#")[0],i=r.indexOf("?");return-1===i?r:r.slice(0,i)}static#vc(e,t){if("string"!=typeof e)throw new TypeError('The "key" argument must be a string.');if(!(t instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');const r=fo.#nc.get(e);if(r)return r.refs+=1,r;const i={objectUrl:URL.createObjectURL(t),refs:1,size:t.size};return fo.#nc.set(e,i),i}static#xc(e){if("string"!=typeof e)throw new TypeError('The "key" argument must be a string.');const t=fo.#nc.get(e);t&&(t.refs-=1,t.refs>0||(URL.revokeObjectURL(t.objectUrl),fo.#nc.delete(e)))}}const yo=fo;class go{static#Ac=new Map;static get size(){return go.#Ac.size}static get keys(){return Array.from(go.#Ac.keys())}static get stats(){let e=0;for(const t of go.#Ac.values())e+=t.mirrors;return{pending:go.#Ac.size,mirrors:e}}static has(e){return go.#Ac.has(e)}static get(e){return go.#Ac.get(e)??null}static entries(){return Array.from(go.#Ac.values(),e=>({key:e.key,src:e.src,startedAt:e.startedAt,mirrors:e.mirrors,settled:e.settled}))}static open(e,t){if("string"!=typeof e)throw new TypeError('The "key" argument must be a string.');if("string"!=typeof t)throw new TypeError('The "src" argument must be a string.');const r=go.#Ac.get(e);if(r)return r;const i={key:e,src:t,startedAt:Date.now(),mirrors:0,settled:!1,sequence:0,events:[],subscribers:new Set,promise:null,resolve:()=>{},reject:()=>{}};return i.promise=new Promise((e,t)=>{i.resolve=t=>{i.settled=!0,e(t)},i.reject=e=>{i.settled=!0,t(e)}}),i.promise.catch(()=>{}),go.#Ac.set(e,i),i}static attach(e){const t=go.#Ac.get(e);return t?(t.mirrors+=1,t):null}static close(e){const t=go.#Ac.get(e);return!!t&&(t.settled||t.reject(new Error(`The mirrored download for "${t.src}" ended without a payload.`)),go.#Ac.delete(e))}static clear(){for(const e of go.#Ac.values())e.settled||e.reject(new Error("The mirror registry was cleared."));go.#Ac.clear()}static publish(e,t,r){if("string"!=typeof e)throw new TypeError('The "key" argument must be a string.');if("string"!=typeof t)throw new TypeError('The "name" argument must be a string.');if(!Array.isArray(r))throw new TypeError('The "args" argument must be an array.');const i=go.#Ac.get(e);if(!i)return 0;const s={seq:i.sequence,name:t,args:r,timestamp:performance.now()};i.sequence+=1,i.events.push(s);for(const e of i.subscribers)e(s);return i.subscribers.size}static subscribe(e,t){if("function"!=typeof t)throw new TypeError('The "handler" argument must be a function.');const r=go.#Ac.get(e);if(!r)return null;const{events:i}=r;for(let e=0;e<i.length;e+=1)t(i[e]);return r.subscribers.add(t),()=>r.subscribers.delete(t)}static history(e){return go.#Ac.get(e)?.events??[]}}const wo=go,bo=e().EventEmitter;class vo extends bo{static get TinyMediaMirror(){return wo}static MediaState=Object.freeze({IDLE:"idle",LOADING:"loading",LOADED:"loaded",ERROR:"error",DESTROYED:"destroyed"});static get tagName(){return""}#Cc;#Ju=vo.MediaState.IDLE;#Un=null;#Ic;#tc=0;#kc=0;#Dc=!1;#Mc=!1;#Lc=!1;#X=null;#Nc=null;#_c=null;#Rc=[];#Za=null;#jc=!1;#Pc=!1;#Oc=null;#$c=null;#Hc=null;#Fc=!1;#zc=0;#Bc=!1;#Wc=null;#Uc=!0;#qc=null;#Vc=null;#Kc=new Map;#Gc=!0;#Jc=!1;#Yc=!1;#Xc=null;#Gu=globalThis.fetch.bind(globalThis);#Qc={};#Zc=void 0;#ed={};#pu={src:"",type:"",width:0,height:0,duration:0,size:0,fromCache:!1,loadTime:0,timestamp:0,animation:null};constructor(e={}){if(null===e||"object"!=typeof e)throw new TypeError('The "options" argument must be an object.');const{src:t,timeout:r=1/0,element:i=null,autoReload:s=!1,originalSrc:n=!1,earlyDecode:o=!0,progressive:a=!0,useHeadRequest:l=!1,mirror:h=!0,body:u}=e;if(void 0!==t&&"string"!=typeof t)throw new TypeError('The "src" option must be a string.');if("number"!=typeof r||Number.isNaN(r)||r<0)throw new RangeError('The "timeout" option must be a positive number.');if(null!==i&&!(i instanceof HTMLElement))throw new TypeError('The "element" option must be an HTMLElement or null.');if("boolean"!=typeof n)throw new TypeError('The "originalSrc" option must be a boolean.');if("boolean"!=typeof o)throw new TypeError('The "earlyDecode" option must be a boolean.');if("boolean"!=typeof a)throw new TypeError('The "progressive" option must be a boolean.');if("boolean"!=typeof h)throw new TypeError('The "mirror" option must be a boolean.');if("boolean"!=typeof s)throw new TypeError('The "autoReload" option must be a boolean.');super();const c=this.constructor.tagName;if(i&&c&&i.tagName!==c)throw new TypeError(`The "element" option must be a <${c.toLowerCase()}> element.`);if(this.#Cc=t??i?.getAttribute("src")??"",this.#Ic=r,this.#Lc=s,this.#Fc=n,void 0!==e.cache&&null!==e.cache&&!(e.cache instanceof yo))throw new TypeError('The "cache" option must be a TinyMediaCache or null.');this.#Za=e.cache??null,this.#td(),this.#Dc=l,this.#Bc=o,this.#Uc=a,this.#Zc=u,this.#Gc=h,i&&(this.#Un=i,this.#rd())}static#id=new Set(["mirror","destroy","error","metadata"]);emit(e,...t){const r=super.emit(e,...t);return!this.#Xc||this.#Yc||vo.#id.has(e)||this.#Xc(e,t),r}get mirror(){return this.#Gc}get mirrored(){return this.#Jc}get response(){return this.#qc}get headResponse(){return this.#Vc}get useHeadRequest(){return this.#Dc}get objectUrl(){return this.#Hc}get src(){return this.#Cc}get internalSrc(){return this.#Oc}get originalSrc(){return this.#Fc}get earlyDecode(){return this.#Bc}get progressive(){return this.#Uc}set src(e){if("string"!=typeof e)throw new TypeError('The "src" value must be a string.');this.#sd(e)&&this.#Un&&this.#Un.getAttribute("src")!==e&&(e?this.#Un.setAttribute("src",e):this.#Un.removeAttribute("src"),this._flushMutations())}get aborted(){return this.#Pc}get cacheAcquired(){return this.#jc}get autoReload(){return this.#Lc}get cacheHint(){return this.#Mc}get endTime(){return this.#kc}get startTime(){return this.#tc}get state(){return this.#Ju}get element(){return this.#Un}get metadata(){return{...this.#pu,httpHeaders:{...this.#pu.httpHeaders}}}get resourceSize(){return this.#zc}get isLoading(){return this.#Ju===vo.MediaState.LOADING}get isLoaded(){return this.#Ju===vo.MediaState.LOADED}get hasError(){return this.#Ju===vo.MediaState.ERROR}get progress(){return this.#Nc}get cache(){return this.#Za}set cache(e){if(null!==e&&!(e instanceof yo))throw new TypeError('The "cache" value must be a TinyMediaCache or null.');this.#Za=e}get signal(){if(!this.#_c)throw new Error("Signal does not exist.");return this.#_c}get body(){return this.#Zc}set body(e){this.#Zc=e}get pending(){return wo.has(this.#nd(this.#Cc))}get _fetch(){return this.#Gu}set _fetch(e){if("function"!=typeof e)throw new TypeError('The "fetch" value must be a function.');this.#Gu=e}get _requestInit(){return this.#Qc}set _requestInit(e){this.#Qc=e}isCached(e=this.#Cc){if("string"!=typeof e)throw new TypeError('The "src" argument must be a string.');return!!this.#Za&&this.#Za.has(e)}get cached(){return this.isCached()}peekCache(e=this.#Cc){if("string"!=typeof e)throw new TypeError('The "src" argument must be a string.');return this.#Za?this.#Za.peek(e):null}_insertDecoder(e,t){if("string"!=typeof e||0===e.length)throw new TypeError('The "mime" argument must be a non-empty string.');if("function"!=typeof t)throw new TypeError('The "callback" argument must be a function.');this.#Kc.set(e,t)}_createProgress(e=0){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError('The "total" argument must be a finite number.');if(e<0)throw new RangeError('The "total" argument must be a non-negative number.');return this.#Nc=new mo(e).start(),this.#Nc}_emitProgress(){this.#Nc&&this.emit("progress",this.#Nc.snapshot())}_emitMetadata(e,t){if(null===e||"object"!=typeof e)throw new TypeError('The "patch" argument must be an object.');if("string"!=typeof t||0===t.length)throw new TypeError('The "type" argument must be a non-empty string.');const r=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));this.#ed={...this.#ed,...r},this.#pu={...this.#pu,...r},this.#Xc?.("metadata",[r,t]),this.emit("metadata",this.metadata,t)}_on(e,t,r){if(!(e instanceof HTMLElement))throw new TypeError('The "element" argument must be an HTMLElement.');if("string"!=typeof t||0===t.length)throw new TypeError('The "type" argument must be a non-empty string.');if("function"!=typeof r)throw new TypeError('The "handler" argument must be a function.');e.addEventListener(t,r),this.#Rc.push(()=>e.removeEventListener(t,r))}_forwardEvents(e,t){if(!Array.isArray(t))throw new TypeError('The "events" argument must be an array of strings.');for(const r of t){if("string"!=typeof r||0===r.length)throw new TypeError('Every entry of "events" must be a non-empty string.');this._on(e,r,e=>{this.emit(r,e)})}}_detachEvents(){for(const e of this.#Rc)e();this.#Rc=[]}async load(){if(this.#Ju===vo.MediaState.DESTROYED)throw new Error("Cannot load a destroyed media loader.");if(this.#Ju===vo.MediaState.LOADING)throw new Error("The media is already loading.");if(!this.#Cc)throw new Error("Cannot load media without a source.");this._detachEvents(),this._releaseFromCache(),this.#td(),this.#od(),this.#ad(),this._createProgress(0),this.#Yu(vo.MediaState.LOADING),this.emit("loadstart",{src:this.#Cc});try{return await this.#ld(this._startLoad()),this.#kc=performance.now(),this.#pu=this.#hd(),this.#Yu(vo.MediaState.LOADED),this.emit("loaded",this.#pu),this.#pu}catch(e){throw this.#kc=performance.now(),this.#Pc?(this.#Pc=!1,this.#Yu(vo.MediaState.IDLE),this.emit("abort",{src:this.#Cc})):(this.#Yu(vo.MediaState.ERROR),this.#ud(e)),e}finally{this.emit("loadend",{src:this.#Cc,state:this.#Ju})}}async reload(){if(this.#Ju===vo.MediaState.LOADING)throw new Error("Cannot reload while the media is loading.");if(this.#Ju===vo.MediaState.DESTROYED)throw new Error("Cannot reload a destroyed media loader.");return this.#Nc?.reset(),this.#Ju=vo.MediaState.IDLE,this.load()}abort(){return this.#Ju===vo.MediaState.LOADING&&(this.#Pc=!0,this.#_c&&this.#_c.abort(),!0)}mount(e){if(!(e instanceof HTMLElement))throw new TypeError('The "container" argument must be an HTMLElement.');if(!this.#Un)throw new Error("Cannot mount before the media element is created.");return e.appendChild(this.#Un),this}destroy(){this.#Ju!==vo.MediaState.DESTROYED&&(this.#Ju=vo.MediaState.DESTROYED,this.#_c&&this.#_c.abort(),this._cleanup(),this._detachEvents(),this.#cd(),null!==this.#$c&&(clearTimeout(this.#$c),this.#$c=null),this.#od(),this._releaseFromCache(),this.#Kc.clear(),this.emit("destroy"),this.removeAllListeners(),this.#Un=null)}_resolveElement(){return this.#Un||(this.#Un=this._createElement()),this.#rd(),this.#Un}_setElement(e){if(!(e instanceof HTMLElement))throw new TypeError('The "element" argument must be an HTMLElement.');this.#Un=e,this.#rd()}_setCacheHint(e){if("boolean"!=typeof e)throw new TypeError('The "value" argument must be a boolean.');this.#Mc=Boolean(e)}_setInternalSrc(e){if(null!==e&&"string"!=typeof e)throw new TypeError('The "url" argument must be a string or null.');this.#Oc=e,this.#dd(),this._flushMutations(),this.emit("srctransition",{src:this.#Cc,internalSrc:e})}#dd(){const e=this.#Un;e&&this.#Fc&&(this.#Oc?e.setAttribute("original-src",this.#Cc):e.removeAttribute("original-src"))}_waitForMedia(e,t="loadeddata"){if(!(e instanceof HTMLElement))throw new TypeError('The "element" argument must be an HTMLElement.');if("string"!=typeof t)throw new TypeError('The "readyEvent" argument must be a string.');if(!this.#_c)throw new Error("Signal does not exist to wait for media.");const{signal:r}=this.#_c;return new Promise((i,s)=>{const n=()=>{l(),i(void 0)},o=()=>{l(),s(new Error(`Failed to load media: ${this.#Cc}`))},a=()=>{l(),s(new DOMException("The media load was aborted.","AbortError"))},l=()=>{e.removeEventListener(t,n),e.removeEventListener("error",o),r.removeEventListener("abort",a)};e.addEventListener(t,n),e.addEventListener("error",o),r.addEventListener("abort",a,{once:!0})})}_cacheBlob(e){if(!(e instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');if(this._setResourceSize(e.size),this.#Za){const t=this.#Za.get(this.#Cc);if(t)return this.#Za.acquire(this.#Cc),this.#jc=!0,t.objectUrl;const r=this.#Za.set(this.#Cc,e,!1,this.#ed);return this.#Za.acquire(this.#Cc),this.#jc=!0,this.emit("cachemiss",r),r.objectUrl}return this._createObjectUrl(e)}async _downloadStream(e,t,r=0,i=null){if("string"!=typeof e)throw new TypeError('The "url" argument must be a string.');if(!Number.isInteger(r)||r<0)throw new RangeError('The "startByte" argument must be a non-negative integer.');if(void 0!==t&&"function"!=typeof t)throw new TypeError('The "onChunk" argument must be a function or undefined.');const s=this.#nd(e),n=this.#Gc&&0===r,o=n?wo.attach(s):null;if(o)return this.#md(o,e,t,r,i);const a=n?wo.open(s,e):null;this.#Xc=a?(e,t)=>wo.publish(s,e,t):null;try{const s=await this.#pd(e,t,r,i);return a?.resolve(s),s}catch(e){throw a?.reject(e),e}finally{this.#Xc=null,a&&wo.close(s)}}async#pd(e,t,r=0,i=null){if("string"!=typeof e)throw new TypeError('The "url" argument must be a string.');const s=this.#Qc.method?.toUpperCase(),n="GET"===s;let o="",a=0,l=!1;if(this.#Dc&&"GET"===s&&0===r)try{const t=await this.#Gu(e,{...this.#Qc,method:"HEAD",signal:i||this.signal.signal});if(this.#Vc=t,this.emit("headResponse",t),t.ok){o=t.headers.get("content-type")||"";const e=t.headers.get("content-length");e&&(a=Number(e));const r={};t.headers.forEach((e,t)=>{r[t]=e});const i={};o&&(i.type=o),a>0&&(i.size=a),Object.keys(r).length>0&&(i.httpHeaders=r),Object.keys(i).length>0&&this._emitMetadata(i,"HEAD"),l=!0}}catch(e){}const h=new Headers(this.#Qc.headers);n&&r>0&&h.set("Range",`bytes=${r}-`);const u={...this.#Qc,signal:i||this.signal.signal,headers:h};u.body||void 0===this.#Zc||(u.body=this.#Zc);const c=await this.#Gu(e,u);if(this.#qc=c,this.emit("response",c),!c.ok){if(416===c.status)throw new Error("Requested range not satisfiable.");throw new Error(`Failed to fetch media: ${c.status} ${c.statusText}`)}if(!c.body)return new Blob([],{type:o||"application/octet-stream"});const d=c.headers.get("content-type")||o,m=Number(c.headers.get("content-length")||0);if(206===c.status){const e=c.headers.get("content-range");if(e){const t=e.match(/\/(\d+)$/);t&&(a=Number(t[1]))}}else a=m>0?m+r:a;const p={};c.headers.forEach((e,t)=>{p[t]=e});const f={};d&&d!==o&&(f.type=d,o=d),a>0&&(!l||206===c.status)&&(f.size=a),Object.keys(p).length>0&&(f.httpHeaders=p),Object.keys(f).length>0&&this._emitMetadata(f,"GET"),this.#fd(o);const y=this._createProgress(a),g=c.body.getReader(),w=[];let b=r;try{for(;;){const{done:e,value:r}=await g.read();if(e)break;w.push(r),this.#Wc?.write(r),b+=r.byteLength,y.push(r.byteLength),this.emit("chunk",{chunk:r,loaded:b,total:a}),this._emitProgress(),t&&t(r,w)}}finally{this.#od()}return new Blob(w,{type:o||"application/octet-stream"})}#nd(e){if(!this.#Za?.ignoreSearch)return e;const t=e.split("#")[0],r=t.indexOf("?");return-1===r?t:t.slice(0,r)}async#md(e,t,r,i,s){const n=[],o=this._createProgress(0),a=wo.history(e.key).length,l=wo.subscribe(e.key,e=>{this.#yd(e,n,o,r)});let h;try{h=await e.promise}catch{return l&&l(),this.#pd(t,r,i,s)}return l&&l(),this.#Jc=!0,this._setResourceSize(h.size),h.type&&this._emitMetadata({type:h.type},"MIRROR"),await this.#gd(h),this.emit("mirror",{src:this.#Cc,key:e.key,size:h.size,mirrors:e.mirrors,replayed:a}),h}#yd(e,t,r,i){if("metadata"===e.name){const[t,r]=e.args;return void this._emitMetadata(t,r)}if("chunk"===e.name){const[s]=e.args,n=s.chunk;0===r.total&&s.total>0&&(r.total=s.total),t.push(n),r.push(s.chunk.byteLength),i&&i(n,t)}this.#wd(e.name,e.args)}#wd(e,t){this.#Yc=!0;try{Reflect.apply(this.emit,this,[e,...t])}finally{this.#Yc=!1}}async#gd(e){this.#fd(e.type),this.#Wc&&(this.#Wc.write(new Uint8Array(await e.arrayBuffer())),this.#od())}#fd(e){if(!this.#Bc)return;const t=e.split(";")[0].trim().toLowerCase();this.#Kc.forEach((e,r)=>{!this.#Wc&&t.startsWith(`${r}/`)&&(this.#Wc=e(t))})}#od(){if(this.#Wc){if("function"==typeof this.#Wc.finalize){const e=this.#Wc.finalize();e&&this._emitMetadata(e,"DECODE")}this.#Wc.close(),this.#Wc=null}}_acquireFromCache(){if(!this.#Za)return null;const e=this.#Za.acquire(this.#Cc);return e&&(this.#jc=!0,this._setCacheHint(!0),this._setResourceSize(e.size),e.type&&this._emitMetadata({type:e.type},"CACHE"),e.metadata&&this._emitMetadata(e.metadata,"CACHE")),e}_releaseFromCache(){this.#Za&&this.#jc&&(this.#Za.release(this.#Cc),this.#jc=!1)}_getLoadTime(){return this.#kc-this.#tc}_detectCache(){if("undefined"==typeof performance||"function"!=typeof performance.getEntriesByName)return!1;const e=performance.getEntriesByName(this.#Cc);if(0===e.length)return!1;const t=e[e.length-1];return 0===t.transferSize&&t.decodedBodySize>0}_setResourceSize(e){if("number"!=typeof e||Number.isNaN(e)||e<0)throw new RangeError('The "size" argument must be a positive number.');this.#zc=e}_getResourceSize(){if(this.#zc>0)return this.#zc;if("undefined"==typeof performance||"function"!=typeof performance.getEntriesByName)return 0;const e=performance.getEntriesByName(this.#Cc);if(0===e.length)return 0;const t=e[e.length-1];return t.decodedBodySize||t.transferSize||0}_flushMutations(){this.#X&&this.#X.takeRecords()}_createObjectUrl(e){if(!(e instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');return this._revokeObjectUrl(),this.#Hc=URL.createObjectURL(e),this.#Hc}_revokeObjectUrl(){this.#Hc&&(URL.revokeObjectURL(this.#Hc),this.#Hc=null)}#ad(){this.#_c=new AbortController,this.#_c.signal.addEventListener("abort",()=>this._abort(),{once:!0})}#bd(){return{src:this.#Cc,type:"",width:0,height:0,duration:0,size:0,fromCache:!1,loadTime:0,timestamp:0,animation:null,httpHeaders:{}}}#td(){this.#Pc=!1,this.#Oc=null,this.#zc=0,this.#Mc=!1,this.#Jc=!1,this.#Yc=!1,this.#Xc=null,this.#ed={},this.#tc=performance.now(),this.#kc=0,this.#pu=this.#bd()}#Yu(e){if(this.#Ju===e)return;const t=this.#Ju;this.#Ju=e,this.emit("statechange",{state:e,previous:t,src:this.#Cc})}#ud(e){this.listenerCount("error")>0&&this.emit("error",e)}#sd(e){if(e===this.#Cc)return!1;const t=this.#Cc;return this.#Cc=e,this.#pu.src=e,this.emit("srcchange",{src:e,previousSrc:t}),!0}#rd(){!this.#X&&"undefined"!=typeof MutationObserver&&this.#Un&&(this.#X=new MutationObserver(e=>this.#vd(e)),this.#X.observe(this.#Un,{attributes:!0,attributeFilter:this.#Fc?["src","original-src"]:["src"]}))}#cd(){this.#X&&(this.#X.disconnect(),this.#X=null)}#vd(e){const t=this.#Un;if(!t)return;let r=null;for(const{attributeName:i}of e)"original-src"===i?r=t.getAttribute("original-src")??"":"src"===i&&null===r&&(r=t.getAttribute("src")??"");null!==r&&r!==this.#Cc&&r!==this.#Oc&&(this.#sd(r),this.#Lc&&this.reload().catch(e=>{this.listenerCount("error")>0&&this.emit("error",e)}))}#hd(){return{src:this.#Cc,fromCache:this.#Mc||this._detectCache(),loadTime:this.#kc-this.#tc,timestamp:Date.now(),animation:null,...this._getMetadataDetails(),...this.#ed}}#ld(e){return this.#Ic<=0?e:new Promise((t,r)=>{this.#$c=setTimeout(()=>{this.#$c=null,this.#_c&&this.#_c.abort(),this.emit("timeout",{src:this.#Cc,timeout:this.#Ic}),r(new Error(`Media load timed out after ${this.#Ic}ms.`))},this.#Ic),e.then(e=>{null!==this.#$c&&clearTimeout(this.#$c),this.#$c=null,t(e)},e=>{null!==this.#$c&&clearTimeout(this.#$c),this.#$c=null,r(e)})})}_createElement(){throw new Error('The "_createElement" method must be implemented by a subclass.')}_startLoad(){throw new Error('The "_startLoad" method must be implemented by a subclass.')}_getMetadataDetails(){return{type:"",width:0,height:0,duration:0,size:0}}_abort(){this._revokeObjectUrl();const e=this.#Un;if(!e)return;const t=e;"function"==typeof t.pause&&t.pause(),e.removeAttribute("src"),"function"==typeof t.load&&t.load(),this._setInternalSrc(null)}_cleanup(){}}const Eo=vo;class To extends Error{constructor(e="The buffer does not hold enough bytes to satisfy the read."){super(e),this.name="TinyNeedMoreData"}}class So{#Ed;#Td;#Sd;#xd;constructor(e,t=0,r=e.length){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');if(!Number.isInteger(t)||t<0||t>e.length)throw new RangeError('The "offset" argument is out of bounds.');if(!Number.isInteger(r)||r<t||r>e.length)throw new RangeError('The "limit" argument is out of bounds.');this.#Ed=e,this.#Td=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#Sd=t,this.#xd=r}get offset(){return this.#Sd}get limit(){return this.#xd}get remaining(){return this.#xd-this.#Sd}get eof(){return this.#Sd>=this.#xd}get buffer(){return this.#Ed}has(e){if(!Number.isInteger(e))throw new TypeError('The "count" argument must be an integer.');return e>=0&&this.#Sd+e<=this.#xd}#Ad(e){if(!Number.isInteger(e))throw new TypeError('The "count" argument must be an integer.');if(e<0)throw new RangeError('The "count" argument must be a non-negative integer.');if(!this.has(e))throw new To}seek(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "position" argument must be a positive integer.');return this.#Sd=e,this}skip(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "count" argument must be a non-negative integer.');return this.#Ad(e),this.#Sd+=e,this}uint8(){return this.#Ad(1),this.#Td.getUint8(this.#Sd++)}uint16(){this.#Ad(2);const e=this.#Td.getUint16(this.#Sd);return this.#Sd+=2,e}uint16le(){this.#Ad(2);const e=this.#Td.getUint16(this.#Sd,!0);return this.#Sd+=2,e}uint24(){this.#Ad(3);const e=this.#Ed[this.#Sd]<<16|this.#Ed[this.#Sd+1]<<8|this.#Ed[this.#Sd+2];return this.#Sd+=3,e}uint32(){this.#Ad(4);const e=this.#Td.getUint32(this.#Sd);return this.#Sd+=4,e}uint32le(){this.#Ad(4);const e=this.#Td.getUint32(this.#Sd,!0);return this.#Sd+=4,e}int32le(){this.#Ad(4);const e=this.#Td.getInt32(this.#Sd,!0);return this.#Sd+=4,e}uint64(){return 4294967296*this.uint32()+this.uint32()}ascii(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "length" argument must be a non-negative integer.');this.#Ad(e);let t="";for(let r=0;r<e;r+=1)t+=String.fromCharCode(this.#Ed[this.#Sd+r]);return this.#Sd+=e,t}bytes(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "length" argument must be a non-negative integer.');this.#Ad(e);const t=this.#Ed.subarray(this.#Sd,this.#Sd+e);return this.#Sd+=e,t}}const xo=new Set(["moov","trak","mdia","minf","stbl","edts","dinf","udta","mvex","moof","traf","iprp","ipco","mfra","skip","jxl "]),Ao=new Set(["meta"]);function Co(e,t){const r=e.offset,i=e.uint32(),s=e.ascii(4);let n=8,o=i;if(1===i?(o=e.uint64(),n=16):0===i&&(o=t-r),o<n||r+o>t)throw new To;return{type:s,start:r,dataStart:r+n,dataEnd:r+o,end:r+o}}function Io(e,t,r,i,s=0){if(s>8)return null;for(const n of function*(e,t,r){let i=t;for(;i+8<=r;){e.seek(i);const t=Co(e,r);yield t,i=t.end}}(e,t,r)){if(i.has(n.type))return n;if(xo.has(n.type)||Ao.has(n.type)){const t=Ao.has(n.type)?4:0,r=Io(e,n.dataStart+t,n.dataEnd,i,s+1);if(r)return r}}return null}function ko(e,t,r=0){return!(e.length<r+t.length)&&t.every((t,i)=>e[r+i]===t)}function Do(e){return e.seek(6),{width:e.uint8()||256,height:e.uint8()||256}}function Mo(e,t){let r=t;for(;r<e.length;){const t=e[r];if(void 0===t)break;if(r+=1,0===t)return r;r+=t}return r}const Lo=Object.freeze([{name:"png",mime:"image/png",sniff:e=>ko(e,[137,80,78,71,13,10,26,10]),parse:function(e){return e.seek(16),{width:e.uint32(),height:e.uint32()}}},{name:"jpeg",mime:"image/jpeg",sniff:e=>ko(e,[255,216,255]),parse:function(e){const t=e.limit;for(e.seek(2);e.offset+4<=t;){if(255!==e.uint8())continue;let r=e.uint8();for(;255===r&&e.offset<t;)r=e.uint8();if(1===r||r>=208&&r<=217)continue;if(218===r)return null;const i=e.uint16();if(r>=192&&r<=207&&196!==r&&200!==r&&204!==r){e.skip(1);const t=e.uint16(),r=e.uint16();return r>0&&t>0?{width:r,height:t}:null}e.skip(i-2)}return null}},{name:"gif",mime:"image/gif",sniff:e=>ko(e,[71,73,70,56]),parse:function(e){e.seek(6);const t=e.uint16le(),r=e.uint16le();return t>0&&r>0?{width:t,height:r}:null}},{name:"bmp",mime:"image/bmp",sniff:e=>ko(e,[66,77]),parse:function(e){e.seek(18);const t=e.int32le(),r=Math.abs(e.int32le());return t>0&&r>0?{width:t,height:r}:null}},{name:"webp",mime:"image/webp",sniff:e=>ko(e,[82,73,70,70])&&ko(e,[87,69,66,80],8),parse:function(e){e.seek(12);const t=e.ascii(4);if("VP8 "===t)return e.seek(26),{width:16383&e.uint16le(),height:16383&e.uint16le()};if("VP8L"===t){e.seek(21);const t=e.uint32le();return{width:1+(16383&t),height:1+(t>>14&16383)}}return"VP8X"===t?(e.seek(24),{width:1+(e.uint8()|e.uint8()<<8|e.uint8()<<16),height:1+(e.uint8()|e.uint8()<<8|e.uint8()<<16)}):null}},{name:"avif",mime:"image/avif",sniff:e=>ko(e,[102,116,121,112],4),parse:function(e){const t=Io(e,0,e.limit,new Set(["ispe"]));if(!t)return null;e.seek(t.dataStart+4);const r=e.uint32(),i=e.uint32();return r>0&&i>0?{width:r,height:i}:null}},{name:"ico",mime:"image/x-icon",sniff:e=>ko(e,[0,0,1,0]),parse:Do},{name:"cur",mime:"image/x-icon",sniff:e=>ko(e,[0,0,2,0]),parse:Do},{name:"svg",mime:"image/svg+xml",sniff:e=>{const t=new TextDecoder("utf-8").decode(e.subarray(0,256)).trimStart();return t.startsWith("<svg")||t.startsWith("<?xml")||t.startsWith("<!DOCTYPE svg")},parse:function(e){const t=Math.min(e.limit,8192);e.seek(0);const r=new TextDecoder("utf-8").decode(e.bytes(t)),i=r.match(/<svg\b[^>]*>/i);if(!i){if(r.includes("<svg"))throw new To;return null}const s=i[0],n=e=>{const t=s.match(new RegExp(`${e}\\s*=\\s*["']([^"']+)["']`,"i"));return t?Math.round(Number.parseFloat(t[1])):0},o=n("width"),a=n("height");if(o>0&&a>0)return{width:o,height:a};const l=s.match(/viewBox\s*=\s*["']([^"']+)["']/i);if(l){const e=l[1].trim().split(/[\s,]+/).map(Number);if(4===e.length&&e[2]>0&&e[3]>0)return{width:Math.round(e[2]),height:Math.round(e[3])}}return null}}]),No=class{#Cd=new Uint8Array(0);#Id=null;#kd=!1;#Dd=!1;#uc;#Md=!1;#Ld=0;#Nd=0;#_d=0;finalize(){if(!this.#Md||!this.#Id||!this.#kd)return null;const e=this.#Rd();return this.#Cd=new Uint8Array(0),e?{animation:e}:null}constructor(e="",t=65536){if("number"!=typeof t||Number.isNaN(t)||t<1)throw new RangeError('The "maxBytes" argument must be a positive number.');this.#uc=t}#Rd(){const e=this.#Id?.name;return"gif"===e?function(e){if(e.length<13)return null;let t=13;const r=e[10];128&r&&(t+=3*(1<<1+(7&r)));let i=0,s=1,n=!1,o=0,a=100;for(;t<e.length;){const r=e[t];if(59===r)break;if(33===r){const r=e[t+1];if(255===r&&11===e[t+2])ko(e,[78,69,84,83,67,65,80,69,50,46,48],t+3)&&3===e[t+14]&&1===e[t+15]&&(s=e[t+16]|e[t+17]<<8,n=!0);else if(249===r&&4===e[t+2]){let r=e[t+4]|e[t+5]<<8;r<=1&&(r=10),a=10*r}t=Mo(e,t+2)}else{if(44!==r)break;{i+=1,o+=a,a=100;const r=e[t+9];t+=10,128&r&&(t+=3*(1<<1+(7&r))),t+=1,t=Mo(e,t)}}if(!t||isNaN(t))break}return i<=1?null:{frames:i,loopCount:n?s:1,duration:o}}(this.#Cd):"webp"===e?function(e){let t=12,r=0,i=1,s=0,n=!1;for(;t+8<=e.length;){const o=new DataView(e.buffer,e.byteOffset+t,8),a=String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]),l=o.getUint32(4,!0),h=t+8;"ANIM"===a&&h+6<=e.length?(n=!0,i=e[h+4]|e[h+5]<<8):"ANMF"===a&&h+15<=e.length&&(r+=1,s+=e[h+12]|e[h+13]<<8|e[h+14]<<16),t+=8+l+l%2}return!n||r<=1?null:{frames:r,loopCount:i,duration:s}}(this.#Cd):"png"===e?function(e){let t=8,r=0,i=1,s=0,n=!1;for(;t+8<=e.length;){const o=new DataView(e.buffer,e.byteOffset+t,8).getUint32(0),a=String.fromCharCode(e[t+4],e[t+5],e[t+6],e[t+7]),l=t+8;if("acTL"===a&&l+8<=e.length){n=!0;const t=new DataView(e.buffer,e.byteOffset+l,8);r=t.getUint32(0),i=t.getUint32(4)}else if("fcTL"===a&&l+26<=e.length){const t=new DataView(e.buffer,e.byteOffset+l,26),r=t.getUint16(20),i=t.getUint16(22)||100;s+=Math.round(r/i*1e3)}else if("IEND"===a)break;t+=12+o}return!n||r<=1?null:{frames:r,loopCount:i,duration:s}}(this.#Cd):"avif"===e?function(e){const t=new So(e),r=Io(t,0,t.limit,new Set(["moov"]));if(!r)return null;const i=Io(t,r.dataStart,r.dataEnd,new Set(["mvhd"]));let s=0;if(i){t.seek(i.dataStart);const e=t.uint8();let r,n;if(t.skip(3),1===e){t.skip(16),r=t.uint32();const e=t.bytes(8);n=e[4]<<24|e[5]<<16|e[6]<<8|e[7]}else t.skip(8),r=t.uint32(),n=t.uint32();r>0&&(s=Math.round(n/r*1e3))}const n=Io(t,r.dataStart,r.dataEnd,new Set(["trak"]));if(!n)return null;const o=Io(t,n.dataStart,n.dataEnd,new Set(["mdia"]));if(!o)return null;const a=Io(t,o.dataStart,o.dataEnd,new Set(["minf"]));if(!a)return null;const l=Io(t,a.dataStart,a.dataEnd,new Set(["stbl"]));if(!l)return null;const h=Io(t,l.dataStart,l.dataEnd,new Set(["stsz"]));let u=0;return h&&(t.seek(h.dataStart+4),t.uint32(),u=t.uint32()),u<=1?null:{frames:u,loopCount:0,duration:s}}(this.#Cd):null}push(e){if(!(e instanceof Uint8Array))throw new TypeError('The "chunk" argument must be a Uint8Array.');if(this.#Dd)return null;if(this.#kd&&!this.#Md)return null;const t=new Uint8Array(this.#Cd.length+e.length);if(t.set(this.#Cd),t.set(e,this.#Cd.length),this.#Cd=t,!this.#Id){if(this.#Id=this.#jd(),!this.#Id)return this.#Cd.length>512&&(this.#Dd=!0),null;this.#Md=["gif","webp","png","avif"].includes(this.#Id.name)}if(this.#kd&&this.#Md){const e=this.#Rd();return e&&e.frames>this.#_d?(this.#_d=e.frames,{width:this.#Ld,height:this.#Nd,animation:e}):null}try{const e=this.#Id.parse(new So(this.#Cd));if(e){if(this.#kd=!0,this.#Ld=e.width,this.#Nd=e.height,this.#Md){const t=this.#Rd();t&&(e.animation=t,this.#_d=t.frames)}else this.#Cd=new Uint8Array(0);return e}}catch(e){if(!(e instanceof To))throw e}return this.#Cd.length>this.#uc&&!this.#kd&&(this.#Dd=!0,this.#Cd=new Uint8Array(0)),null}close(){this.#Cd=new Uint8Array(0),this.#Dd=!0}#jd(){for(const e of Lo)try{if(e.sniff(this.#Cd))return e}catch{return null}return null}},_o="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=";function Ro(e,t,r){const i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=[];let n=t;for(;n+8<=r;){let t=i.getUint32(n);const o=String.fromCharCode(e[n+4],e[n+5],e[n+6],e[n+7]);let a=8;if(1===t){if(n+16>r)break;t=4294967296*i.getUint32(n+8)+i.getUint32(n+12),a=16}else 0===t&&(t=r-n);if(t<a||n+t>r)break;s.push({type:o,start:n,dataStart:n+a,dataEnd:n+t,end:n+t}),n+=t}return s}function jo(e){let t=0;for(const r of e)t+=r.length;const r=new Uint8Array(t);let i=0;for(const t of e)r.set(t,i),i+=t.length;return r}function Po(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Oo(e){return new Uint8Array([e>>8&255,255&e])}function $o(e){return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,255&e])}function Ho(e,...t){const r=jo(t),i=new Uint8Array(8+r.length);return i.set($o(i.length),0),i.set(Po(e),4),i.set(r,8),i}function Fo(e,t,r,i){const s=Ho("ftyp",Po("avif"),$o(0),Po("avif"),Po("mif1"),Po("miaf")),n=s=>{const n=Ho("hdlr",$o(0),$o(0),Po("pict"),$o(0),$o(0),$o(0),new Uint8Array([0])),o=Ho("pitm",$o(0),Oo(1)),a=Ho("iloc",$o(0),new Uint8Array([68,0]),Oo(1),Oo(1),Oo(0),Oo(1),$o(s),$o(i.length)),l=Ho("infe",$o(33554432),Oo(1),Oo(0),Po("av01"),new Uint8Array([0])),h=Ho("iinf",$o(0),Oo(1),l),u=Ho("ispe",$o(0),$o(t),$o(r)),c=Ho("ipco",e,u),d=Ho("ipma",$o(0),$o(1),Oo(1),new Uint8Array([2,129,2])),m=Ho("iprp",c,d);return Ho("meta",$o(0),n,o,a,h,m)},o=n(0);return jo([s,n(s.length+o.length+8),Ho("mdat",i)])}const zo=class extends Eo{static get tagName(){return"IMG"}#Pd;#Od;#$d;#Hd;#Fd;#zd=[];#Bd=[];#Wd=!1;#Jo=!0;#Ud=1;#qd=0;#Vd=null;#Kd=null;#Gd=null;constructor(e={}){if(null===e||"object"!=typeof e)throw new TypeError('The "options" argument must be an object.');if(null!==e.element&&void 0!==e.element&&!(e.element instanceof HTMLImageElement))throw new TypeError('The "element" option must be an HTMLImageElement or null.');super({useHeadRequest:!1,...e}),e.cache||(this.#Gd=new yo({strategy:yo.Strategy.MANUAL}));const t=["none","native","script-only","controlled"],r=["sync","async","auto"],{crossOrigin:i=null,decoding:s="async",stream:n=!1,animationControl:o="none"}=e;if(!t.includes(o))throw new RangeError(`The "animationControl" option must be one of: ${t.join(", ")}.`);if(!r.includes(s))throw new RangeError(`The "decoding" option must be one of: ${r.join(", ")}.`);if(![null,"anonymous","use-credentials"].includes(i))throw new RangeError('The "crossOrigin" option must be "anonymous", "use-credentials" or null.');this.#Od=i,this.#$d=s,this.#Pd=null,this.#Fd=o,this.#Hd="none"!==this.#Fd||Boolean(n),this._insertDecoder("image",e=>{const t=new No(e);return{write:e=>{const r=t.push(e);r&&this._emitMetadata(r,"PROBE")},close:()=>{const e=t.finalize();e&&this._emitMetadata(e,"PROBE_ANIMATION"),t.close()}}})}get image(){return this.#Pd}get stream(){return this.#Hd}get naturalWidth(){return this.#Pd?.naturalWidth??0}get naturalHeight(){return this.#Pd?.naturalHeight??0}get aspectRatio(){const e=this.naturalHeight;return 0===e?0:this.naturalWidth/e}freeze(e=null){if(null!==e&&(!Number.isInteger(e)||e<0))throw new RangeError('The "frameIndex" argument must be a non-negative integer or null.');if("none"!==this.#Fd&&"script-only"!==this.#Fd)if(this.#Wd=!0,"native"===this.#Fd&&this.#zd.length>0){const e=this.#zd[0].url;this.#Pd&&(this._setInternalSrc(e),this.#Pd.src=e)}else if("controlled"===this.#Fd&&(this.pause(),null!==e&&e>=0&&e<this.#zd.length&&(this.#qd=e),this.#Pd&&this.#zd[this.#qd])){const e=this.#zd[this.#qd].url;this._setInternalSrc(e),this.#Pd.src=e}}unfreeze(){"none"!==this.#Fd&&"script-only"!==this.#Fd&&(this.#Wd=!1,"native"===this.#Fd?this.#Pd&&this.#Kd&&(this._setInternalSrc(this.#Kd),this.#Pd.src=this.#Kd):"controlled"===this.#Fd&&this.play())}play(){"controlled"===this.#Fd&&(this.#Vd||(this.#Jo=!0,this.#Wd=!1,this.#Jd()))}pause(){"controlled"===this.#Fd&&(this.#Jo=!1,this.#Vd&&(clearTimeout(this.#Vd),this.#Vd=null))}get playbackRate(){return this.#Ud}set playbackRate(e){"controlled"===this.#Fd&&(this.#Ud=Math.max(.1,Number(e)||1))}get animationScript(){return JSON.parse(JSON.stringify(this.#Bd))}set animationScript(e){if("controlled"!==this.#Fd)throw new Error("Animation script editing is only available in controlled mode.");if(!Array.isArray(e))throw new TypeError('The "script" value must be an array.');this.#Bd=Array.isArray(e)?e:[]}async _startLoad(){this._releaseAnimationFrames();const e=this._resolveElement();let t;if(this.#Pd=e,this.#Od&&(e.crossOrigin=this.#Od),e.decoding=this.#$d,e.removeAttribute("src"),this._flushMutations(),this.#Hd?t=await this.#Yd(e):(t=this._waitForMedia(e,"load"),e.src=this.src,this._flushMutations()),await t,"function"==typeof e.decode)try{await e.decode()}catch{}}#Xd(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "index" argument must be a non-negative integer.');return`${this.src}:::frame=${e}`}#Qd(e){if(!Number.isInteger(e)||e<0)throw new RangeError('The "index" argument must be a non-negative integer.');const t=this.cache??this.#Gd;if(!t)throw new Error("No cache is available to store animation frames.");const r=t.get(this.#Xd(e));return r?(t.acquire(this.#Xd(e)),r.objectUrl):null}#Zd(e,t){if(!Number.isInteger(e)||e<0)throw new RangeError('The "index" argument must be a non-negative integer.');if(!(t instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');const r=this.cache??this.#Gd;if(!r)throw new Error("No cache is available to store animation frames.");const i=this.#Xd(e),s=r.set(i,t,!1,{},this.src);return r.acquire(i),s.objectUrl}async#Yd(e){if(!(e instanceof HTMLImageElement))throw new TypeError('The "image" argument must be an HTMLImageElement.');const t=this._acquireFromCache();if(t){if(this.emit("cachehit",t),this._setInternalSrc(t.objectUrl),this.#Kd=t.objectUrl,"none"!==this.#Fd&&t.metadata?.animation&&0===this.#zd.length&&await this.#em(await t.blob.arrayBuffer()),"controlled"===this.#Fd)return this.#Kd=null,this.play(),Promise.resolve();const r=this._waitForMedia(e,"load");return e.src=t.objectUrl,this._flushMutations(),r}let r=performance.now(),i=null;try{const t=await this._downloadStream(this.src,(t,s)=>{if(this.progressive&&"controlled"!==this.#Fd){const t=performance.now();if(t-r>500){r=t;const n=new Blob(s,{type:this.metadata.type||"image/jpeg"}),o=URL.createObjectURL(n);i&&URL.revokeObjectURL(i),i=o,this._setInternalSrc(o),e.src=o,this._flushMutations()}}});"none"!==this.#Fd&&this.metadata.animation&&await this.#em(await t.arrayBuffer());const s=this.mirrored?this.#tm(t):this._cacheBlob(t);if(this._setInternalSrc(s),"controlled"===this.#Fd)return this.#Kd=null,this.play(),Promise.resolve();this.#Kd=s;const n=this._waitForMedia(e,"load");return e.src=s,this._flushMutations(),n}finally{i&&URL.revokeObjectURL(i)}}async#em(e){if(!(e instanceof ArrayBuffer))throw new TypeError('The "arrayBuffer" argument must be an ArrayBuffer.');const t=new Uint8Array(e);t.length<12||(71===t[0]&&73===t[1]&&70===t[2]?this.#rm(t):82===t[0]&&73===t[1]&&70===t[2]&&70===t[3]&&87===t[8]&&69===t[9]&&66===t[10]&&80===t[11]?this.#im(t):137===t[0]&&80===t[1]&&78===t[2]&&71===t[3]?this.#sm(t):102===t[4]&&116===t[5]&&121===t[6]&&112===t[7]&&this.#nm(t))}#om(e){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');let t=4294967295;for(let r=0;r<e.length;r++){t^=e[r];for(let e=0;e<8;e++)t=1&t?3988292384^t>>>1:t>>>1}return(4294967295^t)>>>0}#nm(e){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');const t=Ro(e,0,e.length).find(e=>"moov"===e.type);if(!t)return;const r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=Ro(e,t.dataStart,t.dataEnd).filter(e=>"trak"===e.type);let s=null;for(const t of i){const i=Ro(e,t.dataStart,t.dataEnd).find(e=>"mdia"===e.type);if(!i)continue;const n=Ro(e,i.dataStart,i.dataEnd).find(e=>"minf"===e.type);if(!n)continue;const o=Ro(e,n.dataStart,n.dataEnd).find(e=>"stbl"===e.type);if(!o)continue;const a=Ro(e,i.dataStart,i.dataEnd).find(e=>"mdhd"===e.type);let l=1e3;a&&(l=1===e[a.dataStart]?r.getUint32(a.dataStart+20):r.getUint32(a.dataStart+12)),s={stbl:o,timescale:l};break}if(!s)return;const n=Ro(e,s.stbl.dataStart,s.stbl.dataEnd),o=n.find(e=>"stsz"===e.type),a=n.find(e=>"stco"===e.type),l=n.find(e=>"co64"===e.type),h=n.find(e=>"stsc"===e.type),u=n.find(e=>"stts"===e.type),c=n.find(e=>"stsd"===e.type);if(!o||!h||!c)return;const d=[];{const e=o.dataStart+4,t=r.getUint32(e),i=r.getUint32(e+4);for(let s=0;s<i;s+=1)d.push(t>0?t:r.getUint32(e+8+4*s))}const m=[];if(a){const e=r.getUint32(a.dataStart+4);for(let t=0;t<e;t+=1)m.push(r.getUint32(a.dataStart+8+4*t))}else if(l){const e=r.getUint32(l.dataStart+4);for(let t=0;t<e;t+=1){const e=r.getUint32(l.dataStart+8+8*t),i=r.getUint32(l.dataStart+12+8*t);m.push(4294967296*e+i)}}const p=[];{const e=r.getUint32(h.dataStart+4);for(let t=0;t<e;t+=1){const e=h.dataStart+8+12*t;p.push({firstChunk:r.getUint32(e),samplesPerChunk:r.getUint32(e+4)})}}const f=[];if(u){const e=r.getUint32(u.dataStart+4);for(let t=0;t<e;t+=1){const e=u.dataStart+8+8*t,i=r.getUint32(e),s=r.getUint32(e+4);for(let e=0;e<i;e+=1)f.push(s)}}const y=[];{let e=0;for(let t=0;t<p.length;t+=1){const{firstChunk:r,samplesPerChunk:i}=p[t],s=t+1<p.length?p[t+1].firstChunk-1:m.length;for(let t=r;t<=s;t+=1){let r=m[t-1]??0;for(let t=0;t<i;t+=1)y.push(r),r+=d[e]??0,e+=1}}}const g=Ro(e,c.dataStart+8,c.dataEnd)[0];if(!g)return;const w=r.getUint16(g.dataStart+24),b=r.getUint16(g.dataStart+26),v=Ro(e,g.dataStart+78,g.dataEnd).find(e=>"av1C"===e.type);if(!v)return;const E=e.subarray(v.start,v.end),T=Math.min(d.length,y.length);for(let t=0;t<T;t+=1){const r=d[t],i=y[t],n=f[t]??0;let o=s.timescale>0?Math.round(n/s.timescale*1e3):100;if(o<=10&&(o=100),this.#Bd.push({delay:o}),"script-only"!==this.#Fd){let s=this.#Qd(t);if(!s){const n=Fo(E,w,b,e.subarray(i,i+r)),o=new Blob([n],{type:"image/avif"});s=this.#Zd(t,o)}this.#zd.push({url:s,cacheKey:this.#Xd(t)})}if("native"===this.#Fd)break}}#im(e){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');if(e.length<12)return;let t=12,r=null,i=null;const s=[],n=[];for(;t+8<=e.length;){const o=new DataView(e.buffer,e.byteOffset+t,8),a=String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]),l=o.getUint32(4,!0),h=t+8+l+l%2;if(h>e.length)break;const u=e.subarray(t,h);if("VP8X"===a)r=u;else if("ANIM"===a)i=u;else if("ANMF"===a){const r=t+8,i=e[r+12]|e[r+13]<<8|e[r+14]<<16;n.push({chunk:u,delay:i})}else n.length||"VP8 "===a||"VP8L"===a||s.push(u);t=h}if(0!==n.length)for(let e=0;e<n.length;e++){const t=n[e];let o=t.delay;if(o<=10&&(o=100),this.#Bd.push({delay:o}),"script-only"!==this.#Fd){let n=this.#Qd(e);if(!n){const o=[];r&&o.push(r),i&&o.push(i);for(const e of s)o.push(e);o.push(t.chunk);let a=4;for(const e of o)a+=e.length;const l=new Uint8Array(12),h=new DataView(l.buffer);l.set([82,73,70,70],0),h.setUint32(4,a,!0),l.set([87,69,66,80],8);const u=new Blob([l,...o],{type:"image/webp"});n=this.#Zd(e,u)}this.#zd.push({url:n,cacheKey:this.#Xd(e)})}if("native"===this.#Fd)break}}#sm(e){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');const t=[137,80,78,71,13,10,26,10],r=new Uint8Array([0,0,0,0,73,69,78,68,174,66,96,130]);if(e.length<8)return;const i=[],s=[];let n=null,o=0,a=0,l=8,h=!1,u=null;for(;l+8<=e.length;){const t=new DataView(e.buffer,e.byteOffset+l,8).getUint32(0),r=String.fromCharCode(e[l+4],e[l+5],e[l+6],e[l+7]),c=l+12+t;if(c>e.length)break;const d=e.subarray(l,c);if("IHDR"===r){const e=new DataView(d.buffer,d.byteOffset,d.byteLength);o=e.getUint32(8),a=e.getUint32(12),s.push(d)}else if("acTL"===r);else if("fcTL"===r){if(h=!0,u&&i.push(u),u=null,t>=26){const t=new DataView(e.buffer,e.byteOffset+l+8,26),r=t.getUint16(20),i=t.getUint16(22)||100;u={delay:0===i?100:Math.round(r/i*1e3),dataChunks:[],width:t.getUint32(4),height:t.getUint32(8),x:t.getUint32(12),y:t.getUint32(16),disposeOp:t.getUint8(24),blendOp:t.getUint8(25)}}}else if("IDAT"===r)h=!0,u&&u.dataChunks.push({type:"IDAT",bytes:d});else if("fdAT"===r)h=!0,u&&u.dataChunks.push({type:"fdAT",bytes:d});else{if("IEND"===r){n=d;break}h||s.push(d)}l=c}if(u&&i.push(u),0===i.length)return;const c=e=>{const i=s.map(t=>{if("IHDR"!==String.fromCharCode(t[4],t[5],t[6],t[7]))return t;const r=new Uint8Array(t),i=new DataView(r.buffer,r.byteOffset,r.byteLength);return i.setUint32(8,e.width),i.setUint32(12,e.height),i.setUint32(r.length-4,this.#om(r.subarray(4,r.length-4))),r}),o=[new Uint8Array(t),...i];for(const t of e.dataChunks)if("IDAT"===t.type)o.push(t.bytes);else if("fdAT"===t.type){const e=new Uint8Array(t.bytes.length-4),r=new DataView(e.buffer);r.setUint32(0,t.bytes.length-16),e.set([73,68,65,84],4),e.set(t.bytes.subarray(12,t.bytes.length-4),8),r.setUint32(e.length-4,this.#om(e.subarray(4,e.length-4))),o.push(e)}o.push(n??r);let a=0;for(const e of o)a+=e.length;const l=new Uint8Array(a);let h=0;for(const e of o)l.set(e,h),h+=e.length;let u="";for(let e=0;e<l.length;e+=1)u+=String.fromCharCode(l[e]);return btoa(u)},d=new Map,m=e=>{let t=d.get(e);return void 0===t&&(t=c(i[e]),d.set(e,t)),t},p=o||1,f=a||1,y=[];let g=0;const w=(e,t,r,i,s)=>{if(""===e)return"";if(i>=p&&s>=f)return"";if(i<=0||s<=0)return e;const n=`apng-mask-${g}`;return g+=1,y.push(`<mask id="${n}" maskUnits="userSpaceOnUse" x="0" y="0" width="${p}" height="${f}"><rect x="0" y="0" width="${p}" height="${f}" fill="#fff"/><rect x="${t}" y="${r}" width="${i}" height="${s}" fill="#000"/></mask>`),`<g mask="url(#${n})">${e}</g>`};let b="";for(let e=0;e<i.length;e+=1){const t=i[e],r=b,s=`<image href="data:image/png;base64,${m(e)}" x="${t.x}" y="${t.y}" width="${t.width}" height="${t.height}"/>`,n=0===t.blendOp?w(b,t.x,t.y,t.width,t.height)+s:b+s;let o=t.delay;if(o<=10&&(o=100),this.#Bd.push({delay:o}),"script-only"!==this.#Fd){let t=this.#Qd(e);if(!t){const r=`<svg xmlns="http://www.w3.org/2000/svg" width="${p}" height="${f}" viewBox="0 0 ${p} ${f}">`+(y.length>0?`<defs>${y.join("")}</defs>`:"")+n+"</svg>";t=this.#Zd(e,new Blob([r],{type:"image/svg+xml"}))}this.#zd.push({url:t,cacheKey:this.#Xd(e)})}if(b=1===t.disposeOp?w(n,t.x,t.y,t.width,t.height):2===t.disposeOp?r:n,"native"===this.#Fd)break}}#rm(e){if(!(e instanceof Uint8Array))throw new TypeError('The "bytes" argument must be a Uint8Array.');if(e.length<13)return;let t=13;const r=e[10];t+=128&r?3*(1<<1+(7&r)):0;const i=e.subarray(0,t);let s=null,n=100;for(;t<e.length;){const r=e[t];if(59===r)break;if(33===r){for(249===e[t+1]&&(s=e.subarray(t,t+8),n=10*(e[t+4]|e[t+5]<<8),n<=10&&(n=100)),t+=2;t<e.length&&0!==e[t];)t+=e[t]+1;t++}else{if(44!==r)break;{const r=t;t+=10;const o=e[t-1];for(128&o&&(t+=3*(1<<1+(7&o))),t++;t<e.length&&0!==e[t];)t+=e[t]+1;t++;const a=t;if(this.#Bd.push({delay:n}),"script-only"!==this.#Fd){const t=this.#zd.length;let n=this.#Qd(t);if(!n){const o=new Uint8Array(i.length+(s?s.length:0)+(a-r)+1);o.set(i,0);let l=i.length;s&&(o.set(s,l),l+=s.length),o.set(e.subarray(r,a),l),o[o.length-1]=59;const h=new Blob([o],{type:"image/gif"});n=this.#Zd(t,h)}this.#zd.push({url:n,cacheKey:this.#Xd(t)})}if("native"===this.#Fd)break;s=null}}}}#Jd(){if(!this.#Jo||this.#Wd||!this.#Pd||0===this.#zd.length)return;const e=this.#zd[this.#qd];if(!e)return;const t=this.#Bd[this.#qd],r=(t?.delay||100)/this.#Ud;this._setInternalSrc(e.url),this.#Pd.src=e.url,this._flushMutations(),this.#Vd=setTimeout(()=>{this.#qd=(this.#qd+1)%this.#zd.length,this.#Jd()},r)}_getMetadataDetails(){const e=this.#Pd,t=this.metadata.animation;return{type:e?.naturalWidth?`image/${this.#am()}`:"image/*",width:e?.naturalWidth??0,height:e?.naturalHeight??0,duration:t?t.duration/1e3:NaN,size:this._getResourceSize()}}_abort(){super._abort(),this.#Pd&&(this.#Pd.src=_o,this._flushMutations())}_releaseAnimationFrames(){null!==this.#Vd&&(clearTimeout(this.#Vd),this.#Vd=null);for(const e of this.#zd){const t=this.cache??this.#Gd;t?t.release(e.cacheKey):URL.revokeObjectURL(e.url)}this.#zd=[],this.#Bd=[],this.#qd=0,this.#Wd=!1,this.#Jo=!1}_cleanup(){this._revokeObjectUrl(),this.pause(),this._releaseAnimationFrames(),this.#Kd=null,this.#Pd&&(this.#Pd.onload=null,this.#Pd.onerror=null,this.#Pd.removeAttribute("src"),this.#Pd.src=_o,this._flushMutations())}_createElement(){return document.createElement("img")}#tm(e){if(!(e instanceof Blob))throw new TypeError('The "blob" argument must be a Blob.');return this._setResourceSize(e.size),this._createObjectUrl(e)}#am(){const e=this.src.split("?")[0].split("#")[0],t=e.lastIndexOf(".");return-1===t?"png":e.slice(t+1).toLowerCase()}};class Bo extends Eo{#lm;#hm;#um=null;#ie=null;#wn;constructor(e={}){if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError('The "options" argument must be a plain object.');super(e);const{fetch:t=globalThis.fetch.bind(globalThis),init:r={},responseType:i="blob"}=e;if("function"!=typeof t)throw new TypeError('The "fetch" option must be a function.');if(null===r||"object"!=typeof r||Array.isArray(r))throw new TypeError('The "init" option must be a plain object.');if(!["blob","arraybuffer","text","json"].includes(i))throw new RangeError('The "responseType" option must be one of: blob, arraybuffer, text, json.');this._fetch=t,this._requestInit=r,this.#lm=r,this.#hm=i,this.#wn={...e,fetch:t,init:{...r},responseType:i}}get blob(){return this.#um}get data(){return this.#ie}get responseType(){return this.#hm}get init(){return{...this.#lm}}clone(e={}){if(null===e||"object"!=typeof e||Array.isArray(e))throw new TypeError('The "overrides" argument must be a plain object.');const t={...this.#wn.init,...e.init??{}};return new Bo({...this.#wn,...e,init:t})}exportFetch(){const e=this;return async function(t,r){return e._fetch(t,r)}}async _startLoad(){const e=this._acquireFromCache();if(e)return this.emit("cachehit",e),this.#um=e.blob,void await this.#cm(e.blob);const t=await this._downloadStream(this.src);this.#um=t,this._setResourceSize(t.size),this.cache&&this._cacheBlob(t),await this.#cm(t)}async#cm(e){"arraybuffer"===this.#hm?this.#ie=await e.arrayBuffer():"text"===this.#hm?this.#ie=await e.text():"json"===this.#hm?this.#ie=JSON.parse(await e.text()):this.#ie=e}_getMetadataDetails(){return{type:this.#um?.type||"application/octet-stream",width:0,height:0,duration:0,size:this.#um?.size??0}}_createElement(){throw new Error("TinyFetchLoader does not create a DOM element.")}}const Wo=Bo,Uo=/^[A-Za-z0-9_-]{11}$/,qo="https://www.youtube.com/oembed",Vo="https://i.ytimg.com/vi",Ko=new Set(["youtube.com","m.youtube.com","music.youtube.com","youtube-nocookie.com","youtu.be"]),Go=new Set(["http:","https:"]),Jo=new Set(["default","mqdefault","hqdefault","sddefault","maxresdefault"]),Yo="video";function Xo(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw new TypeError(`${t} must be a plain object, received ${Array.isArray(e)?"array":typeof e}.`);return e}function Qo(e,t,r){const i=e[t];if("string"!=typeof i)throw new TypeError(`${r}: "${t}" must be a string, received ${typeof i}.`);const s=i.trim();if(0===s.length)throw new RangeError(`${r}: "${t}" cannot be empty.`);return s}function Zo(e,t,r){const i=e[t];if("number"!=typeof i)throw new TypeError(`${r}: "${t}" must be a number, received ${typeof i}.`);if(!Number.isInteger(i)||i<=0)throw new RangeError(`${r}: "${t}" must be a positive integer, received ${i}.`);return i}function ea(e,t="assertYouTubeOEmbedResponse"){const r=Xo(e,`${t}: payload`),i=Qo(r,"type",t);if(i!==Yo)throw new RangeError(`${t}: "type" must be "${Yo}", received "${i}".`);return{title:Qo(r,"title",t),author_name:Qo(r,"author_name",t),author_url:Qo(r,"author_url",t),type:i,version:Qo(r,"version",t),provider_name:Qo(r,"provider_name",t),provider_url:Qo(r,"provider_url",t),html:Qo(r,"html",t),width:Zo(r,"width",t),height:Zo(r,"height",t),thumbnail_url:Qo(r,"thumbnail_url",t),thumbnail_width:Zo(r,"thumbnail_width",t),thumbnail_height:Zo(r,"thumbnail_height",t)}}function ta(e){if("string"!=typeof e)throw new TypeError('extractYouTubeVideoId: "input" must be a string.');const t=e.trim();if(0===t.length)throw new RangeError('extractYouTubeVideoId: "input" cannot be empty.');if(Uo.test(t))return t;let r;try{r=new URL(t)}catch{throw new SyntaxError(`extractYouTubeVideoId: "${e}" is neither a video id nor a valid URL.`)}if(!Go.has(r.protocol))throw new RangeError(`extractYouTubeVideoId: unsupported protocol "${r.protocol}".`);const i=r.hostname.replace(/^www\./,"").toLowerCase();if(!Ko.has(i))throw new RangeError(`extractYouTubeVideoId: unsupported host "${i}".`);const s=r.pathname.match(/^\/(?:embed|shorts|live|v)\/([A-Za-z0-9_-]{11})/),n="youtu.be"===i?r.pathname.slice(1).split("/")[0]:r.searchParams.get("v")??s?.[1]??null;if("string"!=typeof n||!Uo.test(n))throw new SyntaxError(`extractYouTubeVideoId: no valid video id found in "${e}".`);return n}async function ra(e,t={}){const r="fetchYouTubeOEmbed",i=Xo(t,`${r}: "options"`),{signal:s,fetchImpl:n=fetch}=i;if(void 0!==s&&!(s instanceof AbortSignal))throw new TypeError(`${r}: "options.signal" must be an AbortSignal.`);if("function"!=typeof n)throw new TypeError(`${r}: "options.fetchImpl" must be a function.`);const o=ta(e),a=new URL(qo);a.searchParams.set("format","json"),a.searchParams.set("url",`https://www.youtube.com/watch?v=${o}`);const l=await n(a,{method:"GET",signal:s});if("object"!=typeof l||null===l||"function"!=typeof l.json)throw new TypeError(`${r}: "options.fetchImpl" did not resolve to a Response.`);if(!l.ok)throw new Error(`${r}: request failed with status ${l.status} for video "${o}".`);return ea(await l.json(),r)}function ia(e,t="hqdefault"){if("string"!=typeof t)throw new TypeError(`getYouTubeThumbnailUrl: "quality" must be a string, received ${typeof t}.`);if(!Jo.has(t))throw new RangeError(`getYouTubeThumbnailUrl: "quality" must be one of ${[...Jo].join(", ")}.`);return`${Vo}/${ta(e)}/${t}.jpg`}})(),window.TinyEssentials=i})();