@sv443-network/coreutils 3.0.8 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/CoreUtils.cjs +34 -32
- package/dist/CoreUtils.min.cjs +3 -3
- package/dist/CoreUtils.min.mjs +3 -3
- package/dist/CoreUtils.min.umd.js +3 -3
- package/dist/CoreUtils.mjs +34 -32
- package/dist/CoreUtils.umd.js +606 -552
- package/dist/lib/DataStore.d.ts +6 -0
- package/dist/lib/DataStoreEngine.d.ts +1 -1
- package/package.json +5 -5
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
"use strict";var Y=Object.create;var N=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)N(r,t,{get:e[t],enumerable:!0})},
|
|
19
|
+
"use strict";var Y=Object.create;var N=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)N(r,t,{get:e[t],enumerable:!0})},L=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of te(e))!ie.call(r,n)&&n!==t&&N(r,n,{get:()=>e[n],enumerable:!(i=ee(e,n))||i.enumerable});return r};var k=(r,e,t)=>(t=r!=null?Y(re(r)):{},L(e||!r||!r.__esModule?N(t,"default",{value:r,enumerable:!0}):t,r)),ae=r=>L(N({},"__esModule",{value:!0}),r);var $e={};ne($e,{BrowserStorageEngine:()=>j,ChecksumMismatchError:()=>T,CustomError:()=>v,DataStore:()=>R,DataStoreEngine:()=>P,DataStoreSerializer:()=>K,DatedError:()=>p,Debouncer:()=>F,FileStorageEngine:()=>B,MigrationError:()=>w,NanoEmitter:()=>E,NetworkError:()=>x,ScriptContextError:()=>g,ValidationError:()=>U,abtoa:()=>W,atoab:()=>Q,autoPlural:()=>Ee,bitSetHas:()=>oe,capitalize:()=>Oe,clamp:()=>D,compress:()=>I,computeHash:()=>z,consumeGen:()=>ge,consumeStringGen:()=>ye,createProgressBar:()=>Ne,darkenColor:()=>q,debounce:()=>Me,decompress:()=>C,defaultPbChars:()=>G,digitCount:()=>se,fetchAdvanced:()=>be,formatNumber:()=>ue,getCallStack:()=>Pe,getListLength:()=>De,hexToRgb:()=>_,insertValues:()=>Ve,joinArrayReadable:()=>Fe,lightenColor:()=>fe,mapRange:()=>V,overflowVal:()=>ce,pauseFor:()=>Se,pureObj:()=>Te,randRange:()=>S,randomId:()=>he,randomItem:()=>de,randomItemIndex:()=>$,randomizeArray:()=>pe,rgbToHex:()=>H,roundFixed:()=>M,scheduleExit:()=>xe,secsToTimeStr:()=>Ae,setImmediateInterval:()=>ve,setImmediateTimeoutLoop:()=>we,takeRandomItem:()=>me,takeRandomItemIndex:()=>J,truncStr:()=>ke,valsWithin:()=>le});module.exports=ae($e);function oe(r,e){return(r&e)===e}function D(r,e,t){return typeof t!="number"&&(t=e,e=0),Math.max(Math.min(r,t),e)}function se(r,e=!0){if(r=Number(["string","number"].includes(typeof r)?r:String(r)),typeof r=="number"&&isNaN(r))return NaN;let[t,i]=r.toString().split("."),n=t==="0"?1:Math.floor(Math.log10(Math.abs(Number(t)))+1),o=e&&i?i.length:0;return n+o}function ue(r,e,t){return r.toLocaleString(e,t==="short"?{notation:"compact",compactDisplay:"short",maximumFractionDigits:1}:{style:"decimal",maximumFractionDigits:0})}function V(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 ce(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 S(...r){let e,t,i=!1;if(typeof r[0]=="number"&&typeof r[1]=="number")[e,t]=r;else if(typeof r[0]=="number"&&typeof r[1]!="number")e=0,[t]=r;else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map(n=>typeof n).join(", ")}) instead`);if(typeof r[2]=="boolean"?i=r[2]:typeof r[1]=="boolean"&&(i=r[1]),e=Number(e),t=Number(t),isNaN(e)||isNaN(t))return NaN;if(e>t)throw new TypeError(`Parameter "min" can't be bigger than "max"`);if(i){let n=new Uint8Array(1);return crypto.getRandomValues(n),Number(Array.from(n,o=>Math.round(V(o,0,255,e,t)).toString(10)).join(""))}else return Math.floor(Math.random()*(t-e+1))+e}function M(r,e){let t=10**e;return Math.round(r*t)/t}function le(r,e,t=1,i=.5){return Math.abs(M(r,t)-M(e,t))<=i}function de(r){return $(r)[0]}function $(r){if(r.length===0)return[void 0,void 0];let e=S(r.length-1);return[r[e],e]}function pe(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 me(r){var e;return(e=J(r))==null?void 0:e[0]}function J(r){let[e,t]=$(r);return t===void 0?[void 0,void 0]:(r.splice(t,1),[e,t])}function q(r,e,t=!1){var l;r=r.trim();let i=(c,d,m,y)=>(c=Math.max(0,Math.min(255,c-c*y/100)),d=Math.max(0,Math.min(255,d-d*y/100)),m=Math.max(0,Math.min(255,m-m*y/100)),[c,d,m]),n,o,a,s,u=r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);if(u)[n,o,a,s]=_(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,o,a,s]=c}else throw new TypeError("Unsupported color format");return[n,o,a]=i(n,o,a,e),u?H(n,o,a,s,r.startsWith("#"),t):r.startsWith("rgba")?`rgba(${n}, ${o}, ${a}, ${s??NaN})`:`rgb(${n}, ${o}, ${a})`}function _(r){r=(r.startsWith("#")?r.slice(1):r).trim();let e=r.length===8||r.length===4?parseInt(r.slice(-(r.length/4)),16)/(r.length===8?255:15):void 0;isNaN(Number(e))||(r=r.slice(0,-(r.length/4))),(r.length===3||r.length===4)&&(r=r.split("").map(a=>a+a).join(""));let t=parseInt(r,16),i=t>>16&255,n=t>>8&255,o=t&255;return[D(i,0,255),D(n,0,255),D(o,0,255),typeof e=="number"?D(e,0,1):void 0]}function fe(r,e,t=!1){return q(r,e*-1,t)}function H(r,e,t,i,n=!0,o=!1){let a=s=>D(Math.round(s),0,255).toString(16).padStart(2,"0")[o?"toUpperCase":"toLowerCase"]();return`${n?"#":""}${a(r)}${a(e)}${a(t)}${i?a(i*255):""}`}function W(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 I(r,e,t="string"){let i=r instanceof Uint8Array?r:new TextEncoder().encode((r==null?void 0:r.toString())??String(r)),n=new CompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:W(a)}async function C(r,e,t="string"){let i=r instanceof Uint8Array?r:Q((r==null?void 0:r.toString())??String(r)),n=new DecompressionStream(e),o=n.writable.getWriter();o.write(i),o.close();let a=new Uint8Array(await new Response(n.readable).arrayBuffer());return t==="arrayBuffer"?a:new TextDecoder().decode(a)}async function z(r,e="SHA-256"){let t;typeof r=="string"?t=new TextEncoder().encode(r):t=r;let i=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(i)).map(a=>a.toString(16).padStart(2,"0")).join("")}function he(r=16,e=16,t=!1,i=!0){if(r<1)throw new RangeError("The length argument must be at least 1");if(e<2||e>36)throw new RangeError("The radix argument must be between 2 and 36");let n=[],o=i?[0,1]:[0];if(t){let a=new Uint8Array(r);crypto.getRandomValues(a),n=Array.from(a,s=>V(s,0,255,0,e).toString(e).substring(0,1))}else n=Array.from({length:r},()=>Math.floor(Math.random()*e).toString(e));return n.some(a=>/[a-zA-Z]/.test(a))?n.map(a=>o[S(0,o.length-1,t)]===1?a.toUpperCase():a).join(""):n.join("")}var p=class extends Error{date;constructor(e,t){super(e,t),this.name=this.constructor.name,this.date=new Date}},T=class extends p{constructor(e,t){super(e,t),this.name="ChecksumMismatchError"}},v=class extends p{constructor(e,t,i){super(t,i),this.name=e}},w=class extends p{constructor(e,t){super(e,t),this.name="MigrationError"}},U=class extends p{constructor(e,t){super(e,t),this.name="ValidationError"}},g=class extends p{constructor(e,t){super(e,t),this.name="ScriptContextError"}},x=class extends p{constructor(e,t){super(e,t),this.name="NetworkError"}};async function ge(r){return await(typeof r=="function"?r():r)}async function ye(r){return typeof r=="string"?r:String(typeof r=="function"?await r():r)}async function be(r,e={}){let{timeout:t=1e4,signal:i,...n}=e,o=new AbortController;i==null||i.addEventListener("abort",()=>o.abort());let a={},s;t>=0&&(s=setTimeout(()=>o.abort(),t),a={signal:o.signal});try{let u=await fetch(r,{...n,...a});return typeof s<"u"&&clearTimeout(s),u}catch(u){throw typeof s<"u"&&clearTimeout(s),new x("Error while calling fetch",{cause:u})}}function De(r,e=!0){return"length"in r?r.length:"size"in r?r.size:"count"in r?r.count:e?0:NaN}function Se(r,e,t=!1){return new Promise((i,n)=>{let o=setTimeout(()=>i(),r);e==null||e.addEventListener("abort",()=>{clearTimeout(o),t?n(new v("AbortError","The pause was aborted")):i()})})}function Te(r){return Object.assign(Object.create(null),r??{})}function ve(r,e,t){let i,n=()=>clearInterval(i),o=()=>{if(t!=null&&t.aborted)return n();r()};t==null||t.addEventListener("abort",n),o(),i=setInterval(o,e)}function we(r,e,t){let i,n=()=>clearTimeout(i),o=async()=>{if(t!=null&&t.aborted)return n();await r(),i=setTimeout(o,e)};t==null||t.addEventListener("abort",n),o()}function xe(r=0,e=0){if(e<0)throw new TypeError("Timeout must be a non-negative number");let t;if(typeof process<"u"&&"exit"in process&&typeof process.exit=="function")t=()=>process.exit(r);else if(typeof Deno<"u"&&"exit"in Deno&&typeof Deno.exit=="function")t=()=>Deno.exit(r);else throw new g("Cannot exit the process, no exit method available");setTimeout(t,e)}function Pe(r,e=1/0){if(typeof e!="number"||isNaN(e)||e<0)throw new TypeError("lines parameter must be a non-negative number");try{throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)")}catch(t){let i=(t.stack??"").split(`
|
|
20
20
|
`).map(n=>n.trim()).slice(2,e+2);return r!==!1?i:i.join(`
|
|
21
|
-
`)}}function Pe(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 Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ne(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ve(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 Fe(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 Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function Me(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 Z=1,U=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await _(i,t,"string")],this.decodeData=[t,async i=>await k(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),m=[],b=(O,h,y)=>{m.push(this.engine.setValue(h,y)),m.push(this.engine.deleteValue(O))};b(`_uucfg-${this.id}`,`__ds-${this.id}-dat`,l),isNaN(c)||b(`_uucfgver-${this.id}`,`__ds-${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?b(`_uucfgenc-${this.id}`,`__ds-${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(m.push(this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)),m.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(m)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}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"&&typeof e!="object"||e===null||isNaN(t))return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`__ds-${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`__ds-${this.id}-ver`,t=this.formatVersion),a=!0);let s=typeof i=="string"?await this.engine.deserializeData(i,o):i;return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):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(){if(!this.memoryCache)throw new p("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(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.memoryCache&&(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,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}return await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,a),this.engine.setValue(`__ds-${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,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(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`__ds-${this.id}-ver`,o),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 E=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(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,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new p("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 p("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))}},R=class extends E{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)}},f,j=class extends E{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(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id);return await f.unlink(t)}catch(t){console.error("Error deleting file:",t)}}};var B=class r{stores;options;constructor(e,t={}){if(!crypto||!crypto.subtle)throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return $(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new p(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
21
|
+
`)}}function Ee(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 Oe(r){return r.charAt(0).toUpperCase()+r.slice(1)}var G={100:"\u2588",75:"\u2593",50:"\u2592",25:"\u2591",0:"\u2500"};function Ne(r,e,t=G){if(r===100)return t[100].repeat(e);let i=Math.floor(r/100*e),n=r/10*e-i,o="";n>=.75?o=t[75]:n>=.5?o=t[50]:n>=.25&&(o=t[25]);let a=t[100].repeat(i),s=t[0].repeat(e-i-(o?1:0));return`${a}${o}${s}`}function Ve(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 Fe(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 Ae(r){let e=r<0,t=Math.abs(r);if(isNaN(t)||!isFinite(t))throw new TypeError("The seconds argument must be a valid number");let i=Math.floor(t/3600),n=Math.floor(t%3600/60),o=Math.floor(t%60);return(e?"-":"")+[i?i+":":"",String(n).padStart(n>0||i>0?2:1,"0"),":",String(o).padStart(o>0||n>0||i>0||r===0?2:1,"0")].join("")}function ke(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 Z=1,R=class{id;formatVersion;defaultData;encodeData;decodeData;compressionFormat="deflate-raw";memoryCache;engine;keyPrefix;options;firstInit=!0;cachedData;migrations;migrateIds=[];constructor(e){if(this.id=e.id,this.formatVersion=e.formatVersion,this.defaultData=e.defaultData,this.memoryCache=e.memoryCache??!0,this.cachedData=this.memoryCache?e.defaultData:{},this.migrations=e.migrations,e.migrateIds&&(this.migrateIds=Array.isArray(e.migrateIds)?e.migrateIds:[e.migrateIds]),this.engine=typeof e.engine=="function"?e.engine():e.engine,this.keyPrefix=e.keyPrefix??"__ds-",this.options=e,"encodeData"in e&&"decodeData"in e&&Array.isArray(e.encodeData)&&Array.isArray(e.decodeData))this.encodeData=[e.encodeData[0],e.encodeData[1]],this.decodeData=[e.decodeData[0],e.decodeData[1]],this.compressionFormat=e.encodeData[0]??null;else if(e.compressionFormat===null)this.encodeData=void 0,this.decodeData=void 0,this.compressionFormat=null;else{let t=typeof e.compressionFormat=="string"?e.compressionFormat:"deflate-raw";this.compressionFormat=t,this.encodeData=[t,async i=>await I(i,t,"string")],this.decodeData=[t,async i=>await C(i,t,"string")]}this.engine.setDataStoreOptions({id:this.id,encodeData:this.encodeData,decodeData:this.decodeData})}async loadData(){try{if(this.firstInit){this.firstInit=!1;let u=Number(await this.engine.getValue("__ds_fmt_ver",0)),l=await this.engine.getValue(`_uucfg-${this.id}`,null);if(l){let c=Number(await this.engine.getValue(`_uucfgver-${this.id}`,NaN)),d=await this.engine.getValue(`_uucfgenc-${this.id}`,null),m=[],y=(O,h,b)=>{m.push(this.engine.setValue(h,b)),m.push(this.engine.deleteValue(O))};y(`_uucfg-${this.id}`,`${this.keyPrefix}${this.id}-dat`,l),isNaN(c)||y(`_uucfgver-${this.id}`,`${this.keyPrefix}${this.id}-ver`,c),typeof d=="boolean"||d==="true"||d==="false"||typeof d=="number"||d==="0"||d==="1"?y(`_uucfgenc-${this.id}`,`${this.keyPrefix}${this.id}-enf`,[0,"0",!0,"true"].includes(d)?this.compressionFormat??null:null):(m.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)),m.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))),await Promise.allSettled(m)}(isNaN(u)||u<Z)&&await this.engine.setValue("__ds_fmt_ver",Z)}this.migrateIds.length>0&&(await this.migrateId(this.migrateIds),this.migrateIds=[]);let e=await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`,null),t=Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`,NaN));if(typeof e!="string"&&typeof e!="object"||e===null||isNaN(t))return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData);let i=e??JSON.stringify(this.defaultData),n=String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`,null)),o=n!=="null"&&n!=="false"&&n!=="0"&&n!==""&&n!==null,a=!1;isNaN(t)&&(await this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,t=this.formatVersion),a=!0);let s=typeof i=="string"?await this.engine.deserializeData(i,o):i;return t<this.formatVersion&&this.migrations&&(s=await this.runMigrations(s,t)),a&&await this.setData(s),this.memoryCache?this.cachedData=this.engine.deepCopy(s):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(){if(!this.memoryCache)throw new p("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");return this.engine.deepCopy(this.cachedData)}setData(e){return this.memoryCache&&(this.cachedData=e),new Promise(async t=>{await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(e,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]),t()})}async saveDefaultData(){this.memoryCache&&(this.cachedData=this.defaultData),await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(this.defaultData,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,this.formatVersion),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)])}async deleteData(){var e,t;await Promise.allSettled([this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)]),await((t=(e=this.engine).deleteStorage)==null?void 0:t.call(e))}encodingEnabled(){return!!(this.encodeData&&this.decodeData)&&this.compressionFormat!==null||!!this.compressionFormat}async runMigrations(e,t,i=!0){if(!this.migrations)return e;let n=e,o=Object.entries(this.migrations).sort(([s],[u])=>Number(s)-Number(u)),a=t;for(let[s,u]of o){let l=Number(s);if(t<this.formatVersion&&t<l)try{let c=u(n);n=c instanceof Promise?await c:c,a=t=l}catch(c){if(!i)throw new w(`Error while running migration function for format version '${s}'`,{cause:c});return await this.saveDefaultData(),this.engine.deepCopy(this.defaultData)}}return await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(n,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,a),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat)]),this.memoryCache?this.cachedData=this.engine.deepCopy(n):this.engine.deepCopy(n)}async migrateId(e){let t=Array.isArray(e)?e:[e];await Promise.all(t.map(async i=>{let[n,o,a]=await(async()=>{let[u,l,c]=await Promise.all([this.engine.getValue(`${this.keyPrefix}${i}-dat`,JSON.stringify(this.defaultData)),this.engine.getValue(`${this.keyPrefix}${i}-ver`,NaN),this.engine.getValue(`${this.keyPrefix}${i}-enf`,null)]);return[u,Number(l),!!c&&String(c)!=="null"]})();if(n===void 0||isNaN(o))return;let s=await this.engine.deserializeData(n,a);await Promise.allSettled([this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,await this.engine.serializeData(s,this.encodingEnabled())),this.engine.setValue(`${this.keyPrefix}${this.id}-ver`,o),this.engine.setValue(`${this.keyPrefix}${this.id}-enf`,this.compressionFormat),this.engine.deleteValue(`${this.keyPrefix}${i}-dat`),this.engine.deleteValue(`${this.keyPrefix}${i}-ver`),this.engine.deleteValue(`${this.keyPrefix}${i}-enf`)])}))}};var P=class{dataStoreOptions;constructor(e){e&&(this.dataStoreOptions=e)}setDataStoreOptions(e){this.dataStoreOptions=e}async serializeData(e,t){var o,a,s,u,l;this.ensureDataStoreOptions();let i=JSON.stringify(e);if(!t||!((o=this.dataStoreOptions)!=null&&o.encodeData)||!((a=this.dataStoreOptions)!=null&&a.decodeData))return i;let n=(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,o,a;this.ensureDataStoreOptions();let i=(n=this.dataStoreOptions)!=null&&n.decodeData&&t?(a=(o=this.dataStoreOptions.decodeData)==null?void 0:o[1])==null?void 0:a.call(o,e):void 0;return i instanceof Promise&&(i=await i),JSON.parse(i??e)}ensureDataStoreOptions(){if(!this.dataStoreOptions)throw new p("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 p("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))}},j=class extends P{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)}},f,B=class extends P{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(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let o=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions),a=await f.readFile(o,"utf-8");return a?JSON.parse(await((n=(i=(t=this.dataStoreOptions)==null?void 0:t.decodeData)==null?void 0:i[1])==null?void 0:n.call(i,a))??a):void 0}catch{return}}async writeFile(e){var t,i,n,o;this.ensureDataStoreOptions();try{if(f||(f=(t=await import("fs/promises"))==null?void 0:t.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let a=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);await f.mkdir(a.slice(0,a.lastIndexOf(a.includes("/")?"/":"\\")),{recursive:!0}),await f.writeFile(a,await((o=(n=(i=this.dataStoreOptions)==null?void 0:i.encodeData)==null?void 0:n[1])==null?void 0:o.call(n,JSON.stringify(e)))??JSON.stringify(e,void 0,2),"utf-8")}catch(a){console.error("Error writing file:",a)}}async getValue(e,t){let i=await this.readFile();if(!i)return t;let n=i==null?void 0:i[e];if(typeof n>"u")return t;if(typeof t=="string")return typeof n=="object"&&n!==null?JSON.stringify(n):typeof n=="string"?n:String(n);if(typeof n=="string")try{return JSON.parse(n)}catch{return t}return n}async setValue(e,t){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let i=await this.readFile();i||(i={});let n=t;if(typeof t=="string")try{if(t.startsWith("{")||t.startsWith("[")){let o=JSON.parse(t);typeof o=="object"&&o!==null&&(n=o)}}catch{}i[e]=n,await this.writeFile(i)}).catch(i=>{throw console.error("Error in setValue:",i),i}),await this.fileAccessQueue.catch(()=>{})}async deleteValue(e){this.fileAccessQueue=this.fileAccessQueue.then(async()=>{let t=await this.readFile();t&&(delete t[e],await this.writeFile(t))}).catch(t=>{throw console.error("Error in deleteValue:",t),t}),await this.fileAccessQueue.catch(()=>{})}async deleteStorage(){var e;this.ensureDataStoreOptions();try{if(f||(f=(e=await import("fs/promises"))==null?void 0:e.default),!f)throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)",{cause:new p("'node:fs/promises' module not available")});let t=typeof this.options.filePath=="string"?this.options.filePath:this.options.filePath(this.dataStoreOptions.id,this.dataStoreOptions);return await f.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 g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");this.stores=e,this.options={addChecksum:!0,ensureIntegrity:!0,remapIds:{},...t}}async calcChecksum(e){return z(e,"SHA-256")}async serializePartial(e,t=!0,i=!0){var a;let n=[],o=this.stores.filter(s=>typeof e=="function"?e(s.id):e.includes(s.id));for(let s of o){let u=!!(t&&s.encodingEnabled()&&((a=s.encodeData)!=null&&a[1])),l=s.memoryCache?s.getData():await s.loadData(),c=u?await s.encodeData[1](JSON.stringify(l)):JSON.stringify(l);n.push({id:s.id,data:c,formatVersion:s.formatVersion,encoded:u,checksum:this.options.addChecksum?await this.calcChecksum(c):void 0})}return i?JSON.stringify(n):n}async serialize(e=!0,t=!0){return this.serializePartial(this.stores.map(i=>i.id),e,t)}async deserializePartial(e,t){let i=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i)||!i.every(r.isSerializedDataStoreObj))throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");let n=a=>{var s;return((s=Object.entries(this.options.remapIds).find(([,u])=>u.includes(a)))==null?void 0:s[0])??a},o=a=>typeof e=="function"?e(a):e.includes(a);for(let a of i){let s=n(a.id);if(!o(s))continue;let u=this.stores.find(c=>c.id===s);if(!u)throw new p(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);if(this.options.ensureIntegrity&&typeof a.checksum=="string"){let c=await this.calcChecksum(a.data);if(c!==a.checksum)throw new T(`Checksum mismatch for DataStore with ID "${a.id}"!
|
|
22
22
|
Expected: ${a.checksum}
|
|
23
|
-
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}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 X=()=>({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
|
|
23
|
+
Has: ${c}`)}let l=a.encoded&&u.encodingEnabled()?await u.decodeData[1](a.data):a.data;a.formatVersion&&!isNaN(Number(a.formatVersion))&&Number(a.formatVersion)<u.formatVersion?await u.runMigrations(JSON.parse(l),Number(a.formatVersion),!1):await u.setData(JSON.parse(l))}}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 X=()=>({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 E=class{events=X();eventUnsubscribes=[];emitterOptions;constructor(e={}){this.emitterOptions={publicEmit:!1,...e}}on(e,t){let i,n=()=>{i&&(i(),this.eventUnsubscribes=this.eventUnsubscribes.filter(o=>o!==i))};return i=this.events.on(e,t),this.eventUnsubscribes.push(i),n}once(e,t){return new Promise(i=>{let n,o=((...a)=>{t==null||t(...a),n==null||n(),i(a)});n=this.events.on(e,o),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 o={allOf:[],oneOf:[],once:!1,...n},{oneOf:a,allOf:s,once:u,signal:l,callback:c}=o;if(l!=null&&l.aborted)return i;if(a.length===0&&s.length===0)throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");let d=[],m=(h=!1)=>{if(!(!(l!=null&&l.aborted)&&!h)){for(let b of d)b();d.splice(0,d.length),this.eventUnsubscribes=this.eventUnsubscribes.filter(b=>!d.includes(b))}},y=new Set,O=()=>s.length===0||y.size===s.length;for(let h of a){let b=this.events.on(h,((...A)=>{m(),O()&&(c(h,...A),u&&m(!0))}));d.push(b)}for(let h of s){let b=this.events.on(h,((...A)=>{m(),y.add(h),O()&&(a.length===0||a.includes(h))&&(c(h,...A),u&&m(!0))}));d.push(b)}t.push(()=>m(!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 E{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=(...o)=>{this.queuedCall=void 0,this.emit("call",...o),this.listeners.forEach(a=>a.call(this,...o))},n=()=>{this.activeTimeout=setTimeout(()=>{this.queuedCall?(this.queuedCall(),n()):this.activeTimeout=void 0},this.timeout)};switch(this.type){case"immediate":typeof this.activeTimeout>"u"?(i(...t),n()):this.queuedCall=()=>i(...t);break;case"idle":this.activeTimeout&&clearTimeout(this.activeTimeout),this.activeTimeout=setTimeout(()=>{i(...t),this.activeTimeout=void 0},this.timeout);break;default:throw new TypeError(`Invalid debouncer type: ${this.type}`)}}};function Me(r,e=200,t="immediate"){let i=new F(e,t);i.addListener(r);let n=((...o)=>i.call(...o));return n.debouncer=i,n}
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
|
package/dist/CoreUtils.mjs
CHANGED
|
@@ -474,6 +474,7 @@ var DataStore = class {
|
|
|
474
474
|
compressionFormat = "deflate-raw";
|
|
475
475
|
memoryCache;
|
|
476
476
|
engine;
|
|
477
|
+
keyPrefix;
|
|
477
478
|
options;
|
|
478
479
|
/**
|
|
479
480
|
* Whether all first-init checks should be done.
|
|
@@ -505,6 +506,7 @@ var DataStore = class {
|
|
|
505
506
|
if (opts.migrateIds)
|
|
506
507
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
507
508
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
509
|
+
this.keyPrefix = opts.keyPrefix ?? "__ds-";
|
|
508
510
|
this.options = opts;
|
|
509
511
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
510
512
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
@@ -546,13 +548,13 @@ var DataStore = class {
|
|
|
546
548
|
promises.push(this.engine.setValue(newKey, value));
|
|
547
549
|
promises.push(this.engine.deleteValue(oldKey));
|
|
548
550
|
};
|
|
549
|
-
migrateFmt(`_uucfg-${this.id}`,
|
|
551
|
+
migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
|
|
550
552
|
if (!isNaN(oldVer))
|
|
551
|
-
migrateFmt(`_uucfgver-${this.id}`,
|
|
553
|
+
migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
|
|
552
554
|
if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
|
|
553
|
-
migrateFmt(`_uucfgenc-${this.id}`,
|
|
555
|
+
migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? this.compressionFormat ?? null : null);
|
|
554
556
|
else {
|
|
555
|
-
promises.push(this.engine.setValue(
|
|
557
|
+
promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
|
|
556
558
|
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
557
559
|
}
|
|
558
560
|
await Promise.allSettled(promises);
|
|
@@ -564,18 +566,18 @@ var DataStore = class {
|
|
|
564
566
|
await this.migrateId(this.migrateIds);
|
|
565
567
|
this.migrateIds = [];
|
|
566
568
|
}
|
|
567
|
-
const storedDataRaw = await this.engine.getValue(
|
|
568
|
-
let storedFmtVer = Number(await this.engine.getValue(
|
|
569
|
+
const storedDataRaw = await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
|
|
570
|
+
let storedFmtVer = Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
|
|
569
571
|
if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
570
572
|
await this.saveDefaultData();
|
|
571
573
|
return this.engine.deepCopy(this.defaultData);
|
|
572
574
|
}
|
|
573
575
|
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
574
|
-
const encodingFmt = String(await this.engine.getValue(
|
|
576
|
+
const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
575
577
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
576
578
|
let saveData = false;
|
|
577
579
|
if (isNaN(storedFmtVer)) {
|
|
578
|
-
await this.engine.setValue(
|
|
580
|
+
await this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, storedFmtVer = this.formatVersion);
|
|
579
581
|
saveData = true;
|
|
580
582
|
}
|
|
581
583
|
let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
@@ -611,9 +613,9 @@ var DataStore = class {
|
|
|
611
613
|
this.cachedData = data;
|
|
612
614
|
return new Promise(async (resolve) => {
|
|
613
615
|
await Promise.allSettled([
|
|
614
|
-
this.engine.setValue(
|
|
615
|
-
this.engine.setValue(
|
|
616
|
-
this.engine.setValue(
|
|
616
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
617
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
618
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
617
619
|
]);
|
|
618
620
|
resolve();
|
|
619
621
|
});
|
|
@@ -624,9 +626,9 @@ var DataStore = class {
|
|
|
624
626
|
if (this.memoryCache)
|
|
625
627
|
this.cachedData = this.defaultData;
|
|
626
628
|
await Promise.allSettled([
|
|
627
|
-
this.engine.setValue(
|
|
628
|
-
this.engine.setValue(
|
|
629
|
-
this.engine.setValue(
|
|
629
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
630
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
631
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
630
632
|
]);
|
|
631
633
|
}
|
|
632
634
|
//#region deleteData
|
|
@@ -638,9 +640,9 @@ var DataStore = class {
|
|
|
638
640
|
async deleteData() {
|
|
639
641
|
var _a, _b;
|
|
640
642
|
await Promise.allSettled([
|
|
641
|
-
this.engine.deleteValue(
|
|
642
|
-
this.engine.deleteValue(
|
|
643
|
-
this.engine.deleteValue(
|
|
643
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
|
|
644
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
|
|
645
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
|
|
644
646
|
]);
|
|
645
647
|
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
646
648
|
}
|
|
@@ -679,9 +681,9 @@ var DataStore = class {
|
|
|
679
681
|
}
|
|
680
682
|
}
|
|
681
683
|
await Promise.allSettled([
|
|
682
|
-
this.engine.setValue(
|
|
683
|
-
this.engine.setValue(
|
|
684
|
-
this.engine.setValue(
|
|
684
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(newData, this.encodingEnabled())),
|
|
685
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
|
|
686
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
685
687
|
]);
|
|
686
688
|
if (this.memoryCache)
|
|
687
689
|
return this.cachedData = this.engine.deepCopy(newData);
|
|
@@ -698,9 +700,9 @@ var DataStore = class {
|
|
|
698
700
|
await Promise.all(ids.map(async (id) => {
|
|
699
701
|
const [data, fmtVer, isEncoded] = await (async () => {
|
|
700
702
|
const [d, f, e] = await Promise.all([
|
|
701
|
-
this.engine.getValue(
|
|
702
|
-
this.engine.getValue(
|
|
703
|
-
this.engine.getValue(
|
|
703
|
+
this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
|
|
704
|
+
this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
|
|
705
|
+
this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
|
|
704
706
|
]);
|
|
705
707
|
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
706
708
|
})();
|
|
@@ -708,12 +710,12 @@ var DataStore = class {
|
|
|
708
710
|
return;
|
|
709
711
|
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
710
712
|
await Promise.allSettled([
|
|
711
|
-
this.engine.setValue(
|
|
712
|
-
this.engine.setValue(
|
|
713
|
-
this.engine.setValue(
|
|
714
|
-
this.engine.deleteValue(
|
|
715
|
-
this.engine.deleteValue(
|
|
716
|
-
this.engine.deleteValue(
|
|
713
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
714
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
715
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
716
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
717
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
718
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
717
719
|
]);
|
|
718
720
|
}));
|
|
719
721
|
}
|
|
@@ -837,7 +839,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
837
839
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
838
840
|
if (!fs)
|
|
839
841
|
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
840
|
-
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
842
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
841
843
|
const data = await fs.readFile(path, "utf-8");
|
|
842
844
|
return data ? JSON.parse(await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) ?? data) : void 0;
|
|
843
845
|
} catch {
|
|
@@ -853,7 +855,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
853
855
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
854
856
|
if (!fs)
|
|
855
857
|
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
856
|
-
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
858
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
857
859
|
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
858
860
|
await fs.writeFile(path, await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) ?? JSON.stringify(data, void 0, 2), "utf-8");
|
|
859
861
|
} catch (err) {
|
|
@@ -936,7 +938,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
936
938
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
937
939
|
if (!fs)
|
|
938
940
|
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
939
|
-
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
941
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
940
942
|
return await fs.unlink(path);
|
|
941
943
|
} catch (err) {
|
|
942
944
|
console.error("Error deleting file:", err);
|