tiny-essentials
Version:
Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.
1 lines • 24.6 kB
JavaScript
(()=>{"use strict";const e={d:(t,r)=>{if(Array.isArray(r))for(var n=0;n<r.length;){var o=r[n++],i=r[n++];e.o(t,o)?0===i&&n++:0===i?Object.defineProperty(t,o,{enumerable:!0,value:r[n++]}):Object.defineProperty(t,o,{enumerable:!0,get:i})}else for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};function r(e){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 n(e,t){const r=e.filter(e=>!t.includes(e));return{added:t.filter(t=>!e.includes(t)),removed:r}}function o(e,t=!1){return t?function(t,r){return t[e]>r[e]?-1:t[e]<r[e]?1:0}:function(t,r){return t[e]<r[e]?-1:t[e]>r[e]?1:0}}function i(e=new Date,t="asSeconds",r=null){if(e instanceof Date){const n=r instanceof Date?r:new Date,o=e.getTime()-n.getTime();switch(t){case"asMilliseconds":return o;case"asSeconds":default:return o/1e3;case"asMinutes":return o/6e4;case"asHours":return o/36e5;case"asDays":return o/864e5}}return null}function a(e,t="seconds",r="{time}"){e=Math.max(0,Math.floor(e));const n=["seconds","minutes","hours","days","months","years"].indexOf(t),o=n>=5,i=n>=4,a=n>=3,s=n>=2,l=n>=1,u=n>=0,c={years:o?0:NaN,months:i?0:NaN,days:a?0:NaN,hours:s?0:NaN,minutes:l?0:NaN,seconds:u?0:NaN,total:NaN};let d=e;if(o||i||a){const e=new Date(1980,0,1),t=new Date(e.getTime()+1e3*d),r=new Date(e);if(o)for(;new Date(r.getFullYear()+1,r.getMonth(),r.getDate()).getTime()<=t.getTime();)r.setFullYear(r.getFullYear()+1),c.years++;if(i)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)}s&&(c.hours=Math.floor(d/3600),d%=3600),l&&(c.minutes=Math.floor(d/60),d%=60),u&&(c.seconds=d),i&&(c.years,c.months,c.days),o&&(c.years,c.months,c.days),c.total=+e.toFixed(2).replace(/\.00$/,"");const f=e=>{const t="string"==typeof e?parseInt(e):e;return Number.isNaN(t)?"NaN":String(t).padStart(2,"0")},m=[s?f(c.hours):null,l?f(c.minutes):null,u?f(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,f(c.hours)).replace(/\{minutes\}/g,f(c.minutes)).replace(/\{seconds\}/g,f(c.seconds)).replace(/\{time\}/g,m).replace(/\{total\}/g,String(c.total)).trim()}function s(e){return a(e,"hours","{hours}:{minutes}:{seconds}")}function l(e){return a(e,"days","{days}d {hours}:{minutes}:{seconds}")}function u(e,t="milliseconds"){e=Math.max(0,Math.floor(e));const r=["milliseconds","seconds","minutes","hours","days","months","years"].indexOf(t),n=r>=6,o=r>=5,i=r>=4,a=r>=3,s=r>=2,l=r>=1,u=r>=0,c={years:n?0:NaN,months:o?0:NaN,days:i?0:NaN,hours:a?0:NaN,minutes:s?0:NaN,seconds:l?0:NaN,milliseconds:u?0:NaN,total:NaN};let d=e;if(n||o||i){const e=new Date(1980,0,1),t=new Date(e.getTime()+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(i)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),s&&(c.minutes=Math.floor(d/6e4),d%=6e4),l&&(c.seconds=Math.floor(d/1e3),d%=1e3),u&&(c.milliseconds=d),o&&(c.years,c.months,c.days),n&&(c.years,c.months,c.days),c.total=+e,c}function c(e){return Array.isArray(e)?e.length:d(e)?Object.keys(e).length:0}function d(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"===Object.prototype.toString.call(e)}function f(e,t){return new Promise((r,n)=>{const o=new FileReader;o.onload=()=>{try{r(o.result)}catch(e){n(e)}},o.onerror=()=>{n(o.error)},o[t](e)})}function m(e,t=!1){return new Promise((r,n)=>{"string"!=typeof t&&"boolean"!=typeof t&&n(new TypeError("The isDataUrl parameter must be a boolean or a string.")),f(e,"readAsDataURL").then(e=>{if("string"!=typeof e)throw new TypeError("Expected file content to be a string.");const n=e.match(/^data:(.+);base64,(.*)$/);if(!n||!n[2])throw new Error("Invalid data URL format or missing Base64 content.");const[,o,i]=n;if(!/^[\w/+]+=*$/.test(i))throw new Error("Base64 content is malformed.");if("boolean"==typeof t)return r(t?e:i);if(!/^[\w-]+\/[\w.+-]+$/.test(t))throw new Error(`Invalid MIME type string: ${t}`);return r(`data:${t};base64,${i}`)}).catch(n)})}function p(e){return new Promise((t,r)=>f(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 n=JSON.parse(r);if("object"!=typeof n||null===n)throw new Error("Parsed content is not a valid JSON object or array.");t(n)}).catch(r))}function h(e,t,r=2){const n=JSON.stringify(t,null,r),o=new Blob([n],{type:"application/json"}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function g(e,t){if("function"!=typeof t)throw new TypeError('The "onProgress" argument must be a function.');if(!e.body)return e;const r=e.headers.get("content-length"),n=r?parseInt(r,10):0;let o=0;const i=e.body.getReader(),a=new ReadableStream({async start(e){for(;;){const{done:r,value:a}=await i.read();if(r)break;o+=a.byteLength,t(o,n),e.enqueue(a)}e.close()}});return new Response(a,{headers:e.headers,status:e.status,statusText:e.statusText})}async function y(e,{method:t="GET",body:r,timeout:n=0,retries:o=0,headers:i={},signal:a=null,onProgress:s}={}){if("string"!=typeof e||!e.startsWith("../")&&!e.startsWith("./")&&!e.startsWith("/")&&!e.startsWith("https://")&&!e.startsWith("http://"))throw new Error("Invalid URL: must be a valid http or https address.");if("string"!=typeof t||!t.trim())throw new Error("Invalid method: must be a non-empty string.");if(!a){if("number"!=typeof n||!Number.isFinite(n)||Number.isNaN(n)||n<0)throw new Error("Invalid timeout: must be a positive number.");if("number"!=typeof o||!Number.isFinite(o)||Number.isNaN(o)||o<0)throw new Error("Invalid retries: must be a positive number.")}const l=a?1:o+1;let u=null;for(let c=0;c<l;c++){const l=a?null:new AbortController,f=a||(l?.signal??null),m=!a&&n&&l?setTimeout(()=>l.abort(),n):null;try{const n=await fetch(e,{method:t.toUpperCase(),headers:{Accept:"application/json",...i},body:void 0!==r?d(r)?JSON.stringify(r):r:void 0,signal:f});if(m&&clearTimeout(m),!n.ok)throw new Error(`HTTP error: ${n.status} ${n.statusText}`);return s?g(n,s):n}catch(e){if(u=e,a)break;c<o&&await new Promise(e=>setTimeout(e,300*(c+1)))}}throw new Error(`Failed to fetch JSON from "${e}"${u?`: ${u.message}`:"."}`)}async function w(e,t){return new Promise((r,n)=>{y(e,t).then(async e=>{const t=e.headers.get("content-type")||"";if(!t.includes("application/json"))throw new Error(`Unexpected content-type: ${t}`);const n=await e.json();if(!Array.isArray(n)&&!d(n))throw new Error("Received invalid data instead of valid JSON.");return r(n)}).catch(n)})}async function b(e,t,r){return new Promise((n,o)=>{y(e,r).then(async e=>{const r=e.headers.get("content-type")||"";if(Array.isArray(t)&&t.length>0&&!t.some(e=>r.includes(e)))throw new Error(`Blocked MIME type: ${r}`);const o=await e.text();return n(o)}).catch(o)})}function E({element:e=document.body,hiddenClass:t="windowHidden",visibleClass:r="windowVisible",onVisible:n,onHidden:o}={}){if(!(e instanceof Element))throw new TypeError('"element" must be an instance of Element.');if("string"!=typeof t)throw new TypeError('"hiddenClass" must be a string.');if("string"!=typeof r)throw new TypeError('"visibleClass" must be a string.');if(void 0!==n&&"function"!=typeof n)throw new TypeError('"onVisible" must be a function if provided.');if(void 0!==o&&"function"!=typeof o)throw new TypeError('"onHidden" must be a function if provided.');let i="",a="";const s=()=>{e.classList.remove(t),e.classList.remove(r)};let l=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){l=c[e];break}const d=function(u){s();const c=u?.type,d=l&&document[l];["focus","focusin","pageshow"].includes(c)?(e.classList.add(r),n?.({type:c,oldClass:a,oldType:i}),a=r):["blur","focusout","pagehide"].includes(c)||d?(e.classList.add(t),o?.({type:c,oldClass:a,oldType:i}),a=t):(e.classList.add(r),n?.({type:c,oldClass:a,oldType:i}),a=r),i=c};let f=()=>{};if(l){const e=u[c.indexOf(l)];document.addEventListener(e,d),window.addEventListener("focus",d),window.addEventListener("blur",d),f=()=>{document.removeEventListener(e,d),window.removeEventListener("focus",d),window.removeEventListener("blur",d),s()}}else"onfocusin"in document?(document.onfocusin=document.onfocusout=d,f=()=>{document.onfocusin=document.onfocusout=null,s()}):(window.onpageshow=window.onpagehide=window.onfocus=window.onblur=d,f=()=>{window.onpageshow=window.onpagehide=window.onfocus=window.onblur=null,s()});const m=new Event(l&&document[l]?"blur":"focus");return d(m),f}e.r(t),e.d(t,{addAiMarkerShortcut:()=>X,areElsCollBottom:()=>Z,areElsCollLeft:()=>_,areElsCollPerfBottom:()=>te,areElsCollPerfLeft:()=>re,areElsCollPerfRight:()=>ne,areElsCollPerfTop:()=>ee,areElsCollRight:()=>Q,areElsCollTop:()=>V,areElsColliding:()=>oe,areElsPerfColliding:()=>ie,arraySortPositions:()=>o,asyncReplace:()=>q,breakdownDuration:()=>u,calculateMarketcap:()=>H,cloneObjTypeOrder:()=>F,compareMarketcap:()=>W,countObj:()=>c,diffArrayList:()=>n,diffStrings:()=>K,documentIsFullScreen:()=>S,exitFullScreen:()=>I,extendObjType:()=>N,extractMediaId3Tags:()=>ve,fetchJson:()=>w,fetchText:()=>b,formatBytes:()=>U,formatCustomTimer:()=>a,formatDayTimer:()=>l,formatTimer:()=>s,genFibonacciSeq:()=>Y,getAge:()=>$,getElsCollDetails:()=>me,getElsCollDirDepth:()=>fe,getElsCollOverlap:()=>le,getElsCollOverlapPos:()=>ue,getElsColliding:()=>ae,getElsPerfColliding:()=>se,getElsRelativeCenterOffset:()=>de,getPercentage:()=>B,getRectCenter:()=>ce,getSimplePerc:()=>j,getTimeDuration:()=>i,installWindowHiddenScript:()=>E,isFullScreenMode:()=>D,isJsonObject:()=>d,isScreenFilled:()=>C,objType:()=>k,offFullScreenChange:()=>P,onFullScreenChange:()=>x,parseMediaMetadata:()=>Te,readBase64Blob:()=>m,readFileBlob:()=>f,readJsonBlob:()=>p,reorderObjTypeOrder:()=>M,requestFullScreen:()=>A,ruleOfThree:()=>R,safeTextTrim:()=>G,saveJsonFile:()=>h,shuffleArray:()=>r,toTitleCase:()=>z,toTitleCaseLowerFirst:()=>J,valMediaContentMetadata:()=>be,valMediaContentMetadataPartial:()=>Ee});const v="undefined"!=typeof window&&void 0!==window.document,T={items:{},order:[]};function N(e,t){const r=[],n=Array.isArray(e)?e:Object.entries(e);for(const[e,o]of n)if(!T.items.hasOwnProperty(e)){T.items[e]=o;let n="number"==typeof t?t:-1;if(-1===n){const e=T.order.indexOf("object");n=e>-1?e:T.order.length}n=Math.min(Math.max(0,n),T.order.length),T.order.splice(n,0,e),r.push(e)}return r}function M(e){const t=[...T.order];return!!e.every(e=>t.includes(e))&&(T.order=e.slice(),!0)}function F(){return[...T.order]}const L=e=>{if(null===e)return"null";for(const t of T.order)if("function"!=typeof T.items[t]||T.items[t](e))return t;return"unknown"};function k(e,t){if(void 0===e)return null;const r=L(e);return"string"==typeof t?r===t.toLowerCase():r}N([["undefined",e=>void 0===e],["null",e=>null===e],["boolean",e=>"boolean"==typeof e],["number",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],["array",e=>Array.isArray(e)]]),v&&N([["file",e=>"undefined"!=typeof File&&e instanceof File]]),N([["date",e=>e instanceof Date],["regexp",e=>e instanceof RegExp],["map",e=>e instanceof Map],["set",e=>e instanceof Set],["weakmap",e=>e instanceof WeakMap],["weakset",e=>e instanceof WeakSet],["promise",e=>e instanceof Promise]]),v&&N([["htmlelement",e=>"undefined"!=typeof HTMLElement&&e instanceof HTMLElement]]),N([["object",e=>d(e)]]);const S=()=>!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitIsFullScreen||document.mozFullScreen),C=()=>window.innerHeight===screen.height&&window.innerWidth===screen.width,D=()=>S()||C(),A=e=>new Promise(async(t,r)=>{const n=document.documentElement;try{n.requestFullscreen?await n.requestFullscreen(e):n.mozRequestFullScreen?n.mozRequestFullScreen(e):n.webkitRequestFullScreen?n.webkitRequestFullScreen(e):n.msRequestFullscreen&&n.msRequestFullscreen(e),t()}catch(e){r(e)}}),I=()=>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)}}),O=["fullscreenchange","webkitfullscreenchange","mozfullscreenchange","MSFullscreenChange"],x=(e,t)=>{O.forEach(r=>{document.addEventListener(r,e,t)})},P=(e,t)=>{O.forEach(r=>{document.removeEventListener(r,e,t)})};function R(e,t,r,n=!1){return n?Number(e*t)/r:Number(r*t)/e}function j(e,t){return e*(t/100)}function B(e,t){return 0===t?0:e/t*100}function $(e=0,t=null){if(null!=e&&0!==e){const r=new Date(e);if(Number.isNaN(r.getTime()))return null;const n=t instanceof Date?t:new Date;let o=n.getFullYear()-r.getFullYear();const i=n.getMonth(),a=r.getMonth(),s=n.getDate(),l=r.getDate();return(i<a||i===a&&s<l)&&o--,Math.abs(o)}return null}function U(e,t=null,r=null){if("number"!=typeof e||e<0)return{unit:null,value:null};if(0===e)return{unit:"Bytes",value:0};const n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=r&&n.includes(r)?n.indexOf(r):n.length-1,i=Math.min(Math.floor(Math.log(e)/Math.log(1024)),o);let a=e/Math.pow(1024,i);if(null!==t){const e=t<0?0:t;a=parseFloat(a.toFixed(e))}return{unit:n[i],value:a}}function Y({baseValues:e=[0,1],length:t=10,combiner:r=(e,t)=>e+t}={}){if(!Array.isArray(e)||2!==e.length)throw new Error("baseValues must be an array of exactly two numbers");const n=[...e.slice(0,2)];for(let e=2;e<t;e++){const t=r(n[e-2],n[e-1],e);n.push(t)}return n}function H(e,t){if(Number.isNaN(e)||!Number.isFinite(e))throw new TypeError("Original market cap must be a number.");if(Number.isNaN(t)||!Number.isFinite(t))throw new TypeError("Circulating supply must be a number.");if(t<=0)throw new Error("Circulating supply must be greater than zero.");return e/t}function W(e,t,r){if(Number.isNaN(r)||!Number.isFinite(r))throw new TypeError("New market cap must be a number.");const n=H(e,t),o="number"==typeof r?r/t:NaN;return{originalPrice:n,newPrice:o,priceChangePercent:"number"==typeof r?(o-n)/n*100:NaN}}async function q(e,t,r){const n=[];e.replace(t,(e,...t)=>(n.push(r(e,...t)),e));const o=await Promise.all(n);return e.replace(t,()=>o.shift())}function z(e){return e.replace(/\w\S*/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase())}function J(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 X({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.");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 G(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 n=e.trim();if(n.length>t){const e=n.lastIndexOf(" ",t);return e>0&&e>=t*r?`${n.substring(0,e).trim()}...`:`${n.substring(0,t).trim()}...`}return n}function K(e,t){const r={added:{},removed:{},modified:{}};for(const n in e)n in t?e[n]!==t[n]&&(r.modified[n]={old:e[n],new:t[n]}):r.removed[n]=e[n];for(const n in t)n in e||(r.added[n]=t[n]);return r}const V=(e,t)=>e.bottom<t.top,Z=(e,t)=>e.top>t.bottom,_=(e,t)=>e.right<t.left,Q=(e,t)=>e.left>t.right,ee=(e,t)=>e.bottom<=t.top,te=(e,t)=>e.top>=t.bottom,re=(e,t)=>e.right<=t.left,ne=(e,t)=>e.left>=t.right,oe=(e,t)=>!(_(e,t)||Q(e,t)||V(e,t)||Z(e,t)),ie=(e,t)=>!(re(e,t)||ne(e,t)||ee(e,t)||te(e,t)),ae=(e,t)=>_(e,t)?"left":Q(e,t)?"right":V(e,t)?"top":Z(e,t)?"bottom":null,se=(e,t)=>re(e,t)?"left":ne(e,t)?"right":ee(e,t)?"top":te(e,t)?"bottom":null,le=(e,t)=>({overlapLeft:t.right-e.left,overlapRight:e.right-t.left,overlapTop:t.bottom-e.top,overlapBottom:e.bottom-t.top}),ue=({overlapLeft:e=-1,overlapRight:t=-1,overlapTop:r=-1,overlapBottom:n=-1}={})=>({dirX:e<t?"right":"left",dirY:r<n?"bottom":"top"}),ce=e=>({x:e.left+e.width/2,y:e.top+e.height/2});function de(e,t){const r=e.left+e.width/2,n=e.top+e.height/2;return{x:t.left+t.width/2-r,y:t.top+t.height/2-n}}function fe(e,t){if(!ie(e,t))return{inDir:null,dirX:null,dirY:null,depthX:0,depthY:0};const{overlapLeft:r,overlapRight:n,overlapTop:o,overlapBottom:i}=le(e,t),{dirX:a,dirY:s}=ue({overlapLeft:r,overlapRight:n,overlapTop:o,overlapBottom:i}),l=Math.min(r,n),u=Math.min(o,i);let c;return c=l<u?a:s,{inDir:c,dirX:a,dirY:s,depthX:l,depthY:u}}function me(e,t){const r=ie(e,t),n={in:null,x:null,y:null},o={y:null,x:null},i={top:0,bottom:0,left:0,right:0},{overlapLeft:a,overlapRight:s,overlapTop:l,overlapBottom:u}=le(t,e);i.top=l,i.bottom=u,i.left=a,i.right=s;const c=Object.entries(i).filter(([,e])=>e>0).sort((e,t)=>e[1]-t[1]),{dirX:d,dirY:f}=ue({overlapLeft:s,overlapRight:a,overlapTop:u,overlapBottom:l});return n.y=f,n.x=d,i.bottom<0?o.y="bottom":i.top<0&&(o.y="top"),i.left<0?o.x="left":i.right<0&&(o.x="right"),n.in=r?i.top===i.bottom&&i.bottom===i.left&&i.left===i.right?"center":c.length?c[0][0]:"top":null,{dirs:n,depth:i,isNeg:o}}const pe=new Map;class he extends Error{constructor(e,t,r){super(e),this.name="MediaLoadingError",this.url=t,this.stage=r}}const ge=async e=>{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)},ye=(e,t="image/jpeg")=>{const r=e=>{const t=URL.createObjectURL(e),r=pe.get(t);return pe.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 n=e.split(",")[1],o=atob(n),i=new Uint8Array(o.length);for(let e=0;e<o.length;e++)i[e]=o.charCodeAt(e);return r(new Blob([i],{type:t}))}return"string"==typeof e?e:""},we=(e,t)=>{const r=e=>t&&void 0===e,n=e=>r(e)||"string"==typeof e||null===e,o=(e,t)=>!!r(e)||!(!Array.isArray(e)||!e.every(t));if(!n(e.title))throw new TypeError('Invalid metadata: "title" must be a string or null.');if(!n(e.album))throw new TypeError('Invalid metadata: "album" must be a string or null.');if(!n(e.albumartist))throw new TypeError('Invalid metadata: "albumartist" must be a string or null.');if(!n(e.artist))throw new TypeError('Invalid metadata: "artist" must be a string or null.');if(i=e.year,!r(i)&&"number"!=typeof i&&null!==i)throw new TypeError('Invalid metadata: "year" must be a number or null.');var i;if(!o(e.albumartists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "albumartists" must be an array of string.');if(!o(e.genre,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "genre" must be an array of string.');if(!o(e.label,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "label" must be an array of string.');if(!o(e.composer,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "composer" must be an array of string.');if(!o(e.artists,e=>"string"==typeof e))throw new TypeError('Invalid metadata: "artists" must be an array of string.');if(!o(e.picture,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.');const a=(e,t)=>{if(!r(e)){if(null==e)throw new TypeError(`Invalid metadata: "${t}" is required.`);if("object"!=typeof e)throw new TypeError(`Invalid metadata: "${t}" must be an object or null.`);if("number"!=typeof e.no&&null!==e.no)throw new TypeError(`Invalid metadata: "${t}.no" must be a number or null.`);if("number"!=typeof e.of&&null!==e.of)throw new TypeError(`Invalid metadata: "${t}.of" must be a number or null.`)}};a(e.disk,"disk"),a(e.track,"track")},be=e=>we(e,!1),Ee=e=>we(e,!0),ve=async(e,t)=>{if("string"!=typeof e)throw new TypeError(`Expected url to be a string, but received ${typeof e}.`);if("function"!=typeof t)throw new TypeError(`Expected parseFile to be a function, but received ${typeof t}.`);try{const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch audio file: ${r.status} ${r.statusText}`);const n=await r.blob(),o=await t(n);if(!o||"object"!=typeof o.common)throw new TypeError('Invalid metadata: "common" property is missing or not an object.');const i=o.common;return Ee(i),{title:i?.title??null,album:i?.album??null,albumartist:i?.albumartist??null,albumartists:i?.albumartists??[],genre:i?.genre??[],label:i?.label??[],composer:i?.composer??[],year:i?.year??null,artist:i?.artist??null,artists:i?.artists??[],disk:i?.disk?{no:i.disk.no,of:i.disk.of}:{no:null,of:null},track:i?.track?{no:i.track.no,of:i.track.of}:{no:null,of:null},picture:i?.picture?.map(e=>({...e,data:ye(e.data,e.format)}))??[]}}catch(e){throw e}},Te=async(e,t={},r={},n=e=>new Promise((e,t)=>t(new TypeError("parseFile library not found."))),o={},i="null")=>{if("string"!=typeof e&&!(e instanceof HTMLMediaElement))throw new TypeError("Source must be a string or an HTMLMediaElement.");if(o.onProgress&&"function"!=typeof o.onProgress)throw new TypeError("callbacks.onProgress must be a function.");if(o.onError&&"function"!=typeof o.onError)throw new TypeError("callbacks.onError must be a function.");let a,s="";const l=(t,r)=>{o.onProgress&&o.onProgress({event:r,status:"loading",stage:t,url:s||(e instanceof HTMLMediaElement?e.src:"unknown")})},u=(t,r)=>{o.onError&&o.onError({error:t,url:s||(e instanceof HTMLMediaElement?e.src:"unknown"),stage:r})};try{l("INITIALIZING"),"string"==typeof e?(s=e,a=new Audio(s)):(a=e,s=a.src);try{await new Promise((e,t)=>{const r=e=>l("DOWNLOADING",e),n=()=>{i(),e(void 0)},o=e=>{i(),t(new Error(`HTMLMediaElement failed to load: ${e.message||"Unknown error"}`))},i=()=>{a.removeEventListener("progress",r),a.removeEventListener("loadedmetadata",n),a.removeEventListener("error",o)};a.addEventListener("progress",r),a.addEventListener("loadedmetadata",n),a.addEventListener("error",o),a.readyState>=1&&(i(),e(void 0))}),l("METADATA_LOADED")}catch(e){throw new he(e instanceof Error?e.message:"UNKNOWN ERROR",s,"METADATA")}const c={id:r.id||await ge(s),duration:Math.floor(1e3*a.duration),url:s,weight:r.weight??1};let d={};l("EXTRACTING_ID3");try{d=await ve(s,n)}catch(e){u(e instanceof Error?e:new Error("Unknown Error"),"ID3"),console.warn(`[TinyAudioUtils] ID3 extraction failed for ${s}. Falling back to filename.`)}const f=e=>{try{return(e.split(/[?#]/)[0].split("/").pop()??"").replace(/\.[^/.]+$/,"")||"Unknown Track"}catch{return"Unknown Track"}},m={...c,...t,...d,...r,title:d.title||r.title||f(s),artist:d.artist||r.artist||("string"==typeof i?i:String(i()))};return o.onProgress&&o.onProgress({status:"success",stage:"COMPLETE",url:s}),m}catch(e){if(e instanceof he)throw e;{const t=new he(e instanceof Error?e.message:"UNKNOWN ERROR",s,"INITIALIZING");throw u(t,"INITIALIZING"),t}}};window.TinyBasicsEs=t})();