@sv443-network/coreutils 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/CoreUtils.cjs +20 -11
- package/dist/CoreUtils.min.cjs +2 -2
- package/dist/CoreUtils.min.mjs +2 -2
- package/dist/CoreUtils.min.umd.js +2 -2
- package/dist/CoreUtils.mjs +20 -11
- package/dist/CoreUtils.umd.js +22 -13
- package/dist/lib/DataStore.d.ts +2 -2
- package/dist/lib/DataStoreEngine.d.ts +2 -2
- package/dist/lib/DataStoreSerializer.d.ts +1 -1
- package/dist/lib/Debouncer.d.ts +1 -1
- package/dist/lib/NanoEmitter.d.ts +1 -1
- package/dist/lib/TestDataStore.d.ts +2 -2
- package/dist/lib/TieredCache.d.ts +4 -4
- package/dist/lib/Translate.d.ts +1 -1
- package/dist/lib/crypto.d.ts +1 -1
- package/dist/lib/index.d.ts +13 -13
- package/dist/lib/math.d.ts +1 -1
- package/dist/lib/misc.d.ts +1 -1
- package/dist/lib/text.d.ts +1 -1
- package/package.json +18 -18
package/CHANGELOG.md
CHANGED
package/dist/CoreUtils.cjs
CHANGED
|
@@ -620,12 +620,13 @@ var DataStore = class {
|
|
|
620
620
|
await this.migrateId(this.migrateIds);
|
|
621
621
|
this.migrateIds = [];
|
|
622
622
|
}
|
|
623
|
-
const
|
|
623
|
+
const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
624
624
|
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
625
|
-
if (typeof
|
|
625
|
+
if (typeof storedDataRaw !== "string") {
|
|
626
626
|
await this.saveDefaultData();
|
|
627
627
|
return { ...this.defaultData };
|
|
628
628
|
}
|
|
629
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
629
630
|
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
630
631
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
631
632
|
let saveData = false;
|
|
@@ -919,8 +920,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
919
920
|
data = {};
|
|
920
921
|
data[name] = value;
|
|
921
922
|
await this.writeFile(data);
|
|
923
|
+
}).catch((err) => {
|
|
924
|
+
console.error("Error in setValue:", err);
|
|
925
|
+
throw err;
|
|
926
|
+
});
|
|
927
|
+
await this.fileAccessQueue.catch(() => {
|
|
922
928
|
});
|
|
923
|
-
await this.fileAccessQueue;
|
|
924
929
|
}
|
|
925
930
|
/** Deletes a value from persistent storage */
|
|
926
931
|
async deleteValue(name) {
|
|
@@ -930,8 +935,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
930
935
|
return;
|
|
931
936
|
delete data[name];
|
|
932
937
|
await this.writeFile(data);
|
|
938
|
+
}).catch((err) => {
|
|
939
|
+
console.error("Error in deleteValue:", err);
|
|
940
|
+
throw err;
|
|
941
|
+
});
|
|
942
|
+
await this.fileAccessQueue.catch(() => {
|
|
933
943
|
});
|
|
934
|
-
await this.fileAccessQueue;
|
|
935
944
|
}
|
|
936
945
|
/** Deletes the file that contains the data of this DataStore. */
|
|
937
946
|
async deleteStorage() {
|
|
@@ -1164,11 +1173,11 @@ var NanoEmitter = class {
|
|
|
1164
1173
|
once(event, cb) {
|
|
1165
1174
|
return new Promise((resolve) => {
|
|
1166
1175
|
let unsub;
|
|
1167
|
-
const onceProxy = (...args) => {
|
|
1176
|
+
const onceProxy = ((...args) => {
|
|
1168
1177
|
cb == null ? void 0 : cb(...args);
|
|
1169
1178
|
unsub == null ? void 0 : unsub();
|
|
1170
1179
|
resolve(args);
|
|
1171
|
-
};
|
|
1180
|
+
});
|
|
1172
1181
|
unsub = this.events.on(event, onceProxy);
|
|
1173
1182
|
this.eventUnsubscribes.push(unsub);
|
|
1174
1183
|
});
|
|
@@ -1222,12 +1231,12 @@ var NanoEmitter = class {
|
|
|
1222
1231
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1223
1232
|
};
|
|
1224
1233
|
for (const event of oneOf) {
|
|
1225
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1234
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1226
1235
|
checkUnsubAllEvt();
|
|
1227
1236
|
callback(event, ...args);
|
|
1228
1237
|
if (once)
|
|
1229
1238
|
checkUnsubAllEvt(true);
|
|
1230
|
-
});
|
|
1239
|
+
}));
|
|
1231
1240
|
curEvtUnsubs.push(unsub);
|
|
1232
1241
|
}
|
|
1233
1242
|
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
@@ -1241,10 +1250,10 @@ var NanoEmitter = class {
|
|
|
1241
1250
|
}
|
|
1242
1251
|
};
|
|
1243
1252
|
for (const event of allOf) {
|
|
1244
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1253
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1245
1254
|
checkUnsubAllEvt();
|
|
1246
1255
|
checkAllOf(event, ...args);
|
|
1247
|
-
});
|
|
1256
|
+
}));
|
|
1248
1257
|
curEvtUnsubs.push(unsub);
|
|
1249
1258
|
}
|
|
1250
1259
|
if (oneOf.length === 0 && allOf.length === 0)
|
|
@@ -1376,7 +1385,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1376
1385
|
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1377
1386
|
const debouncer = new Debouncer(timeout, type);
|
|
1378
1387
|
debouncer.addListener(fn);
|
|
1379
|
-
const func = (...args) => debouncer.call(...args);
|
|
1388
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1380
1389
|
func.debouncer = debouncer;
|
|
1381
1390
|
return func;
|
|
1382
1391
|
}
|
package/dist/CoreUtils.min.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var W=Object.create;var x=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(r,e)=>{for(var t in e)x(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of G(e))!X.call(r,n)&&n!==t&&x(r,n,{get:()=>e[n],enumerable:!(i=Q(e,n))||i.enumerable});return r};var N=(r,e,t)=>(t=r!=null?W(Z(r)):{},R(e||!r||!r.__esModule?x(t,"default",{value:r,enumerable:!0}):t,r)),ee=r=>R(x({},"__esModule",{value:!0}),r);var Ne={};Y(Ne,{BrowserStorageEngine:()=>k,ChecksumMismatchError:()=>T,DataStore:()=>$,DataStoreEngine:()=>v,DataStoreSerializer:()=>U,DatedError:()=>h,Debouncer:()=>O,FileStorageEngine:()=>z,MigrationError:()=>S,NanoEmitter:()=>w,ValidationError:()=>_,abtoa:()=>L,atoab:()=>q,autoPlural:()=>Se,bitSetHas:()=>te,capitalize:()=>ve,clamp:()=>y,compress:()=>P,computeHash:()=>I,consumeGen:()=>me,consumeStringGen:()=>pe,createProgressBar:()=>we,darkenColor:()=>j,debounce:()=>Ve,decompress:()=>le,defaultPbChars:()=>J,digitCount:()=>re,fetchAdvanced:()=>fe,formatNumber:()=>ie,getListLength:()=>he,hexToRgb:()=>B,insertValues:()=>xe,joinArrayReadable:()=>Ee,lightenColor:()=>ce,mapRange:()=>E,overflowVal:()=>ne,pauseFor:()=>be,pureObj:()=>ge,randRange:()=>D,randomId:()=>de,randomItem:()=>oe,randomItemIndex:()=>M,randomizeArray:()=>se,rgbToHex:()=>K,roundFixed:()=>A,scheduleExit:()=>Te,secsToTimeStr:()=>Pe,setImmediateInterval:()=>ye,setImmediateTimeoutLoop:()=>De,takeRandomItem:()=>ue,takeRandomItemIndex:()=>C,truncStr:()=>Oe,valsWithin:()=>ae});module.exports=ee(Ne);function te(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function re(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),a=e&&i?i.length:0;return n+a}function ie(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function E(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 ne(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 D(...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,a=>Math.round(E(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function A(r,e){let t=10**e;return Math.round(r*t)/t}function ae(r,e,t=10,i=.5){return Math.abs(A(r,t)-A(e,t))<=i}function oe(r){return M(r)[0]}function M(r){if(r.length===0)return[void 0,void 0];let e=D(r.length-1);return[r[e],e]}function se(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 ue(r){var e;return(e=C(r))==null?void 0:e[0]}function C(r){let[e,t]=M(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function j(r,e,t=!1){var l;r=r.trim();let i=(c,d,m,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),[c,d,m]),n,a,o,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,a,o,s]=B(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?K(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function B(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ce(r,e,t=!1){return j(r,e*-1,t)}function K(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function L(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function P(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:L(o)}async function le(r,e,t="string"){let i=r instanceof Uint8Array?r:q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function I(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(o=>o.toString(16).padStart(2,"0")).join("")}function de(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>E(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function me(r){return await(typeof r=="function"?r():r)}async function pe(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function fe(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function he(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function be(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function ge(r){return Object.assign(Object.create(null),r??{})}function ye(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function De(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function Te(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Se(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 ve(r){return r.charAt(0).toUpperCase()+r.slice(1)}var J={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function we(r,e,t=J){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function xe(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 Ee(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 Pe(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Oe(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},_=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var Fe=1,$=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let s=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(s)||s<1){let u=await this.engine.getValue(`_uucfg-${this.id}`,null);if(u){let l=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],m=(g,F,f)=>{d.push(this.engine.setValue(F,f)),d.push(this.engine.deleteValue(g))};u&&m(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,u),isNaN(l)||m(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,l),typeof c=="boolean"?m(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,c===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",Fe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),n=i!=="null"&&i!=="false",a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let o=await this.engine.deserializeData(e,n);return t<this.formatVersion&&this.migrations&&(o=await this.runMigrations(o,t)),a&&await this.setData(o),this.cachedData=this.engine.deepCopy(o)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("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 h("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))}},k=class extends v{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)}},p,z=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}),await this.fileAccessQueue}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}),await this.fileAccessQueue}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var U=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return I(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
1
|
+
"use strict";var W=Object.create;var E=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(r,e)=>{for(var t in e)E(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of G(e))!X.call(r,n)&&n!==t&&E(r,n,{get:()=>e[n],enumerable:!(i=Q(e,n))||i.enumerable});return r};var N=(r,e,t)=>(t=r!=null?W(Z(r)):{},R(e||!r||!r.__esModule?E(t,"default",{value:r,enumerable:!0}):t,r)),ee=r=>R(E({},"__esModule",{value:!0}),r);var Ne={};Y(Ne,{BrowserStorageEngine:()=>k,ChecksumMismatchError:()=>T,DataStore:()=>$,DataStoreEngine:()=>v,DataStoreSerializer:()=>U,DatedError:()=>h,Debouncer:()=>O,FileStorageEngine:()=>z,MigrationError:()=>S,NanoEmitter:()=>w,ValidationError:()=>_,abtoa:()=>L,atoab:()=>q,autoPlural:()=>Se,bitSetHas:()=>te,capitalize:()=>ve,clamp:()=>y,compress:()=>P,computeHash:()=>I,consumeGen:()=>me,consumeStringGen:()=>pe,createProgressBar:()=>we,darkenColor:()=>j,debounce:()=>Ve,decompress:()=>le,defaultPbChars:()=>J,digitCount:()=>re,fetchAdvanced:()=>fe,formatNumber:()=>ie,getListLength:()=>he,hexToRgb:()=>B,insertValues:()=>Ee,joinArrayReadable:()=>xe,lightenColor:()=>ce,mapRange:()=>x,overflowVal:()=>ne,pauseFor:()=>be,pureObj:()=>ge,randRange:()=>D,randomId:()=>de,randomItem:()=>oe,randomItemIndex:()=>M,randomizeArray:()=>se,rgbToHex:()=>K,roundFixed:()=>A,scheduleExit:()=>Te,secsToTimeStr:()=>Pe,setImmediateInterval:()=>ye,setImmediateTimeoutLoop:()=>De,takeRandomItem:()=>ue,takeRandomItemIndex:()=>C,truncStr:()=>Oe,valsWithin:()=>ae});module.exports=ee(Ne);function te(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function re(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),a=e&&i?i.length:0;return n+a}function ie(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function x(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 ne(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 D(...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,a=>Math.round(x(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function A(r,e){let t=10**e;return Math.round(r*t)/t}function ae(r,e,t=10,i=.5){return Math.abs(A(r,t)-A(e,t))<=i}function oe(r){return M(r)[0]}function M(r){if(r.length===0)return[void 0,void 0];let e=D(r.length-1);return[r[e],e]}function se(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 ue(r){var e;return(e=C(r))==null?void 0:e[0]}function C(r){let[e,t]=M(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function j(r,e,t=!1){var l;r=r.trim();let i=(c,m,d,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),[c,m,d]),n,a,o,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,a,o,s]=B(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?K(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function B(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ce(r,e,t=!1){return j(r,e*-1,t)}function K(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function L(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function P(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:L(o)}async function le(r,e,t="string"){let i=r instanceof Uint8Array?r:q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function I(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(o=>o.toString(16).padStart(2,"0")).join("")}function de(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>x(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function me(r){return await(typeof r=="function"?r():r)}async function pe(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function fe(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function he(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function be(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function ge(r){return Object.assign(Object.create(null),r??{})}function ye(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function De(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function Te(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Se(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 ve(r){return r.charAt(0).toUpperCase()+r.slice(1)}var J={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function we(r,e,t=J){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function Ee(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 xe(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 Pe(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Oe(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},_=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var Fe=1,$=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(u)||u<1){let l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),m=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],g=(F,f,b)=>{d.push(this.engine.setValue(f,b)),d.push(this.engine.deleteValue(F))};l&&g(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||g(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof m=="boolean"?g(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,m===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",Fe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),a=n!=="null"&&n!=="false",o=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),o=!0);let s=await this.engine.deserializeData(i,a);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),o&&await this.setData(s),this.cachedData=this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("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 h("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))}},k=class extends v{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)}},p,z=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var U=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return I(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
2
2
|
Expected: ${n.checksum}
|
|
3
|
-
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 H=()=>({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 w=class{events=H();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let
|
|
3
|
+
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 H=()=>({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 w=class{events=H();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=((...o)=>{t==null||t(...o),n==null||n(),i(o)});n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let m=[],d=(f=!1)=>{if(!(!(l!=null&&l.aborted)&&!f)){for(let b of m)b();m.splice(0,m.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(b=>!m.includes(b))}};for(let f of o){let b=this.events.on(f,((...V)=>{d(),c(f,...V),u&&d(!0)}));m.push(b)}let g=new Set,F=(f,...b)=>{d(),g.add(f),g.size===s.length&&(c(f,...b),u&&d(!0))};for(let f of s){let b=this.events.on(f,((...V)=>{d(),F(f,...V)}));m.push(b)}if(o.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");t.push(()=>d(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var O=class extends w{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}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.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 Ve(r,e=200,t="immediate"){let i=new O(e,t);i.addListener(r);let n=((...a)=>i.call(...a));return n.debouncer=i,n}
|
|
4
4
|
//# sourceMappingURL=CoreUtils.min.cjs.map
|
package/dist/CoreUtils.min.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function J(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function H(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),a=e&&i?i.length:0;return n+a}function W(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function P(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 Q(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 D(...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,a=>Math.round(P(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function G(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function Y(r){return N(r)[0]}function N(r){if(r.length===0)return[void 0,void 0];let e=D(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 te(r){var e;return(e=U(r))==null?void 0:e[0]}function U(r){let[e,t]=N(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var l;r=r.trim();let i=(c,d,m,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),[c,d,m]),n,a,o,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,a,o,s]=C(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?j(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function C(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ne(r,e,t=!1){return R(r,e*-1,t)}function j(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function K(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function O(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:B(o)}async function se(r,e,t="string"){let i=r instanceof Uint8Array?r:K((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function A(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(o=>o.toString(16).padStart(2,"0")).join("")}function ue(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>P(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function le(r){return await(typeof r=="function"?r():r)}async function de(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function me(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function pe(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function fe(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function he(r){return Object.assign(Object.create(null),r??{})}function be(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function ge(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ye(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Te(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 Se(r){return r.charAt(0).toUpperCase()+r.slice(1)}var L={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ve(r,e,t=L){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function we(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 xe(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 Ee(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Pe(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},M=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var q=1,I=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await O(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await O(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let s=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(s)||s<1){let u=await this.engine.getValue(`_uucfg-${this.id}`,null);if(u){let l=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],m=(g,x,f)=>{d.push(this.engine.setValue(x,f)),d.push(this.engine.deleteValue(g))};u&&m(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,u),isNaN(l)||m(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,l),typeof c=="boolean"?m(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,c===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",q)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),n=i!=="null"&&i!=="false",a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let o=await this.engine.deserializeData(e,n);return t<this.formatVersion&&this.migrations&&(o=await this.runMigrations(o,t)),a&&await this.setData(o),this.cachedData=this.engine.deepCopy(o)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("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 h("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))}},_=class extends v{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)}},p,$=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}),await this.fileAccessQueue}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}),await this.fileAccessQueue}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var k=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return A(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
1
|
+
function J(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function H(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),a=e&&i?i.length:0;return n+a}function W(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function P(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 Q(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 D(...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,a=>Math.round(P(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function V(r,e){let t=10**e;return Math.round(r*t)/t}function G(r,e,t=10,i=.5){return Math.abs(V(r,t)-V(e,t))<=i}function Y(r){return N(r)[0]}function N(r){if(r.length===0)return[void 0,void 0];let e=D(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 te(r){var e;return(e=U(r))==null?void 0:e[0]}function U(r){let[e,t]=N(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function R(r,e,t=!1){var l;r=r.trim();let i=(c,m,d,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),[c,m,d]),n,a,o,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,a,o,s]=C(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?j(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function C(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ne(r,e,t=!1){return R(r,e*-1,t)}function j(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function B(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function K(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function O(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:B(o)}async function se(r,e,t="string"){let i=r instanceof Uint8Array?r:K((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function A(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(o=>o.toString(16).padStart(2,"0")).join("")}function ue(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>P(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function le(r){return await(typeof r=="function"?r():r)}async function de(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function me(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function pe(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function fe(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function he(r){return Object.assign(Object.create(null),r??{})}function be(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function ge(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function ye(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Te(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 Se(r){return r.charAt(0).toUpperCase()+r.slice(1)}var L={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function ve(r,e,t=L){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function we(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 Ee(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 xe(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Pe(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 b=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends b{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends b{constructor(e,t){super(e,t),this.name="MigrationError"}},M=class extends b{constructor(e,t){super(e,t),this.name="ValidationError"}};var q=1,I=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await O(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await O(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(u)||u<1){let l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),m=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],g=(E,f,h)=>{d.push(this.engine.setValue(f,h)),d.push(this.engine.deleteValue(E))};l&&g(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||g(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof m=="boolean"?g(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,m===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",q)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),a=n!=="null"&&n!=="false",o=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),o=!0);let s=await this.engine.deserializeData(i,a);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),o&&await this.setData(s),this.cachedData=this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new b("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 b("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))}},_=class extends v{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)}},p,$=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new b("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var k=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return A(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
2
2
|
Expected: ${n.checksum}
|
|
3
|
-
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 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 w=class{events=z();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let
|
|
3
|
+
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 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 w=class{events=z();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=((...o)=>{t==null||t(...o),n==null||n(),i(o)});n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let m=[],d=(f=!1)=>{if(!(!(l!=null&&l.aborted)&&!f)){for(let h of m)h();m.splice(0,m.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(h=>!m.includes(h))}};for(let f of o){let h=this.events.on(f,((...x)=>{d(),c(f,...x),u&&d(!0)}));m.push(h)}let g=new Set,E=(f,...h)=>{d(),g.add(f),g.size===s.length&&(c(f,...h),u&&d(!0))};for(let f of s){let h=this.events.on(f,((...x)=>{d(),E(f,...x)}));m.push(h)}if(o.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");t.push(()=>d(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var F=class extends w{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}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.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 je(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=((...a)=>i.call(...a));return n.debouncer=i,n}export{_ as BrowserStorageEngine,T as ChecksumMismatchError,I as DataStore,v as DataStoreEngine,k as DataStoreSerializer,b as DatedError,F as Debouncer,$ as FileStorageEngine,S as MigrationError,w as NanoEmitter,M as ValidationError,B as abtoa,K as atoab,Te as autoPlural,J as bitSetHas,Se as capitalize,y as clamp,O as compress,A as computeHash,le as consumeGen,de as consumeStringGen,ve as createProgressBar,R as darkenColor,je as debounce,se as decompress,L as defaultPbChars,H as digitCount,me as fetchAdvanced,W as formatNumber,pe as getListLength,C as hexToRgb,we as insertValues,Ee as joinArrayReadable,ne as lightenColor,P as mapRange,Q as overflowVal,fe as pauseFor,he as pureObj,D as randRange,ue as randomId,Y as randomItem,N as randomItemIndex,ee as randomizeArray,j as rgbToHex,V as roundFixed,ye as scheduleExit,xe as secsToTimeStr,be as setImmediateInterval,ge as setImmediateTimeoutLoop,te as takeRandomItem,U as takeRandomItemIndex,Pe as truncStr,G as valsWithin};
|
|
4
4
|
//# sourceMappingURL=CoreUtils.min.mjs.map
|
|
@@ -16,9 +16,9 @@
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
"use strict";var W=Object.create;var x=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(r,e)=>{for(var t in e)x(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of G(e))!X.call(r,n)&&n!==t&&x(r,n,{get:()=>e[n],enumerable:!(i=Q(e,n))||i.enumerable});return r};var N=(r,e,t)=>(t=r!=null?W(Z(r)):{},R(e||!r||!r.__esModule?x(t,"default",{value:r,enumerable:!0}):t,r)),ee=r=>R(x({},"__esModule",{value:!0}),r);var Ne={};Y(Ne,{BrowserStorageEngine:()=>k,ChecksumMismatchError:()=>T,DataStore:()=>$,DataStoreEngine:()=>v,DataStoreSerializer:()=>U,DatedError:()=>h,Debouncer:()=>O,FileStorageEngine:()=>z,MigrationError:()=>S,NanoEmitter:()=>w,ValidationError:()=>_,abtoa:()=>L,atoab:()=>q,autoPlural:()=>Se,bitSetHas:()=>te,capitalize:()=>ve,clamp:()=>y,compress:()=>P,computeHash:()=>I,consumeGen:()=>me,consumeStringGen:()=>pe,createProgressBar:()=>we,darkenColor:()=>j,debounce:()=>Ve,decompress:()=>le,defaultPbChars:()=>J,digitCount:()=>re,fetchAdvanced:()=>fe,formatNumber:()=>ie,getListLength:()=>he,hexToRgb:()=>B,insertValues:()=>xe,joinArrayReadable:()=>Ee,lightenColor:()=>ce,mapRange:()=>E,overflowVal:()=>ne,pauseFor:()=>be,pureObj:()=>ge,randRange:()=>D,randomId:()=>de,randomItem:()=>oe,randomItemIndex:()=>M,randomizeArray:()=>se,rgbToHex:()=>K,roundFixed:()=>A,scheduleExit:()=>Te,secsToTimeStr:()=>Pe,setImmediateInterval:()=>ye,setImmediateTimeoutLoop:()=>De,takeRandomItem:()=>ue,takeRandomItemIndex:()=>C,truncStr:()=>Oe,valsWithin:()=>ae});module.exports=ee(Ne);function te(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function re(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),a=e&&i?i.length:0;return n+a}function ie(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function E(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 ne(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 D(...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,a=>Math.round(E(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function A(r,e){let t=10**e;return Math.round(r*t)/t}function ae(r,e,t=10,i=.5){return Math.abs(A(r,t)-A(e,t))<=i}function oe(r){return M(r)[0]}function M(r){if(r.length===0)return[void 0,void 0];let e=D(r.length-1);return[r[e],e]}function se(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 ue(r){var e;return(e=C(r))==null?void 0:e[0]}function C(r){let[e,t]=M(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function j(r,e,t=!1){var l;r=r.trim();let i=(c,d,m,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),[c,d,m]),n,a,o,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,a,o,s]=B(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?K(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function B(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ce(r,e,t=!1){return j(r,e*-1,t)}function K(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function L(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function P(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:L(o)}async function le(r,e,t="string"){let i=r instanceof Uint8Array?r:q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function I(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(o=>o.toString(16).padStart(2,"0")).join("")}function de(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>E(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function me(r){return await(typeof r=="function"?r():r)}async function pe(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function fe(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function he(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function be(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function ge(r){return Object.assign(Object.create(null),r??{})}function ye(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function De(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function Te(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Se(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 ve(r){return r.charAt(0).toUpperCase()+r.slice(1)}var J={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function we(r,e,t=J){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function xe(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 Ee(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 Pe(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Oe(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},_=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var Fe=1,$=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let s=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(s)||s<1){let u=await this.engine.getValue(`_uucfg-${this.id}`,null);if(u){let l=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),c=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],m=(g,F,f)=>{d.push(this.engine.setValue(F,f)),d.push(this.engine.deleteValue(g))};u&&m(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,u),isNaN(l)||m(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,l),typeof c=="boolean"?m(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,c===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",Fe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,JSON.stringify(this.defaultData)),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),n=i!=="null"&&i!=="false",a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let o=await this.engine.deserializeData(e,n);return t<this.formatVersion&&this.migrations&&(o=await this.runMigrations(o,t)),a&&await this.setData(o),this.cachedData=this.engine.deepCopy(o)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("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 h("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))}},k=class extends v{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)}},p,z=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,await this.writeFile(i)}),await this.fileAccessQueue}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}),await this.fileAccessQueue}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var U=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return I(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
19
|
+
"use strict";var W=Object.create;var E=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(r,e)=>{for(var t in e)E(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of G(e))!X.call(r,n)&&n!==t&&E(r,n,{get:()=>e[n],enumerable:!(i=Q(e,n))||i.enumerable});return r};var N=(r,e,t)=>(t=r!=null?W(Z(r)):{},R(e||!r||!r.__esModule?E(t,"default",{value:r,enumerable:!0}):t,r)),ee=r=>R(E({},"__esModule",{value:!0}),r);var Ne={};Y(Ne,{BrowserStorageEngine:()=>k,ChecksumMismatchError:()=>T,DataStore:()=>$,DataStoreEngine:()=>v,DataStoreSerializer:()=>U,DatedError:()=>h,Debouncer:()=>O,FileStorageEngine:()=>z,MigrationError:()=>S,NanoEmitter:()=>w,ValidationError:()=>_,abtoa:()=>L,atoab:()=>q,autoPlural:()=>Se,bitSetHas:()=>te,capitalize:()=>ve,clamp:()=>y,compress:()=>P,computeHash:()=>I,consumeGen:()=>me,consumeStringGen:()=>pe,createProgressBar:()=>we,darkenColor:()=>j,debounce:()=>Ve,decompress:()=>le,defaultPbChars:()=>J,digitCount:()=>re,fetchAdvanced:()=>fe,formatNumber:()=>ie,getListLength:()=>he,hexToRgb:()=>B,insertValues:()=>Ee,joinArrayReadable:()=>xe,lightenColor:()=>ce,mapRange:()=>x,overflowVal:()=>ne,pauseFor:()=>be,pureObj:()=>ge,randRange:()=>D,randomId:()=>de,randomItem:()=>oe,randomItemIndex:()=>M,randomizeArray:()=>se,rgbToHex:()=>K,roundFixed:()=>A,scheduleExit:()=>Te,secsToTimeStr:()=>Pe,setImmediateInterval:()=>ye,setImmediateTimeoutLoop:()=>De,takeRandomItem:()=>ue,takeRandomItemIndex:()=>C,truncStr:()=>Oe,valsWithin:()=>ae});module.exports=ee(Ne);function te(r,e){return(r&e)===e}function y(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function re(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),a=e&&i?i.length:0;return n+a}function ie(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function x(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 ne(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 D(...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,a=>Math.round(x(a,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function A(r,e){let t=10**e;return Math.round(r*t)/t}function ae(r,e,t=10,i=.5){return Math.abs(A(r,t)-A(e,t))<=i}function oe(r){return M(r)[0]}function M(r){if(r.length===0)return[void 0,void 0];let e=D(r.length-1);return[r[e],e]}function se(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 ue(r){var e;return(e=C(r))==null?void 0:e[0]}function C(r){let[e,t]=M(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function j(r,e,t=!1){var l;r=r.trim();let i=(c,m,d,g)=>(c=Math.max(0,Math.min(255,c-c*g/100)),m=Math.max(0,Math.min(255,m-m*g/100)),d=Math.max(0,Math.min(255,d-d*g/100)),[c,m,d]),n,a,o,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,a,o,s]=B(r);else if(r.startsWith("rgb")){let c=(l=r.match(/\d+(\.\d+)?/g))==null?void 0:l.map(Number);if(!c)throw new TypeError("Invalid RGB/RGBA color format");[n,a,o,s]=c}else throw new TypeError("Unsupported color format");return[n,a,o]=i(n,a,o,e),u?K(n,a,o,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${a}, ${o}, ${s??NaN})`:`rgb(${n}, ${a}, ${o})`}function B(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(o=>o+o).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,a=t&255;return[y(i,0,255),y(n,0,255),y(a,0,255),typeof e=="number"?y(e,0,1):void 0]}function ce(r,e,t=!1){return j(r,e*-1,t)}function K(r,e,t,i,n=!0,a=!1){let o=s=>y(Math.round(s),0,255).toString(16).padStart(2,"0")[a?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${o(r)}${o(e)}${o(t)}${i?o(i*255):""}`}function L(r){return btoa(new Uint8Array(r).reduce((e,t)=>e+String.fromCharCode(t),""))}function q(r){return Uint8Array.from(atob(r),e=>e.charCodeAt(0))}async function P(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),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:L(o)}async function le(r,e,t="string"){let i=r instanceof Uint8Array?r:q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),a=n.writable.getWriter();a.write(i),a.close();let o=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?o:new TextDecoder().decode(o)}async function I(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(o=>o.toString(16).padStart(2,"0")).join("")}function de(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=[],a=i?[0,1]:[0];if(t){let o=new Uint8Array(r);crypto.getRandomValues(o),n=Array.from(o,s=>x(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(o=>/[a-zA-Z]/.test(o))?n.map(o=>a[D(0,a.length-1,t)]===1?o.toUpperCase():o).join(""):n.join("")}async function me(r){return await(typeof r=="function"?r():r)}async function pe(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function fe(r,e={}){let{timeout:t=1e4}=e,i=new AbortController,{signal:n,...a}=e;n==null||n.addEventListener("abort",()=>i.abort());let o={},s;t>=0&&(s=setTimeout(()=>i.abort(),t),o={signal:i.signal});try{let u=await fetch(r,{...a,...o});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new Error("Error while calling fetch",{cause:u})}}function he(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function be(r,e,t=!1){return new Promise((i,n)=>{let a=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(a),t?n(new Error("The pause was aborted")):i()})})}function ge(r){return Object.assign(Object.create(null),r??{})}function ye(r,e,t){let i,n=()=>clearInterval(i),a=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),a(),i=setInterval(a,e)}function De(r,e,t){let i,n=()=>clearTimeout(i),a=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(a,e)};t==null||t.addEventListener("abort",n),a()}function Te(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)t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno)t=()=>Deno.exit(r);else throw new Error("Cannot exit the process, no exit method available");setTimeout(t,e)}function Se(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 ve(r){return r.charAt(0).toUpperCase()+r.slice(1)}var J={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function we(r,e,t=J){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,a="";n>=.75?a=t[75]:n>=.5?a=t[50]:n>=.25&&(a=t[25]);let o=t[100].repeat(i),s=t[0].repeat(e-i-(a?1:0));return`${o}${a}${s}`}function Ee(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 xe(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 Pe(r){if(r<0)throw new TypeError("Seconds must be a positive number");let e=Math.floor(r/3600),t=Math.floor(r%3600/60),i=Math.floor(r%60);return[e?e+":":"",String(t).padStart(t>0||e>0?2:1,"0"),":",String(i).padStart(i>0||t>0||e>0?2:1,"0")].join("")}function Oe(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 h=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends h{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},S=class extends h{constructor(e,t){super(e,t),this.name="MigrationError"}},_=class extends h{constructor(e,t){super(e,t),this.name="ValidationError"}};var Fe=1,$=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){var t;if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.cachedData=e.defaultData,this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.encodeData=e.encodeData,this.decodeData=e.decodeData,this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,typeof e.compressionFormat>"u"&&(this.compressionFormat=e.compressionFormat=((t=e.encodeData)==null?void 0:t[0])??"deflate-raw"),typeof e.compressionFormat=="string")this.encodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")],this.decodeData=[e.compressionFormat,async i=>await P(i,e.compressionFormat,"string")];else if("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 throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");this.engine.setDataStoreOptions(e)}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0));if(isNaN(u)||u<1){let l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),m=await this.engine.getValue(`_uucfgenc-${this.id}`,null),d=[],g=(F,f,b)=>{d.push(this.engine.setValue(f,b)),d.push(this.engine.deleteValue(F))};l&&g(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||g(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof m=="boolean"?g(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,m===!0&&!!this.compressionFormat||null):d.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),await Promise.allSettled(d)}await this.engine.setValue("__ds_fmt_ver",Fe)}}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`__ds-${this.id}-dat`,null),t=Number(await this.engine.getValue(`__ds-${this.id}-ver`,NaN));if(typeof e!="string")return await this.saveDefaultData(),{...this.defaultData};let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),a=n!=="null"&&n!=="false",o=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),o=!0);let s=await this.engine.deserializeData(i,a);return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),o&&await this.setData(s),this.cachedData=this.engine.deepCopy(s)}catch(e){return console.warn("Error while parsing JSON data, resetting it to the default value.",e),await this.saveDefaultData(),this.defaultData}}getData(){return this.engine.deepCopy(this.cachedData)}setData(e){return this.cachedData=e,new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.cachedData=this.defaultData,await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,this.formatVersion),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`),this.engine.deleteValue(`__ds-${this.id}-ver`),this.engine.deleteValue(`__ds-${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}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,a=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),o=t;for(let[s,u]of a){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,o=t=l}catch(c){if(!i)throw new S(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.getData()}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n)),this.engine.setValue(`__ds-${this.id}-ver`,o),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.cachedData={...n}}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,a,o]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`__ds-${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`__ds-${i}-ver`,NaN),this.engine.getValue(`__ds-${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(a))return;let s=await this.engine.deserializeData(n,o);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s)),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`__ds-${i}-dat`),this.engine.deleteValue(`__ds-${i}-ver`),this.engine.deleteValue(`__ds-${i}-enf`)])}))}};var v=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var a,o,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((a=this.dataStoreOptions)!=null&&a.encodeData)||!((o=this.dataStoreOptions)!=null&&o.decodeData))return i;let n=(l=(u=(s=this.dataStoreOptions)==null?void 0:s.encodeData)==null?void 0:u[1])==null?void 0:l.call(u,i);return n instanceof Promise?await n:n}async deserializeData(e,t){var n,a,o;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(o=(a=this.dataStoreOptions.decodeData)==null?void 0:a[1])==null?void 0:o.call(a,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new h("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 h("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))}},k=class extends v{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)}},p,z=class extends v{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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),o=await p.readFile(a,"utf-8");return o?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,o))??o):void 0}catch{return}}async writeFile(e){var t,i,n,a;this.ensureDataStoreOptions();try{if(p||(p=(t=await import("fs/promises"))==null?void 0:t.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.mkdir(o.slice(0,o.lastIndexOf(o.includes("/")?"/":"\\")),{recursive:!0}),await p.writeFile(o,await((a=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:a.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(o){console.error("Error writing file:",o)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];return typeof n>"u"?t:n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={}),i[e]=t,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(p||(p=(e=await import("fs/promises"))==null?void 0:e.default),!p)throw new h("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new Error("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await p.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var U=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new Error("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,...t}}async calcChecksum(e){return I(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[];for(let o of this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id))){let s=!!(t&&o.encodingEnabled()&&((a=o.encodeData)!=null&&a[1])),u=s?await o.encodeData[1](JSON.stringify(o.getData())):JSON.stringify(o.getData());n.push({id:o.id,data:u,formatVersion:o.formatVersion,encoded:s,checksum:this.options.addChecksum?await this.calcChecksum(u):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.");for(let n of i.filter(a=>typeof e=="function"?e(a.id):e.includes(a.id))){let a=this.stores.find(s=>s.id===n.id);if(!a)throw new Error(`DataStore instance with ID "${n.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof n.checksum=="string"){let s=await this.calcChecksum(n.data);if(s!==n.checksum)throw new T(`Checksum mismatch for DataStore with ID "${n.id}"!
|
|
20
20
|
Expected: ${n.checksum}
|
|
21
|
-
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 H=()=>({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 w=class{events=H();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=(...o)=>{t==null||t(...o),n==null||n(),i(o)};n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let
|
|
21
|
+
Has: ${s}`)}let o=n.encoded&&a.encodingEnabled()?await a.decodeData[1](n.data):n.data;n.formatVersion&&!isNaN(Number(n.formatVersion))&&Number(n.formatVersion)<a.formatVersion?await a.runMigrations(JSON.parse(o),Number(n.formatVersion),!1):await a.setData(JSON.parse(o))}}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 H=()=>({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 w=class{events=H();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(a=>a!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,a=((...o)=>{t==null||t(...o),n==null||n(),i(o)});n=this.events.on(e,a),this.eventUnsubscribes.push(n)})}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 a={allOf:[],oneOf:[],once:!1,...n},{oneOf:o,allOf:s,once:u,signal:l,callback:c}=a;if(l!=null&&l.aborted)return i;let m=[],d=(f=!1)=>{if(!(!(l!=null&&l.aborted)&&!f)){for(let b of m)b();m.splice(0,m.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(b=>!m.includes(b))}};for(let f of o){let b=this.events.on(f,((...V)=>{d(),c(f,...V),u&&d(!0)}));m.push(b)}let g=new Set,F=(f,...b)=>{d(),g.add(f),g.size===s.length&&(c(f,...b),u&&d(!0))};for(let f of s){let b=this.events.on(f,((...V)=>{d(),F(f,...V)}));m.push(b)}if(o.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");t.push(()=>d(!0))}return i}emit(e,...t){return this.emitterOptions.publicEmit?(this.events.emit(e,...t),!0):!1}unsubscribeAll(){for(let e of this.eventUnsubscribes)e();this.eventUnsubscribes=[]}};var O=class extends w{constructor(t=200,i="immediate"){super();this.timeout=t;this.type=i}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.emit("change",this.timeout=t,this.type)}getTimeout(){return this.timeout}isTimeoutActive(){return typeof this.activeTimeout<"u"}setType(t){this.emit("change",this.timeout,this.type=t)}getType(){return this.type}call(...t){let i=(...a)=>{this.queuedCall=void 0,this.emit("call",...a),this.listeners.forEach(o=>o.call(this,...a))},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 Ve(r,e=200,t="immediate"){let i=new O(e,t);i.addListener(r);let n=((...a)=>i.call(...a));return n.debouncer=i,n}
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
|
package/dist/CoreUtils.mjs
CHANGED
|
@@ -532,12 +532,13 @@ var DataStore = class {
|
|
|
532
532
|
await this.migrateId(this.migrateIds);
|
|
533
533
|
this.migrateIds = [];
|
|
534
534
|
}
|
|
535
|
-
const
|
|
535
|
+
const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
536
536
|
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
537
|
-
if (typeof
|
|
537
|
+
if (typeof storedDataRaw !== "string") {
|
|
538
538
|
await this.saveDefaultData();
|
|
539
539
|
return { ...this.defaultData };
|
|
540
540
|
}
|
|
541
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
541
542
|
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
542
543
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
543
544
|
let saveData = false;
|
|
@@ -831,8 +832,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
831
832
|
data = {};
|
|
832
833
|
data[name] = value;
|
|
833
834
|
await this.writeFile(data);
|
|
835
|
+
}).catch((err) => {
|
|
836
|
+
console.error("Error in setValue:", err);
|
|
837
|
+
throw err;
|
|
838
|
+
});
|
|
839
|
+
await this.fileAccessQueue.catch(() => {
|
|
834
840
|
});
|
|
835
|
-
await this.fileAccessQueue;
|
|
836
841
|
}
|
|
837
842
|
/** Deletes a value from persistent storage */
|
|
838
843
|
async deleteValue(name) {
|
|
@@ -842,8 +847,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
842
847
|
return;
|
|
843
848
|
delete data[name];
|
|
844
849
|
await this.writeFile(data);
|
|
850
|
+
}).catch((err) => {
|
|
851
|
+
console.error("Error in deleteValue:", err);
|
|
852
|
+
throw err;
|
|
853
|
+
});
|
|
854
|
+
await this.fileAccessQueue.catch(() => {
|
|
845
855
|
});
|
|
846
|
-
await this.fileAccessQueue;
|
|
847
856
|
}
|
|
848
857
|
/** Deletes the file that contains the data of this DataStore. */
|
|
849
858
|
async deleteStorage() {
|
|
@@ -1076,11 +1085,11 @@ var NanoEmitter = class {
|
|
|
1076
1085
|
once(event, cb) {
|
|
1077
1086
|
return new Promise((resolve) => {
|
|
1078
1087
|
let unsub;
|
|
1079
|
-
const onceProxy = (...args) => {
|
|
1088
|
+
const onceProxy = ((...args) => {
|
|
1080
1089
|
cb == null ? void 0 : cb(...args);
|
|
1081
1090
|
unsub == null ? void 0 : unsub();
|
|
1082
1091
|
resolve(args);
|
|
1083
|
-
};
|
|
1092
|
+
});
|
|
1084
1093
|
unsub = this.events.on(event, onceProxy);
|
|
1085
1094
|
this.eventUnsubscribes.push(unsub);
|
|
1086
1095
|
});
|
|
@@ -1134,12 +1143,12 @@ var NanoEmitter = class {
|
|
|
1134
1143
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1135
1144
|
};
|
|
1136
1145
|
for (const event of oneOf) {
|
|
1137
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1146
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1138
1147
|
checkUnsubAllEvt();
|
|
1139
1148
|
callback(event, ...args);
|
|
1140
1149
|
if (once)
|
|
1141
1150
|
checkUnsubAllEvt(true);
|
|
1142
|
-
});
|
|
1151
|
+
}));
|
|
1143
1152
|
curEvtUnsubs.push(unsub);
|
|
1144
1153
|
}
|
|
1145
1154
|
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
@@ -1153,10 +1162,10 @@ var NanoEmitter = class {
|
|
|
1153
1162
|
}
|
|
1154
1163
|
};
|
|
1155
1164
|
for (const event of allOf) {
|
|
1156
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1165
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1157
1166
|
checkUnsubAllEvt();
|
|
1158
1167
|
checkAllOf(event, ...args);
|
|
1159
|
-
});
|
|
1168
|
+
}));
|
|
1160
1169
|
curEvtUnsubs.push(unsub);
|
|
1161
1170
|
}
|
|
1162
1171
|
if (oneOf.length === 0 && allOf.length === 0)
|
|
@@ -1288,7 +1297,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1288
1297
|
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1289
1298
|
const debouncer = new Debouncer(timeout, type);
|
|
1290
1299
|
debouncer.addListener(fn);
|
|
1291
|
-
const func = (...args) => debouncer.call(...args);
|
|
1300
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1292
1301
|
func.debouncer = debouncer;
|
|
1293
1302
|
return func;
|
|
1294
1303
|
}
|
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -704,12 +704,13 @@ var DataStore = class {
|
|
|
704
704
|
yield this.migrateId(this.migrateIds);
|
|
705
705
|
this.migrateIds = [];
|
|
706
706
|
}
|
|
707
|
-
const
|
|
707
|
+
const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
708
708
|
let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
709
|
-
if (typeof
|
|
709
|
+
if (typeof storedDataRaw !== "string") {
|
|
710
710
|
yield this.saveDefaultData();
|
|
711
711
|
return __spreadValues({}, this.defaultData);
|
|
712
712
|
}
|
|
713
|
+
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
713
714
|
const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
714
715
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
715
716
|
let saveData = false;
|
|
@@ -1027,8 +1028,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1027
1028
|
data = {};
|
|
1028
1029
|
data[name] = value;
|
|
1029
1030
|
yield this.writeFile(data);
|
|
1030
|
-
}))
|
|
1031
|
-
|
|
1031
|
+
})).catch((err) => {
|
|
1032
|
+
console.error("Error in setValue:", err);
|
|
1033
|
+
throw err;
|
|
1034
|
+
});
|
|
1035
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1036
|
+
});
|
|
1032
1037
|
});
|
|
1033
1038
|
}
|
|
1034
1039
|
/** Deletes a value from persistent storage */
|
|
@@ -1040,8 +1045,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1040
1045
|
return;
|
|
1041
1046
|
delete data[name];
|
|
1042
1047
|
yield this.writeFile(data);
|
|
1043
|
-
}))
|
|
1044
|
-
|
|
1048
|
+
})).catch((err) => {
|
|
1049
|
+
console.error("Error in deleteValue:", err);
|
|
1050
|
+
throw err;
|
|
1051
|
+
});
|
|
1052
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1053
|
+
});
|
|
1045
1054
|
});
|
|
1046
1055
|
}
|
|
1047
1056
|
/** Deletes the file that contains the data of this DataStore. */
|
|
@@ -1294,11 +1303,11 @@ var NanoEmitter = class {
|
|
|
1294
1303
|
once(event, cb) {
|
|
1295
1304
|
return new Promise((resolve) => {
|
|
1296
1305
|
let unsub;
|
|
1297
|
-
const onceProxy = (...args) => {
|
|
1306
|
+
const onceProxy = ((...args) => {
|
|
1298
1307
|
cb == null ? void 0 : cb(...args);
|
|
1299
1308
|
unsub == null ? void 0 : unsub();
|
|
1300
1309
|
resolve(args);
|
|
1301
|
-
};
|
|
1310
|
+
});
|
|
1302
1311
|
unsub = this.events.on(event, onceProxy);
|
|
1303
1312
|
this.eventUnsubscribes.push(unsub);
|
|
1304
1313
|
});
|
|
@@ -1351,12 +1360,12 @@ var NanoEmitter = class {
|
|
|
1351
1360
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1352
1361
|
};
|
|
1353
1362
|
for (const event of oneOf) {
|
|
1354
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1363
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1355
1364
|
checkUnsubAllEvt();
|
|
1356
1365
|
callback(event, ...args);
|
|
1357
1366
|
if (once)
|
|
1358
1367
|
checkUnsubAllEvt(true);
|
|
1359
|
-
});
|
|
1368
|
+
}));
|
|
1360
1369
|
curEvtUnsubs.push(unsub);
|
|
1361
1370
|
}
|
|
1362
1371
|
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
@@ -1370,10 +1379,10 @@ var NanoEmitter = class {
|
|
|
1370
1379
|
}
|
|
1371
1380
|
};
|
|
1372
1381
|
for (const event of allOf) {
|
|
1373
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1382
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1374
1383
|
checkUnsubAllEvt();
|
|
1375
1384
|
checkAllOf(event, ...args);
|
|
1376
|
-
});
|
|
1385
|
+
}));
|
|
1377
1386
|
curEvtUnsubs.push(unsub);
|
|
1378
1387
|
}
|
|
1379
1388
|
if (oneOf.length === 0 && allOf.length === 0)
|
|
@@ -1505,7 +1514,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1505
1514
|
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1506
1515
|
const debouncer = new Debouncer(timeout, type);
|
|
1507
1516
|
debouncer.addListener(fn);
|
|
1508
|
-
const func = (...args) => debouncer.call(...args);
|
|
1517
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1509
1518
|
func.debouncer = debouncer;
|
|
1510
1519
|
return func;
|
|
1511
1520
|
}
|
package/dist/lib/DataStore.d.ts
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* @module DataStore
|
|
3
3
|
* This module contains the DataStore class, which is a general purpose, sync and async persistent database for JSON-serializable data - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-datastore)
|
|
4
4
|
*/
|
|
5
|
-
import type { DataStoreEngine } from "./DataStoreEngine.
|
|
6
|
-
import type { LooseUnion, Prettify, SerializableVal } from "./types.
|
|
5
|
+
import type { DataStoreEngine } from "./DataStoreEngine.ts";
|
|
6
|
+
import type { LooseUnion, Prettify, SerializableVal } from "./types.ts";
|
|
7
7
|
/** Function that takes the data in the old format and returns the data in the new format. Also supports an asynchronous migration. */
|
|
8
8
|
type MigrationFunc = (oldData: any) => any | Promise<any>;
|
|
9
9
|
/** Dictionary of format version numbers and the function that migrates to them from the previous whole integer */
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* This module contains the `DataStoreEngine` class and some of its subclasses like `FileStorageEngine` and `BrowserStorageEngine`.
|
|
4
4
|
* [See the documentation for more info.](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-datastoreengine)
|
|
5
5
|
*/
|
|
6
|
-
import type { DataStoreData, DataStoreOptions } from "./DataStore.
|
|
7
|
-
import type { Prettify, SerializableVal } from "./types.
|
|
6
|
+
import type { DataStoreData, DataStoreOptions } from "./DataStore.ts";
|
|
7
|
+
import type { Prettify, SerializableVal } from "./types.ts";
|
|
8
8
|
/** Contains the only properties of {@linkcode DataStoreOptions} that are relevant to the {@linkcode DataStoreEngine} class. */
|
|
9
9
|
export type DataStoreEngineDSOptions<TData extends DataStoreData> = Prettify<Pick<DataStoreOptions<TData>, "decodeData" | "encodeData" | "id">>;
|
|
10
10
|
export interface DataStoreEngine<TData extends DataStoreData> {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module DataStoreSerializer
|
|
3
3
|
* This module contains the DataStoreSerializer class, which allows you to import and export serialized DataStore data - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#datastoreserializer)
|
|
4
4
|
*/
|
|
5
|
-
import type { DataStore, DataStoreData } from "./DataStore.
|
|
5
|
+
import type { DataStore, DataStoreData } from "./DataStore.ts";
|
|
6
6
|
/** Options for the DataStoreSerializer class */
|
|
7
7
|
export type DataStoreSerializerOptions = {
|
|
8
8
|
/** Whether to add a checksum to the exported data. Defaults to `true` */
|
package/dist/lib/Debouncer.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module Debouncer
|
|
3
3
|
* This module contains the Debouncer class and debounce function that allow you to reduce the amount of calls in rapidly firing event listeners and such - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer)
|
|
4
4
|
*/
|
|
5
|
-
import { NanoEmitter } from "./NanoEmitter.
|
|
5
|
+
import { NanoEmitter } from "./NanoEmitter.ts";
|
|
6
6
|
/**
|
|
7
7
|
* The type of edge to use for the debouncer - [see the docs for a diagram and explanation.](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer)
|
|
8
8
|
* - `immediate` - (default & recommended) - calls the listeners at the very first call ("rising" edge) and queues the latest call until the timeout expires
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* This module contains the NanoEmitter class, which is a tiny event emitter powered by [nanoevents](https://www.npmjs.com/package/nanoevents) - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#nanoemitter)
|
|
4
4
|
*/
|
|
5
5
|
import { type DefaultEvents, type Emitter, type EventsMap, type Unsubscribe } from "nanoevents";
|
|
6
|
-
import type { Prettify } from "./types.
|
|
6
|
+
import type { Prettify } from "./types.ts";
|
|
7
7
|
export interface NanoEmitterOptions {
|
|
8
8
|
/** If set to true, allows emitting events through the public method emit() */
|
|
9
9
|
publicEmit: boolean;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { DataStore, type DataStoreData } from "./DataStore.
|
|
2
|
-
import type { SerializableVal } from "./types.
|
|
1
|
+
import { DataStore, type DataStoreData } from "./DataStore.ts";
|
|
2
|
+
import type { SerializableVal } from "./types.ts";
|
|
3
3
|
/**
|
|
4
4
|
* A DataStore wrapper subclass that exposes internal methods for testing via the `direct_` prefixed methods.
|
|
5
5
|
*/
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
* @module TieredCache
|
|
3
3
|
* This module contains the TieredCache class, which is a cache that can have multiple tiers with different max TTLs, with data being moved between tiers based on what is fetched the most.
|
|
4
4
|
*/
|
|
5
|
-
import { DataStore, type DataStoreData } from "./DataStore.
|
|
6
|
-
import { NanoEmitter, type NanoEmitterOptions } from "./NanoEmitter.
|
|
7
|
-
import type { DataStoreEngine } from "./DataStoreEngine.
|
|
8
|
-
import type { Prettify } from "./types.
|
|
5
|
+
import { DataStore, type DataStoreData } from "./DataStore.ts";
|
|
6
|
+
import { NanoEmitter, type NanoEmitterOptions } from "./NanoEmitter.ts";
|
|
7
|
+
import type { DataStoreEngine } from "./DataStoreEngine.ts";
|
|
8
|
+
import type { Prettify } from "./types.ts";
|
|
9
9
|
/** Options for the {@linkcode TieredCache} class. */
|
|
10
10
|
export type TieredCacheOptions<TData extends DataStoreData> = Prettify<{
|
|
11
11
|
/** Unique identifier for this cache. */
|
package/dist/lib/Translate.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module Translate
|
|
3
3
|
* This module contains a sophisticated but still lightweight, JSON-based translation system - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#class-translate)
|
|
4
4
|
*/
|
|
5
|
-
import type { Stringifiable } from "./types.
|
|
5
|
+
import type { Stringifiable } from "./types.ts";
|
|
6
6
|
/**
|
|
7
7
|
* Translation object to pass to {@linkcode tr.addTranslations()}
|
|
8
8
|
* Can be a flat object of identifier keys and the translation text as the value, or an infinitely nestable object containing the same.
|
package/dist/lib/crypto.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module crypto
|
|
3
3
|
* This module contains various cryptographic functions, like compression and Uint8Array encoding - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#crypto)
|
|
4
4
|
*/
|
|
5
|
-
import type { Stringifiable } from "./types.
|
|
5
|
+
import type { Stringifiable } from "./types.ts";
|
|
6
6
|
/** Converts an Uint8Array to a base64-encoded (ASCII) string */
|
|
7
7
|
export declare function abtoa(buf: Uint8Array): string;
|
|
8
8
|
/** Converts a base64-encoded (ASCII) string to an Uint8Array representation of its bytes */
|
package/dist/lib/index.d.ts
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
* @module @sv443-network/coreutils
|
|
3
3
|
* @description Cross-platform, general-purpose, JavaScript core library for Node, Deno and the browser. Intended to be used in conjunction with [`@sv443-network/userutils`](https://github.com/Sv443-Network/UserUtils) and [`@sv443-network/djsutils`](https://github.com/Sv443-Network/DJSUtils), but can be used independently as well.
|
|
4
4
|
*/
|
|
5
|
-
export * from "./array.
|
|
6
|
-
export * from "./colors.
|
|
7
|
-
export * from "./crypto.
|
|
8
|
-
export * from "./math.
|
|
9
|
-
export * from "./misc.
|
|
10
|
-
export * from "./text.
|
|
11
|
-
export * from "./types.
|
|
12
|
-
export * from "./DataStore.
|
|
13
|
-
export * from "./DataStoreEngine.
|
|
14
|
-
export * from "./DataStoreSerializer.
|
|
15
|
-
export * from "./Debouncer.
|
|
16
|
-
export * from "./Errors.
|
|
17
|
-
export * from "./NanoEmitter.
|
|
5
|
+
export * from "./array.ts";
|
|
6
|
+
export * from "./colors.ts";
|
|
7
|
+
export * from "./crypto.ts";
|
|
8
|
+
export * from "./math.ts";
|
|
9
|
+
export * from "./misc.ts";
|
|
10
|
+
export * from "./text.ts";
|
|
11
|
+
export * from "./types.ts";
|
|
12
|
+
export * from "./DataStore.ts";
|
|
13
|
+
export * from "./DataStoreEngine.ts";
|
|
14
|
+
export * from "./DataStoreSerializer.ts";
|
|
15
|
+
export * from "./Debouncer.ts";
|
|
16
|
+
export * from "./Errors.ts";
|
|
17
|
+
export * from "./NanoEmitter.ts";
|
package/dist/lib/math.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module math
|
|
3
3
|
* This module contains general-purpose math functions like clamping, mapping and random number generation - [see the documentation for more info](https://github.com/Sv443-Network/CoreUtils/blob/main/docs.md#math)
|
|
4
4
|
*/
|
|
5
|
-
import type { NumberFormat, Stringifiable } from "./types.
|
|
5
|
+
import type { NumberFormat, Stringifiable } from "./types.ts";
|
|
6
6
|
/** Checks if the given {@linkcode bitSet} contains the given {@linkcode checkVal} */
|
|
7
7
|
export declare function bitSetHas<TType extends number | bigint>(bitSet: TType, checkVal: TType): boolean;
|
|
8
8
|
/** Ensures the passed {@linkcode value} always stays between {@linkcode min} and {@linkcode max} */
|
package/dist/lib/misc.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @module misc
|
|
3
3
|
* This module contains miscellaneous functions that don't fit in another category - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#misc)
|
|
4
4
|
*/
|
|
5
|
-
import type { ListLike, Prettify, Stringifiable } from "./types.
|
|
5
|
+
import type { ListLike, Prettify, Stringifiable } from "./types.ts";
|
|
6
6
|
/**
|
|
7
7
|
* A ValueGen value is either its type, a promise that resolves to its type, or a function that returns its type, either synchronous or asynchronous.
|
|
8
8
|
* ValueGen allows for the utmost flexibility when applied to any type, as long as {@linkcode consumeGen()} is used to get the final value.
|
package/dist/lib/text.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ListLike, Prettify, Stringifiable } from "./types.
|
|
1
|
+
import type { ListLike, Prettify, Stringifiable } from "./types.ts";
|
|
2
2
|
/**
|
|
3
3
|
* Automatically pluralizes the given string an `-s` or `-ies` to the passed {@linkcode term}, if {@linkcode num} is not equal to 1.
|
|
4
4
|
* By default, words ending in `-y` will have it replaced with `-ies`, and all other words will simply have `-s` appended.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sv443-network/coreutils",
|
|
3
3
|
"libName": "@sv443-network/coreutils",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.3",
|
|
5
5
|
"description": "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.",
|
|
6
6
|
"main": "dist/CoreUtils.cjs",
|
|
7
7
|
"module": "dist/CoreUtils.mjs",
|
|
@@ -41,27 +41,27 @@
|
|
|
41
41
|
"nanoevents": "^9.1.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@changesets/cli": "^2.29.
|
|
45
|
-
"@eslint/eslintrc": "^3.3.
|
|
46
|
-
"@eslint/js": "^9.
|
|
47
|
-
"@swc/core": "^1.11
|
|
48
|
-
"@testing-library/dom": "^10.4.
|
|
49
|
-
"@types/deno": "^2.
|
|
50
|
-
"@types/node": "^22.
|
|
44
|
+
"@changesets/cli": "^2.29.8",
|
|
45
|
+
"@eslint/eslintrc": "^3.3.3",
|
|
46
|
+
"@eslint/js": "^9.39.2",
|
|
47
|
+
"@swc/core": "^1.15.11",
|
|
48
|
+
"@testing-library/dom": "^10.4.1",
|
|
49
|
+
"@types/deno": "^2.5.0",
|
|
50
|
+
"@types/node": "^22.19.7",
|
|
51
51
|
"@types/tx2": "^1.0.3",
|
|
52
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
53
|
-
"@typescript-eslint/parser": "^8.
|
|
54
|
-
"@typescript-eslint/utils": "^8.
|
|
55
|
-
"@vitest/coverage-v8": "^3.
|
|
52
|
+
"@typescript-eslint/eslint-plugin": "^8.54.0",
|
|
53
|
+
"@typescript-eslint/parser": "^8.54.0",
|
|
54
|
+
"@typescript-eslint/utils": "^8.54.0",
|
|
55
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
56
56
|
"esbuild-plugin-umd-wrapper": "^3.0.0",
|
|
57
|
-
"eslint": "^9.
|
|
58
|
-
"globals": "^16.
|
|
57
|
+
"eslint": "^9.39.2",
|
|
58
|
+
"globals": "^16.5.0",
|
|
59
59
|
"jsdom": "^26.1.0",
|
|
60
60
|
"tslib": "^2.8.1",
|
|
61
|
-
"tsup": "^8.5.
|
|
62
|
-
"tsx": "^4.
|
|
63
|
-
"typescript": "^5.
|
|
64
|
-
"vitest": "^3.
|
|
61
|
+
"tsup": "^8.5.1",
|
|
62
|
+
"tsx": "^4.21.0",
|
|
63
|
+
"typescript": "^5.9.3",
|
|
64
|
+
"vitest": "^3.2.4"
|
|
65
65
|
},
|
|
66
66
|
"files": [
|
|
67
67
|
"/dist/CoreUtils.cjs",
|