@sv443-network/coreutils
Version:
Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with `@sv443-network/userutils` and `@sv443-network/djsutils`, but can be used independently as well.
50 lines (38 loc) • 33.8 kB
JavaScript
/* umd */
(function (g, f) {
if ("object" == typeof exports && "object" == typeof module) {
module.exports = f();
} else if ("function" == typeof define && define.amd) {
define("CoreUtils", [], f);
} else if ("object" == typeof exports) {
exports["CoreUtils"] = f();
} else {
g["CoreUtils"] = f();
}
}(this, () => {
var exports = {};
var module = { exports };
;var ce=Object.create;var R=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var he=(r,e)=>{for(var t in e)R(r,t,{get:e[t],enumerable:!0})},X=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!fe.call(r,n)&&n!==t&&R(r,n,{get:()=>e[n],enumerable:!(i=de(e,n))||i.enumerable});return r};var L=(r,e,t)=>(t=r!=null?ce(pe(r)):{},X(e||!r||!r.__esModule?R(t,"default",{value:r,enumerable:!0}):t,r)),ge=r=>X(R({},"__esModule",{value:!0}),r);var He={};he(He,{BrowserStorageEngine:()=>Q,ChecksumMismatchError:()=>V,CustomError:()=>O,DataStore:()=>H,DataStoreEngine:()=>I,DataStoreSerializer:()=>Z,DatedError:()=>y,Debouncer:()=>j,FileStorageEngine:()=>G,MigrationError:()=>N,NanoEmitter:()=>x,NetworkError:()=>C,PicoEmitter:()=>$,ScriptContextError:()=>P,ValidationError:()=>W,abtoa:()=>ie,atoab:()=>ne,autoPlural:()=>ze,bitSetHas:()=>ye,capitalize:()=>je,clamp:()=>w,compress:()=>J,computeHash:()=>_,consumeGen:()=>Oe,consumeStringGen:()=>Me,createProgressBar:()=>Le,createRecurringTask:()=>Ue,createTable:()=>_e,darkenColor:()=>ee,debounce:()=>We,decompress:()=>q,defaultPbChars:()=>ae,defaultTableLineCharset:()=>oe,digitCount:()=>be,fetchAdvanced:()=>Ae,formatNumber:()=>Te,getCallStack:()=>Re,getListLength:()=>Fe,getterifyObj:()=>Ne,hexToRgb:()=>te,insertValues:()=>Ke,joinArrayReadable:()=>Be,lightenColor:()=>we,mapRange:()=>U,overflowVal:()=>De,pauseFor:()=>ke,pureObj:()=>Ve,randRange:()=>k,randomId:()=>xe,randomItem:()=>ve,randomItemIndex:()=>B,randomizeArray:()=>Ee,rgbToHex:()=>re,roundFixed:()=>K,scheduleExit:()=>Ie,secsToTimeStr:()=>Je,setImmediateInterval:()=>Ce,setImmediateTimeoutLoop:()=>$e,takeRandomItem:()=>Pe,takeRandomItemIndex:()=>Y,truncStr:()=>qe,valsWithin:()=>Se});module.exports=ge(He);function ye(r,e){return(r&e)===e}function w(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function be(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function Te(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function U(r,e,t,i,n){return(typeof i>"u"||typeof n>"u")&&(n=t,t=e,i=e=0),Number(e)===0&&Number(i)===0?r*(n/t):(r-e)*((n-i)/(t-e))+i}function De(r,e,t){let i=typeof t=="number"?e:0;if(t=typeof t=="number"?t:e,i>t)throw new RangeError(`Parameter "min" can't be bigger than "max"`);if(isNaN(r)||isNaN(i)||isNaN(t)||!isFinite(r)||!isFinite(i)||!isFinite(t))return NaN;if(r>=i&&r<=t)return r;let n=t-i+1;return((r-i)%n+n)%n+i}function k(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(U(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function K(r,e){let t=10**e;return Math.round(r*t)/t}function Se(r,e,t=1,i=.5){return Math.abs(K(r,t)-K(e,t))<=i}function ve(r){return B(r)[0]}function B(r){if(r.length===0)return[void 0,void 0];let e=k(r.length-1);return[r[e],e]}function Ee(r){let e=[...r];if(r.length===0)return e;for(let t=e.length-1;t>0;t--){let i=Math.floor(Math.random()*(t+1));[e[t],e[i]]=[e[i],e[t]]}return e}function Pe(r){var e;return(e=Y(r))==null?void 0:e[0]}function Y(r){let[e,t]=B(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function ee(r,e,t=!1){var c;r=r.trim();let i=(m,p,h,l)=>(m=Math.max(0,Math.min(255,m-m*l/100)),p=Math.max(0,Math.min(255,p-p*l/100)),h=Math.max(0,Math.min(255,h-h*l/100)),[m,p,h]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=te(r);else if(r.startsWith("rgb")){let m=(c=r.match(/\d+(\.\d+)?/g))==null?void 0:c.map(Number);if(!m)throw new TypeError("Invalid RGB/RGBA color format");[n,o,a,s]=m}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?re(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function te(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[w(i,0,255),w(n,0,255),w(o,0,255),typeof e=="number"?w(e,0,1):void 0]}function we(r,e,t=!1){return ee(r,e*-1,t)}function re(r,e,t,i,n=!0,o=!1){let a=s=>w(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function ie(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function ne(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function J(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:ie(a)}async function q(r,e,t="string"){let i=r instanceof Uint8Array?r:ne((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function _(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function xe(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>U(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[k(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var y=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},V=class extends y{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},O=class extends y{constructor(e,t,i){super(t,i),this.name=e}},N=class extends y{constructor(e,t){super(e,t),this.name="MigrationError"}},W=class extends y{constructor(e,t){super(e,t),this.name="ValidationError"}},P=class extends y{constructor(e,t){super(e,t),this.name="ScriptContextError"}},C=class extends y{constructor(e,t){super(e,t),this.name="NetworkError"}};async function Oe(r,...e){return await(typeof r=="function"?r(...e):r)}async function Me(r,...e){return typeof r=="string"?r:String(typeof r=="function"?await r(...e):r)}async function Ae(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o={...n};i&&(o.signal=i);let a;try{let s=fetch(r,o);if(t<0)return await s;let u=await Promise.race([s,new Promise((c,m)=>{a=setTimeout(()=>m(new DOMException("The operation timed out.","TimeoutError")),t)})]);return clearTimeout(a),u}catch(s){throw clearTimeout(a),new C("Error while calling fetch",{cause:s})}}function Fe(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function ke(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new O("AbortError","The pause was aborted")):i()})})}function Ve(r){return Object.assign(Object.create(null),r??{})}function Ne(r,e=!1){let t={};for(let i in r)Object.defineProperty(t,i,{get:()=>r[i],enumerable:!0,configurable:!0});return e?structuredClone(t):t}function Ce(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function $e(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function Ie(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new P("Cannot exit the process, no exit method available");setTimeout(t,e)}function Re(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new O("GetCallStack","Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.")}catch(t){let i=(t.stack??"").split(`
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
`)}}function Ue(r){var n;let e=0,t=!1;(n=r.signal)==null||n.addEventListener("abort",()=>{t=!0},{once:!0});let i=async(o=!1)=>{var a;if(!t){try{if(((r.immediate??!0)||!o)&&(e++,await((a=r.condition)==null?void 0:a.call(r,e-1))??!0)){let s=await r.task(e-1);r.onSuccess&&await r.onSuccess(s,e-1)}}catch(s){if(r.onError&&await r.onError(s,e-1),r.abortOnError&&(t=!0),!r.onError&&!r.abortOnError)throw s}!t&&(typeof r.maxIterations!="number"||e<r.maxIterations)&&setTimeout(i,r.timeout)}};return i(!0)}function ze(r,e,t="auto"){switch(typeof e!="number"&&("length"in e?e=e.length:"size"in e?e=e.size:"count"in e&&(e=e.count)),["-s","-ies"].includes(t)||(t="auto"),isNaN(e)&&(e=2),t==="auto"?String(r).endsWith("y")?"-ies":"-s":t){case"-s":return`${r}${e===1?"":"s"}`;case"-ies":return`${String(r).slice(0,-1)}${e===1?"y":"ies"}`}}function je(r){return r.charAt(0).toUpperCase()+r.slice(1)}var ae={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Le(r,e,t=ae){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ke(r,...e){return r.replace(/%\d/gm,t=>{var n;let i=Number(t.substring(1))-1;return(n=e[i]??t)==null?void 0:n.toString()})}function Be(r,e=", ",t=" and "){let i=[...r];if(i.length===0)return"";if(i.length===1)return String(i[0]);if(i.length===2)return i.join(t);let n=t+i[i.length-1];return i.pop(),i.join(e)+n}function Je(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function qe(r,e,t="..."){let i=(r==null?void 0:r.toString())??String(r),n=i.length>e?i.substring(0,e-t.length)+t:i;return n.length>e?n.substring(0,e):n}var oe={single:{horizontal:"\u2500",vertical:"\u2502",topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",leftT:"\u251C",rightT:"\u2524",topT:"\u252C",bottomT:"\u2534",cross:"\u253C"},double:{horizontal:"\u2550",vertical:"\u2551",topLeft:"\u2554",topRight:"\u2557",bottomLeft:"\u255A",bottomRight:"\u255D",leftT:"\u2560",rightT:"\u2563",topT:"\u2566",bottomT:"\u2569",cross:"\u256C"},none:{horizontal:" ",vertical:" ",topLeft:" ",topRight:" ",bottomLeft:" ",bottomRight:" ",leftT:" ",rightT:" ",topT:" ",bottomT:" ",cross:" "}};function _e(r,e){var h;let t={columnAlign:"left",truncateAbove:1/0,truncEndStr:"\u2026",minPadding:1,lineStyle:"single",applyCellStyle:()=>{},applyLineStyle:()=>{},lineCharset:oe,...e??{}},i=(l,f,d)=>w(typeof l!="number"||isNaN(Number(l))?f:l,f,d);t.truncateAbove=i(t.truncateAbove,0,1/0),t.minPadding=i(t.minPadding,0,1/0);let n=t.lineCharset[t.lineStyle],o=l=>l.replace(/\u001b\[[0-9;]*m/g,""),a=r.map(l=>l.map(f=>String(f))),s=((h=r[0])==null?void 0:h.length)??0;if(s===0||a.length===0)return"";if(isFinite(t.truncateAbove)){let l=(f,d,g)=>{let b=d-g.length;if(b<=0)return g.slice(0,d);let T=0,D="",v=0,E=!1;for(;v<f.length;){if(f[v]==="\x1B"&&f[v+1]==="["){let M=f.indexOf("m",v+2);if(M!==-1){D+=f.slice(v,M+1),E=!0,v=M+1;continue}}if(T===b)return D+=g,E&&(D+="\x1B[0m"),D;D+=f[v],T++,v++}return D};for(let f of a)for(let d=0;d<f.length;d++)o(f[d]??"").length>t.truncateAbove&&(f[d]=l(f[d]??"",t.truncateAbove,t.truncEndStr))}let u=Array.from({length:s},(l,f)=>Math.max(0,...a.map(d=>o(d[f]??"").length))),c=(l,f,d)=>{let[g="",b=""]=t.applyLineStyle(l,f)??[];return`${g}${d}${b}`},m=(l,f,d,g)=>{let b="",T=0;b+=c(l,T++,f);for(let D=0;D<s;D++){let v=(u[D]??0)+t.minPadding*2;for(let E=0;E<v;E++)b+=c(l,T++,n.horizontal);D<s-1&&(b+=c(l,T++,d))}return b+=c(l,T++,g),b},p=[];for(let l=0;l<a.length;l++){let f=a[l]??[],d=l*3;t.lineStyle!=="none"&&p.push(l===0?m(d,n.topLeft,n.topT,n.topRight):m(d,n.leftT,n.cross,n.rightT));let g="",b=0;g+=c(d+1,b++,n.vertical);for(let T=0;T<s;T++){let D=f[T]??"",v=o(D).length,E=(u[T]??0)-v,M=(Array.isArray(t.columnAlign)?t.columnAlign[T]:t.columnAlign)??"left",A,F;switch(M){case"right":A=t.minPadding+E,F=t.minPadding;break;case"centerLeft":A=t.minPadding+Math.floor(E/2),F=t.minPadding+Math.ceil(E/2);break;case"centerRight":A=t.minPadding+Math.ceil(E/2),F=t.minPadding+Math.floor(E/2);break;default:A=t.minPadding,F=t.minPadding+E}let[ue="",le=""]=t.applyCellStyle(l,T)??[];g+=" ".repeat(A)+ue+D+le+" ".repeat(F),g+=c(d+1,b++,n.vertical)}p.push(g),t.lineStyle!=="none"&&l===a.length-1&&p.push(m(d+2,n.bottomLeft,n.bottomT,n.bottomRight))}return p.join(`
`)}var z=()=>({emit(r,...e){for(let t=this.events[r]||[],i=0,n=t.length;i<n;i++)t[i](...e)},events:{},on(r,e){return(this.events[r]||=[]).push(e),()=>{var t;this.events[r]=(t=this.events[r])==null?void 0:t.filter(i=>e!==i)}}});var $=class{events=z();eventUnsubscribes=[];emitterOptions;catchUpMemory=new Map;constructor(e={}){this.emitterOptions={...e}}emitEvent(e,...t){var i;(i=this.emitterOptions.catchUpEvents)!=null&&i.includes(e)&&this.catchUpMemory.set(e,t),this.events.emit(e,...t)}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};i=this.events.on(e,t),this.eventUnsubscribes.push(i);let o=this.catchUpMemory.get(e);return o&&t(...o),n}once(e,t){let i=this.catchUpMemory.get(e);if(i){let n=i;return t==null||t(...n),Promise.resolve(n)}return new Promise(n=>{let o,a=((...s)=>{t==null||t(...s),o==null||o(),n(s)});o=this.events.on(e,a),this.eventUnsubscribes.push(o)})}onMulti(e){let t=[],i=()=>{for(let n of t)n();t.splice(0,t.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(n=>!t.includes(n))};for(let n of Array.isArray(e)?e:[e]){let o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:c,callback:m}=o;if(c!=null&&c.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("PicoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let p=[],h=(d=!1)=>{if(!(!(c!=null&&c.aborted)&&!d)){for(let g of p)g();p.splice(0,p.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(g=>!p.includes(g))}},l=new Set,f=()=>s.length===0||l.size===s.length;for(let d of a){let g=this.events.on(d,((...b)=>{h(),f()&&(m(d,...b),u&&h(!0))}));p.push(g)}for(let d of s){let g=this.events.on(d,((...b)=>{h(),l.add(d),f()&&(a.length===0||a.includes(d))&&(m(d,...b),u&&h(!0))}));p.push(g)}t.push(()=>h(!0))}return i}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[],this.catchUpMemory.clear()}};var x=class extends ${events=z();eventUnsubscribes=[];emitterOptions;catchUpMemory=new Map;constructor(e={}){super(e),this.emitterOptions={publicEmit:!1,...e}}emit(e,...t){return this.emitterOptions.publicEmit?(this.emitEvent(e,...t),!0):!1}unsubscribeAll(){super.unsubscribeAll()}};var se=1,H=class extends x{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;keyPrefix;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(super(e.nanoEmitterOptions),this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.keyPrefix=e.keyPrefix??"__ds-",this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await J(i,t,"string")],this.decodeData=[t,async i=>await q(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),c=await this.engine.getValue(`_uucfg-${this.id}`,null);if(c){let m=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),p=await this.engine.getValue(`_uucfgenc-${this.id}`,null),h=[],l=(f,d,g)=>{h.push(this.engine.setValue(d,g)),h.push(this.engine.deleteValue(f))};l(`_uucfg-${this.id}`,`${this.keyPrefix}${this.id}-dat`,c),isNaN(m)||l(`_uucfgver-${this.id}`,`${this.keyPrefix}${this.id}-ver`,m),typeof p=="boolean"||p==="true"||p==="false"||typeof p=="number"||p==="0"||p==="1"?l(`_uucfgenc-${this.id}`,`${this.keyPrefix}${this.id}-enf`,[0,"0",!0,"true"].includes(p)?this.compressionFormat??null:null):(h.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)),h.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(h)}(isNaN(u)||u<se)&&await this.engine.setValue("__ds_fmt_ver",se)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`,null),t=Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`,NaN));if(typeof e!="string"&&typeof e!="object"||e===null||isNaN(t)){await this.saveDefaultData(!1);let u=this.engine.deepCopy(this.defaultData);return this.emitEvent("loadData",u),u}let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=typeof i=="string"?await this.engine.deserializeData(i,o):i;t<this.formatVersion&&this.migrations&&(a=await this.runMigrations(a,t));let s=this.memoryCache?this.cachedData=this.engine.deepCopy(a):this.engine.deepCopy(a);return this.emitEvent("loadData",s),s}catch(e){let t=e instanceof Error?e:new Error(String(e));return console.warn("Error while parsing JSON data, resetting it to the default value.",e),this.emitEvent("error",t),await this.saveDefaultData(),this.defaultData}}getData(){if(!this.memoryCache)throw new y("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){let t=this.engine.deepCopy(e);return this.memoryCache&&(this.cachedData=e,this.emitEvent("updateDataSync",t)),new Promise(async i=>{let n=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(n.every(o=>o.status==="fulfilled"))this.emitEvent("updateData",t);else{let o=new Error("Error while saving data to persistent storage: "+n.map(a=>a.status==="rejected"?a.reason:null).filter(Boolean).join("; "));console.error(o),this.emitEvent("error",o)}i()})}async saveDefaultData(e=!0){this.memoryCache&&(this.cachedData=this.defaultData);let t=await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);if(t.every(i=>i.status==="fulfilled"))e&&this.emitEvent("setDefaultData",this.defaultData);else{let i=new Error("Error while saving default data to persistent storage: "+t.map(n=>n.status==="rejected"?n.reason:null).filter(Boolean).join("; "));console.error(i),this.emitEvent("error",i)}}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e)),this.emitEvent("deleteData")}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([u],[c])=>Number(u)-Number(c)),a=t;for(let u=0;u<o.length;u++){let[c,m]=o[u],p=Number(c);if(t<this.formatVersion&&t<p)try{let h=m(n);n=h instanceof Promise?await h:h,a=t=p;let l=p>=this.formatVersion||u===o.length-1;this.emitEvent("migrateData",p,n,l)}catch(h){let l=new N(`Error while running migration function for format version '${c}'`,{cause:h});if(this.emitEvent("migrationError",p,l),this.emitEvent("error",l),!i)throw l;return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,a),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]);let s=this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n);return this.emitEvent("updateData",s),s}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,c,m]=await Promise.all([this.engine.getValue(`${this.keyPrefix}${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`${this.keyPrefix}${i}-ver`,NaN),this.engine.getValue(`${this.keyPrefix}${i}-enf`,null)]);return[u,Number(c),!!m&&String(m)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,o),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`${this.keyPrefix}${i}-dat`),this.engine.deleteValue(`${this.keyPrefix}${i}-ver`),this.engine.deleteValue(`${this.keyPrefix}${i}-enf`)]),this.emitEvent("migrateId",i,this.id)}))}};var I=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,c;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(c=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:c.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new y("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");if(!this.dataStoreOptions.id)throw new y("DataStoreEngine must be initialized with a valid DataStore ID")}deepCopy(e){try{if("structuredClone"in globalThis)return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}},Q=class extends I{options;constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={type:"localStorage",...e}}async getValue(e,t){let i=this.options.type==="localStorage"?globalThis.localStorage.getItem(e):globalThis.sessionStorage.getItem(e);return typeof i>"u"?t:i}async setValue(e,t){this.options.type==="localStorage"?globalThis.localStorage.setItem(e,String(t)):globalThis.sessionStorage.setItem(e,String(t))}async deleteValue(e){this.options.type==="localStorage"?globalThis.localStorage.removeItem(e):globalThis.sessionStorage.removeItem(e)}},S,G=class extends I{options;fileAccessQueue=Promise.resolve();constructor(e){super(e==null?void 0:e.dataStoreOptions),this.options={filePath:t=>`.ds-${t}`,...e}}async readFile(){var e,t,i,n;this.ensureDataStoreOptions();try{if(S||(S=(e=await import("fs/promises"))==null?void 0:e.default),!S)throw new P("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new y("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions),a=await S.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(S||(S=(t=await import("fs/promises"))==null?void 0:t.default),!S)throw new P("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new y("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);await S.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await S.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(S||(S=(e=await import("fs/promises"))==null?void 0:e.default),!S)throw new P("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new y("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);return await S.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var Z=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new P("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},stringifyData:!0,...t}}async calcChecksum(e){try{return _(typeof e=="string"?e:JSON.stringify(e),"SHA-256")}catch(t){throw new Error(`Failed to calculate checksum: ${t.message}`,{cause:t})}}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),c=s.memoryCache?s.getData():await s.loadData(),m=u?await s.encodeData[1](JSON.stringify(c)):this.options.stringifyData?JSON.stringify(c):c;n.push({id:s.id,data:m,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(m):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(m=>m.id===s);if(!u)throw new y(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let m=await this.calcChecksum(a.data);if(m!==a.checksum)throw new V(`Checksum mismatch for DataStore with ID "${a.id}"!
Expected: ${a.checksum}
Has: ${m}`)}let c=a.encoded&&u.encodingEnabled()?await u.decodeData[1](typeof a.data=="string"?a.data:JSON.stringify(a.data)):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(typeof c=="string"?JSON.parse(c):c,Number(a.formatVersion),!1):await u.setData(typeof c=="string"?JSON.parse(c):c)}}async deserialize(e){return this.deserializePartial(this.stores.map(t=>t.id),e)}async loadStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(async t=>({id:t.id,data:await t.loadData()})))}async resetStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.saveDefaultData()))}async deleteStoresData(e){return Promise.allSettled(this.getStoresFiltered(e).map(t=>t.deleteData()))}static isSerializedDataStoreObjArray(e){return Array.isArray(e)&&e.every(t=>typeof t=="object"&&t!==null&&"id"in t&&"data"in t&&"formatVersion"in t&&"encoded"in t)}static isSerializedDataStoreObj(e){return typeof e=="object"&&e!==null&&"id"in e&&"data"in e&&"formatVersion"in e&&"encoded"in e}getStoresFiltered(e){return this.stores.filter(t=>typeof e>"u"?!0:Array.isArray(e)?e.includes(t.id):e(t.id))}};var j=class extends x{constructor(t=200,i="immediate",n){super(n);this.timeout=t;this.type=i}timeout;type;listeners=[];activeTimeout;queuedCall;addListener(t){this.listeners.push(t)}removeListener(t){let i=this.listeners.findIndex(n=>n===t);i!==-1&&this.listeners.splice(i,1)}removeAllListeners(){this.listeners=[]}getListeners(){return this.listeners}setTimeout(t){this.emitEvent("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emitEvent("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...o)=>{this.queuedCall=void 0,this.emitEvent("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function We(r,e=200,t="immediate",i){let n=new j(e,t,i);n.addListener(r);let o=((...a)=>n.call(...a));return o.debouncer=n,o}
if (typeof module.exports == "object" && typeof exports == "object") {
var __cp = (to, from, except, desc) => {
if ((from && typeof from === "object") || typeof from === "function") {
for (let key of Object.getOwnPropertyNames(from)) {
if (!Object.prototype.hasOwnProperty.call(to, key) && key !== except)
Object.defineProperty(to, key, {
get: () => from[key],
enumerable: !(desc = Object.getOwnPropertyDescriptor(from, key)) || desc.enumerable,
});
}
}
return to;
};
module.exports = __cp(module.exports, exports);
}
return module.exports;
}))
//# sourceMappingURL=CoreUtils.min.umd.js.map