tiny-essentials 1.1.0 → 1.1.1
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/README.md +1 -0
- package/dist/TinyEssentials.min.js +1 -1
- package/dist/v1/basics/objFilter.cjs +2 -2
- package/dist/v1/basics/objFilter.mjs +2 -2
- package/dist/v1/libs/TinyCrypto.cjs +49 -51
- package/dist/v1/libs/TinyCrypto.mjs +49 -49
- package/docs/libs/TinyCrypto.md +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
- ⏱️ **Time Calculations**: Easily calculate durations, format timers, and more.
|
|
22
22
|
- 🧠 **Object Utilities**: Perform type checks, count object properties, and calculate percentages.
|
|
23
23
|
- 🛠️ **Custom Utilities**: Includes various helper functions like `ruleOfThree` for proportion calculations and `getAge` to calculate the age based on a given birth date.
|
|
24
|
+
- 🔐 **Encryption Tools**: Use `TinyCrypto` to securely encrypt and decrypt values using AES-256-GCM, with full support for complex JavaScript data types like RegExp, Date, Buffer, and DOM elements (in browsers).
|
|
24
25
|
|
|
25
26
|
## 📦 Installation
|
|
26
27
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var TinyEssentials=function(e){"use strict";function t(e,t="seconds",n="{time}"){e=Math.max(0,Math.floor(e));const r=["seconds","minutes","hours","days","months","years"].indexOf(t),o=r>=5,i=r>=4,a=r>=3,s=r>=2,u=r>=1,l=r>=0,c={years:o?0:NaN,months:i?0:NaN,days:a?0:NaN,hours:s?0:NaN,minutes:u?0:NaN,seconds:l?0:NaN,total:NaN};let p=e;if(o||i||a){const e=new Date(1980,0,1),t=new Date(e.getTime()+1e3*p),n=new Date(e);if(o)for(;new Date(n.getFullYear()+1,n.getMonth(),n.getDate())<=t;)n.setFullYear(n.getFullYear()+1),c.years++;if(i)for(;new Date(n.getFullYear(),n.getMonth()+1,n.getDate())<=t;)n.setMonth(n.getMonth()+1),c.months++;if(a)for(;new Date(n.getFullYear(),n.getMonth(),n.getDate()+1)<=t;)n.setDate(n.getDate()+1),c.days++;p=Math.floor((t-n)/1e3)}s&&(c.hours=Math.floor(p/3600),p%=3600),u&&(c.minutes=Math.floor(p/60),p%=60),l&&(c.seconds=p);const g={seconds:l?e:NaN,minutes:u?e/60:NaN,hours:s?e/3600:NaN,days:a?e/86400:NaN,months:i?12*c.years+c.months+(c.days||0)/30:NaN,years:o?c.years+(c.months||0)/12+(c.days||0)/365:NaN};c.total=+(g[t]||0).toFixed(2).replace(/\.00$/,"");const f=e=>isNaN(e)?"NaN":String(e).padStart(2,"0"),h=[s?f(c.hours):null,u?f(c.minutes):null,l?f(c.seconds):null].filter((e=>null!==e)).join(":");return n.replace(/\{years\}/g,c.years).replace(/\{months\}/g,c.months).replace(/\{days\}/g,c.days).replace(/\{hours\}/g,f(c.hours)).replace(/\{minutes\}/g,f(c.minutes)).replace(/\{seconds\}/g,f(c.seconds)).replace(/\{time\}/g,h).replace(/\{total\}/g,c.total).trim()}const n={items:{undefined:e=>void 0===e,null:e=>null===e,boolean:e=>"boolean"==typeof e,number:e=>"number"==typeof e&&!isNaN(e),bigint:e=>"bigint"==typeof e,string:e=>"string"==typeof e,symbol:e=>"symbol"==typeof e,function:e=>"function"==typeof e,array:e=>Array.isArray(e),date:e=>e instanceof Date,regexp:e=>e instanceof RegExp,map:e=>e instanceof Map,set:e=>e instanceof Set,weakmap:e=>e instanceof WeakMap,weakset:e=>e instanceof WeakSet,promise:e=>e instanceof Promise,buffer:e=>"undefined"!=typeof Buffer&&Buffer.isBuffer(e),htmlElement:e=>"undefined"!=typeof HTMLElement&&e instanceof HTMLElement,object:e=>"object"==typeof e&&null!==e},order:["undefined","null","boolean","number","bigint","string","symbol","function","array","buffer","date","regexp","map","set","weakmap","weakset","promise","htmlElement","object"]};function r(e,t){if(void 0===e)return null;const r=(e=>{if(null===e)return"null";for(const t of n.order)if(!n.items[t]||n.items[t](e))return t;return"unknown"})(e);return"string"==typeof t?r===t.toLowerCase():r}var o={},i={};const a="undefined"!=typeof window&&void 0!==window.document;return e.TinyCrypto=class{constructor(e={}){this.algorithm=e.algorithm||"aes-256-gcm",this.outputEncoding=e.outputEncoding||"hex",this.inputEncoding=e.inputEncoding||"utf8",this.authTagLength=e.authTagLength||16,this.key=e.key||this.generateKey()}generateKey(e=32){return o.randomBytes(e)}generateIV(e=12){return o.randomBytes(e)}encrypt(e,t=this.generateIV()){const n=this.#e(e),r=o.createCipheriv(this.algorithm,this.key,t,{authTagLength:this.authTagLength});let i=r.update(n,this.inputEncoding);i=Buffer.concat([i,r.final()]);const a=r.getAuthTag();return{iv:t.toString(this.outputEncoding),encrypted:i.toString(this.outputEncoding),authTag:a.toString(this.outputEncoding)}}decrypt({iv:e,encrypted:t,authTag:n},r=null){const i=Buffer.from(e,this.outputEncoding),a=Buffer.from(t,this.outputEncoding),s=Buffer.from(n,this.outputEncoding),u=o.createDecipheriv(this.algorithm,this.key,i,{authTagLength:this.authTagLength});u.setAuthTag(s);let l=u.update(a,null,this.inputEncoding);l+=u.final(this.inputEncoding);const{value:c,type:p}=this.#t(l);return r&&this.#n(r,p),c}getTypeFromEncrypted({iv:e,encrypted:t,authTag:n}){const r=Buffer.from(e,this.outputEncoding),i=Buffer.from(t,this.outputEncoding),a=Buffer.from(n,this.outputEncoding),s=o.createDecipheriv(this.algorithm,this.key,r,{authTagLength:this.authTagLength});s.setAuthTag(a);let u=s.update(i,null,this.inputEncoding);u+=s.final(this.inputEncoding);const{type:l}=this.#t(u);return"string"==typeof l?l.toLowerCase():"unknown"}saveKeyToFile(e="secret.key"){const t=this.key.toString("hex");if(a){const n=new Blob([t],{type:"text/plain"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=e,o.click(),URL.revokeObjectURL(r)}else i.writeFileSync(e,t)}saveConfigToFile(e="crypto-config.json"){const t=JSON.stringify(this.exportConfig(),null,2);if(a){const n=new Blob([t],{type:"application/json"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=e,o.click(),URL.revokeObjectURL(r)}else i.writeFileSync(e,t)}async loadConfigFromFile(e){if(a)return new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>{try{const e=JSON.parse(r.result);t(this.importConfig(e))}catch(e){n(new Error("Invalid config JSON file"))}},r.onerror=()=>n(r.error),r.readAsText(e)}));{const t=i.readFileSync(e,"utf8"),n=JSON.parse(t);return this.importConfig(n)}}async loadKeyFromFile(e){if(a)return new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>{const e=r.result.trim(),n=Buffer.from(e,"hex");this.key=n,t(n)},r.onerror=()=>n(r.error),r.readAsText(e)}));{const t=i.readFileSync(e,"utf8"),n=Buffer.from(t,"hex");return this.key=n,n}}exportConfig(){return{algorithm:this.algorithm,outputEncoding:this.outputEncoding,inputEncoding:this.inputEncoding,key:this.key.toString("hex"),authTagLength:this.authTagLength}}importConfig(e){if("string"==typeof e.algorithm)this.algorithm=e.algorithm;else if(void 0!==e.algorithm)throw new Error('Invalid or missing "algorithm" property. Expected a string.');if("string"==typeof e.outputEncoding)this.outputEncoding=e.outputEncoding;else if(void 0!==e.outputEncoding)throw new Error('Invalid or missing "outputEncoding" property. Expected a string.');if("string"==typeof e.inputEncoding)this.inputEncoding=e.inputEncoding;else if(void 0!==e.inputEncoding)throw new Error('Invalid or missing "inputEncoding" property. Expected a string.');if("number"==typeof e.authTagLength)this.authTagLength=e.authTagLength;else if(void 0!==e.authTagLength)throw new Error('Invalid or missing "authTagLength" property. Expected a number.');if("string"==typeof e.key)this.key=Buffer.from(e.key,"hex");else if(void 0!==e.key)throw new Error('Invalid or missing "key" property. Expected a hexadecimal string.')}#r={weakmap:()=>{throw new Error("WeakMap cannot be serialized")},weakset:()=>{throw new Error("WeakSet cannot be serialized")},promise:()=>{throw new Error("Promise cannot be serialized")},function:()=>{throw new Error("Function cannot be serialized")},regexp:e=>JSON.stringify({__type:"RegExp",value:e.toString()}),htmlElement:e=>JSON.stringify({__type:"HTMLElement",value:e.outerHTML}),date:e=>JSON.stringify({__type:"Date",value:e.toISOString()}),bigint:e=>JSON.stringify({__type:"BigInt",value:e.toString()}),number:e=>JSON.stringify({__type:"Number",value:e}),boolean:e=>JSON.stringify({__type:"Boolean",value:e}),string:e=>JSON.stringify({__type:"String",value:e}),null:e=>JSON.stringify({__type:"Null"}),undefined:e=>JSON.stringify({__type:"Undefined"}),map:e=>JSON.stringify({__type:"Map",value:Array.from(e.entries())}),set:e=>JSON.stringify({__type:"Set",value:Array.from(e.values())}),symbol:e=>JSON.stringify({__type:"Symbol",value:e.description}),array:e=>JSON.stringify({__type:"Array",value:e}),object:e=>JSON.stringify({__type:"JSON",value:e}),buffer:e=>JSON.stringify({__type:"Buffer",value:e.toString("base64")})};#o={RegExp:e=>{const t=e.match(/^\/(.*)\/([gimsuy]*)$/);return t?new RegExp(t[1],t[2]):new RegExp(e)},HTMLElement:e=>{if("undefined"==typeof document)throw new Error("HTMLElement deserialization is only supported in browsers");const t=document.createElement("div");return t.innerHTML=e,t.firstElementChild},Date:e=>new Date(e),BigInt:e=>BigInt(e),Number:e=>Number(e),Boolean:e=>Boolean(e),Null:e=>null,Undefined:e=>{},Map:e=>new Map(e),Set:e=>new Set(e),Symbol:e=>Symbol(e),Array:e=>e,JSON:e=>e,String:e=>String(e),Buffer:e=>Buffer.from(e,"base64")};#e(e){const t=r(e)||"undefined";if(this.#r[t])return this.#r[t](e);throw new Error(`Unsupported data type for encryption: ${t}`)}#t(e){try{const t=JSON.parse(e),n=t.__type;return"string"!=typeof n?{value:e,type:"String"}:"function"==typeof this.#o[n]?{value:this.#o[n](t.value),type:n}:{value:e,type:"Unknown"}}catch{return{value:e,type:"Unknown"}}}#n(e,t){if(e.toLowerCase()!==t.toLowerCase())throw new Error(`Type mismatch: expected ${e.toLowerCase()}, but got ${t.toLowerCase()}`)}},e.TinyLevelUp=class{constructor(e,t){this.giveExp=e,this.expLevel=t}expValidator(e){let t=0;const n=this.expLevel*e.level;return e.exp>=n&&(e.level++,t=e.exp-n,e.exp=0,t>0)?this.give(e,t,"extra"):e.exp<1&&e.level>1&&(e.level--,t=Math.abs(e.exp),e.exp=this.expLevel*e.level,t>0)?this.remove(e,t,"extra"):e}getTotalExp(e){let t=0;for(let n=1;n<=e.level;n++)t+=this.expLevel*n;return t+=e.exp,t}expGenerator(e=1){return Math.floor(Math.random()*this.giveExp)+1*e}progress(e){return this.expLevel*e.level}getProgress(e){return this.expLevel*e.level}set(e,t){return e.exp=t,this.expValidator(e),e.totalExp=this.getTotalExp(e),e}give(e,t=0,n="add",r=1){return"add"===n?e.exp+=this.expGenerator(r)+t:"extra"===n&&(e.exp+=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}remove(e,t=0,n="add",r=1){return"add"===n?e.exp-=this.expGenerator(r)+t:"extra"===n&&(e.exp-=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}},e.asyncReplace=async function(e,t,n){const r=[];e.replace(t,((e,...t)=>(r.push(n(e,...t)),e)));const o=await Promise.all(r);return e.replace(t,(()=>o.shift()))},e.cloneObjTypeOrder=function(){return[...n.order]},e.countObj=function(e){return Array.isArray(e)?e.length:r(e,"object")?Object.keys(e).length:0},e.extendObjType=function(e,t){const r=[];for(const[o,i]of Object.entries(e))if(!n.items.hasOwnProperty(o)){n.items[o]=i;let e="number"==typeof t?t:-1;if(-1===e){const t=n.order.indexOf("object");e=t>-1?t:n.order.length}e=Math.min(Math.max(0,e),n.order.length),n.order.splice(e,0,o),r.push(o)}return r},e.formatCustomTimer=t,e.formatDayTimer=function(e){return t(e,"days","{days}d {hours}:{minutes}:{seconds}")},e.formatTimer=function(e){return t(e,"hours","{hours}:{minutes}:{seconds}")},e.getAge=function(e=0,t=null){if(null!=e&&0!==e){const n=new Date(e);if(isNaN(n))return null;const r=t instanceof Date?t:new Date;let o=r.getFullYear()-n.getFullYear();const i=r.getMonth(),a=n.getMonth(),s=r.getDate(),u=n.getDate();return(i<a||i===a&&s<u)&&o--,Math.abs(o)}return null},e.getSimplePerc=function(e,t){return e*(t/100)},e.getTimeDuration=function(e=new Date,t="asSeconds",n=null){if(e instanceof Date){const r=e-(n instanceof Date?n:new Date);switch(t){case"asMilliseconds":return r;case"asSeconds":default:return r/1e3;case"asMinutes":return r/6e4;case"asHours":return r/36e5;case"asDays":return r/864e5}}return null},e.objType=r,e.reorderObjTypeOrder=function(e){const t=[...n.order];return!!e.every((e=>t.includes(e)))&&(n.order=e.slice(),!0)},e.ruleOfThree=function(e,t,n,r){return r?Number(e*t)/n:Number(n*t)/e},e.shuffleArray=function(e){let t,n=e.length;for(;0!==n;)t=Math.floor(Math.random()*n),n--,[e[n],e[t]]=[e[t],e[n]];return e},e.toTitleCase=function(e){return e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()))},e.toTitleCaseLowerFirst=function(e){const t=e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));return t.charAt(0).toLowerCase()+t.slice(1)},e}({});
|
|
1
|
+
var TinyEssentials=function(e){"use strict";function t(e,t="seconds",n="{time}"){e=Math.max(0,Math.floor(e));const r=["seconds","minutes","hours","days","months","years"].indexOf(t),i=r>=5,o=r>=4,a=r>=3,s=r>=2,u=r>=1,l=r>=0,c={years:i?0:NaN,months:o?0:NaN,days:a?0:NaN,hours:s?0:NaN,minutes:u?0:NaN,seconds:l?0:NaN,total:NaN};let p=e;if(i||o||a){const e=new Date(1980,0,1),t=new Date(e.getTime()+1e3*p),n=new Date(e);if(i)for(;new Date(n.getFullYear()+1,n.getMonth(),n.getDate())<=t;)n.setFullYear(n.getFullYear()+1),c.years++;if(o)for(;new Date(n.getFullYear(),n.getMonth()+1,n.getDate())<=t;)n.setMonth(n.getMonth()+1),c.months++;if(a)for(;new Date(n.getFullYear(),n.getMonth(),n.getDate()+1)<=t;)n.setDate(n.getDate()+1),c.days++;p=Math.floor((t-n)/1e3)}s&&(c.hours=Math.floor(p/3600),p%=3600),u&&(c.minutes=Math.floor(p/60),p%=60),l&&(c.seconds=p);const g={seconds:l?e:NaN,minutes:u?e/60:NaN,hours:s?e/3600:NaN,days:a?e/86400:NaN,months:o?12*c.years+c.months+(c.days||0)/30:NaN,years:i?c.years+(c.months||0)/12+(c.days||0)/365:NaN};c.total=+(g[t]||0).toFixed(2).replace(/\.00$/,"");const h=e=>isNaN(e)?"NaN":String(e).padStart(2,"0"),f=[s?h(c.hours):null,u?h(c.minutes):null,l?h(c.seconds):null].filter((e=>null!==e)).join(":");return n.replace(/\{years\}/g,c.years).replace(/\{months\}/g,c.months).replace(/\{days\}/g,c.days).replace(/\{hours\}/g,h(c.hours)).replace(/\{minutes\}/g,h(c.minutes)).replace(/\{seconds\}/g,h(c.seconds)).replace(/\{time\}/g,f).replace(/\{total\}/g,c.total).trim()}const n={items:{undefined:e=>void 0===e,null:e=>null===e,boolean:e=>"boolean"==typeof e,number:e=>"number"==typeof e&&!isNaN(e),bigint:e=>"bigint"==typeof e,string:e=>"string"==typeof e,symbol:e=>"symbol"==typeof e,function:e=>"function"==typeof e,array:e=>Array.isArray(e),date:e=>e instanceof Date,regexp:e=>e instanceof RegExp,map:e=>e instanceof Map,set:e=>e instanceof Set,weakmap:e=>e instanceof WeakMap,weakset:e=>e instanceof WeakSet,promise:e=>e instanceof Promise,buffer:e=>"undefined"!=typeof Buffer&&Buffer.isBuffer(e),htmlelement:e=>"undefined"!=typeof HTMLElement&&e instanceof HTMLElement,object:e=>"object"==typeof e&&null!==e},order:["undefined","null","boolean","number","bigint","string","symbol","function","array","buffer","date","regexp","map","set","weakmap","weakset","promise","htmlelement","object"]};function r(e,t){if(void 0===e)return null;const r=(e=>{if(null===e)return"null";for(const t of n.order)if(!n.items[t]||n.items[t](e))return t;return"unknown"})(e);return"string"==typeof t?r===t.toLowerCase():r}var i={},o={};const a="undefined"!=typeof window&&void 0!==window.document;return e.TinyCrypto=class{constructor(e={}){this.algorithm=e.algorithm||"aes-256-gcm",this.outputEncoding=e.outputEncoding||"hex",this.inputEncoding=e.inputEncoding||"utf8",this.authTagLength=e.authTagLength||16,this.key=e.key||this.generateKey()}generateKey(e=32){return i.randomBytes(e)}generateIV(e=12){return i.randomBytes(e)}encrypt(e,t=this.generateIV()){const n=this.#e(e),r=i.createCipheriv(this.algorithm,this.key,t,{authTagLength:this.authTagLength});let o=r.update(n,this.inputEncoding);o=Buffer.concat([o,r.final()]);const a=r.getAuthTag();return{iv:t.toString(this.outputEncoding),encrypted:o.toString(this.outputEncoding),authTag:a.toString(this.outputEncoding)}}decrypt({iv:e,encrypted:t,authTag:n},r=null){const o=Buffer.from(e,this.outputEncoding),a=Buffer.from(t,this.outputEncoding),s=Buffer.from(n,this.outputEncoding),u=i.createDecipheriv(this.algorithm,this.key,o,{authTagLength:this.authTagLength});u.setAuthTag(s);let l=u.update(a,null,this.inputEncoding);l+=u.final(this.inputEncoding);const{value:c,type:p}=this.#t(l);return r&&this.#n(r,p),c}getTypeFromEncrypted({iv:e,encrypted:t,authTag:n}){const r=Buffer.from(e,this.outputEncoding),o=Buffer.from(t,this.outputEncoding),a=Buffer.from(n,this.outputEncoding),s=i.createDecipheriv(this.algorithm,this.key,r,{authTagLength:this.authTagLength});s.setAuthTag(a);let u=s.update(o,null,this.inputEncoding);u+=s.final(this.inputEncoding);const{type:l}=this.#t(u);return"string"==typeof l?l:"unknown"}saveKeyToFile(e="secret.key"){const t=this.key.toString("hex");if(a){const n=new Blob([t],{type:"text/plain"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=e,i.click(),URL.revokeObjectURL(r)}else o.writeFileSync(e,t)}saveConfigToFile(e="crypto-config.json"){const t=JSON.stringify(this.exportConfig(),null,2);if(a){const n=new Blob([t],{type:"application/json"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=e,i.click(),URL.revokeObjectURL(r)}else o.writeFileSync(e,t)}async loadConfigFromFile(e){if(a)return new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>{try{const e=JSON.parse(r.result);t(this.importConfig(e))}catch(e){n(new Error("Invalid config JSON file"))}},r.onerror=()=>n(r.error),r.readAsText(e)}));{const t=o.readFileSync(e,"utf8"),n=JSON.parse(t);return this.importConfig(n)}}async loadKeyFromFile(e){if(a)return new Promise(((t,n)=>{const r=new FileReader;r.onload=()=>{const e=r.result.trim(),n=Buffer.from(e,"hex");this.key=n,t(n)},r.onerror=()=>n(r.error),r.readAsText(e)}));{const t=o.readFileSync(e,"utf8"),n=Buffer.from(t,"hex");return this.key=n,n}}exportConfig(){return{algorithm:this.algorithm,outputEncoding:this.outputEncoding,inputEncoding:this.inputEncoding,key:this.key.toString("hex"),authTagLength:this.authTagLength}}importConfig(e){if("string"==typeof e.algorithm)this.algorithm=e.algorithm;else if(void 0!==e.algorithm)throw new Error('Invalid or missing "algorithm" property. Expected a string.');if("string"==typeof e.outputEncoding)this.outputEncoding=e.outputEncoding;else if(void 0!==e.outputEncoding)throw new Error('Invalid or missing "outputEncoding" property. Expected a string.');if("string"==typeof e.inputEncoding)this.inputEncoding=e.inputEncoding;else if(void 0!==e.inputEncoding)throw new Error('Invalid or missing "inputEncoding" property. Expected a string.');if("number"==typeof e.authTagLength)this.authTagLength=e.authTagLength;else if(void 0!==e.authTagLength)throw new Error('Invalid or missing "authTagLength" property. Expected a number.');if("string"==typeof e.key)this.key=Buffer.from(e.key,"hex");else if(void 0!==e.key)throw new Error('Invalid or missing "key" property. Expected a hexadecimal string.')}#r={weakmap:()=>{throw new Error("WeakMap cannot be serialized")},weakset:()=>{throw new Error("WeakSet cannot be serialized")},promise:()=>{throw new Error("Promise cannot be serialized")},function:()=>{throw new Error("Function cannot be serialized")},regexp:e=>JSON.stringify({__type:"regexp",value:e.toString()}),htmlElement:e=>JSON.stringify({__type:"htmlelement",value:e.outerHTML}),date:e=>JSON.stringify({__type:"date",value:e.toISOString()}),bigint:e=>JSON.stringify({__type:"bigint",value:e.toString()}),number:e=>JSON.stringify({__type:"number",value:e}),boolean:e=>JSON.stringify({__type:"boolean",value:e}),string:e=>JSON.stringify({__type:"string",value:e}),null:e=>JSON.stringify({__type:"null"}),undefined:e=>JSON.stringify({__type:"undefined"}),map:e=>JSON.stringify({__type:"map",value:Array.from(e.entries())}),set:e=>JSON.stringify({__type:"set",value:Array.from(e.values())}),symbol:e=>JSON.stringify({__type:"symbol",value:e.description}),array:e=>JSON.stringify({__type:"array",value:e}),object:e=>JSON.stringify({__type:"object",value:e}),buffer:e=>JSON.stringify({__type:"buffer",value:e.toString("base64")})};#i={regexp:e=>{const t=e.match(/^\/(.*)\/([gimsuy]*)$/);return t?new RegExp(t[1],t[2]):new RegExp(e)},htmlelement:e=>{if("undefined"==typeof document)throw new Error("HTMLElement deserialization is only supported in browsers");const t=document.createElement("div");return t.innerHTML=e,t.firstElementChild},date:e=>new Date(e),bigint:e=>BigInt(e),number:e=>Number(e),boolean:e=>Boolean(e),null:e=>null,undefined:e=>{},map:e=>new Map(e),set:e=>new Set(e),symbol:e=>Symbol(e),array:e=>e,object:e=>e,string:e=>String(e),buffer:e=>Buffer.from(e,"base64")};#e(e){const t=r(e)||"undefined";if(this.#r[t])return this.#r[t](e);throw new Error(`Unsupported data type for encryption: ${t}`)}#t(e){try{const t=JSON.parse(e),n=t.__type;return"string"!=typeof n?{value:e,type:"string"}:"function"==typeof this.#i[n]?{value:this.#i[n](t.value),type:n}:{value:e,type:"Unknown"}}catch{return{value:e,type:"Unknown"}}}#n(e,t){if(e!==t)throw new Error(`Type mismatch: expected ${e}, but got ${t}`)}},e.TinyLevelUp=class{constructor(e,t){this.giveExp=e,this.expLevel=t}expValidator(e){let t=0;const n=this.expLevel*e.level;return e.exp>=n&&(e.level++,t=e.exp-n,e.exp=0,t>0)?this.give(e,t,"extra"):e.exp<1&&e.level>1&&(e.level--,t=Math.abs(e.exp),e.exp=this.expLevel*e.level,t>0)?this.remove(e,t,"extra"):e}getTotalExp(e){let t=0;for(let n=1;n<=e.level;n++)t+=this.expLevel*n;return t+=e.exp,t}expGenerator(e=1){return Math.floor(Math.random()*this.giveExp)+1*e}progress(e){return this.expLevel*e.level}getProgress(e){return this.expLevel*e.level}set(e,t){return e.exp=t,this.expValidator(e),e.totalExp=this.getTotalExp(e),e}give(e,t=0,n="add",r=1){return"add"===n?e.exp+=this.expGenerator(r)+t:"extra"===n&&(e.exp+=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}remove(e,t=0,n="add",r=1){return"add"===n?e.exp-=this.expGenerator(r)+t:"extra"===n&&(e.exp-=t),this.expValidator(e),e.totalExp=this.getTotalExp(e),e}},e.asyncReplace=async function(e,t,n){const r=[];e.replace(t,((e,...t)=>(r.push(n(e,...t)),e)));const i=await Promise.all(r);return e.replace(t,(()=>i.shift()))},e.cloneObjTypeOrder=function(){return[...n.order]},e.countObj=function(e){return Array.isArray(e)?e.length:r(e,"object")?Object.keys(e).length:0},e.extendObjType=function(e,t){const r=[];for(const[i,o]of Object.entries(e))if(!n.items.hasOwnProperty(i)){n.items[i]=o;let e="number"==typeof t?t:-1;if(-1===e){const t=n.order.indexOf("object");e=t>-1?t:n.order.length}e=Math.min(Math.max(0,e),n.order.length),n.order.splice(e,0,i),r.push(i)}return r},e.formatCustomTimer=t,e.formatDayTimer=function(e){return t(e,"days","{days}d {hours}:{minutes}:{seconds}")},e.formatTimer=function(e){return t(e,"hours","{hours}:{minutes}:{seconds}")},e.getAge=function(e=0,t=null){if(null!=e&&0!==e){const n=new Date(e);if(isNaN(n))return null;const r=t instanceof Date?t:new Date;let i=r.getFullYear()-n.getFullYear();const o=r.getMonth(),a=n.getMonth(),s=r.getDate(),u=n.getDate();return(o<a||o===a&&s<u)&&i--,Math.abs(i)}return null},e.getSimplePerc=function(e,t){return e*(t/100)},e.getTimeDuration=function(e=new Date,t="asSeconds",n=null){if(e instanceof Date){const r=e-(n instanceof Date?n:new Date);switch(t){case"asMilliseconds":return r;case"asSeconds":default:return r/1e3;case"asMinutes":return r/6e4;case"asHours":return r/36e5;case"asDays":return r/864e5}}return null},e.objType=r,e.reorderObjTypeOrder=function(e){const t=[...n.order];return!!e.every((e=>t.includes(e)))&&(n.order=e.slice(),!0)},e.ruleOfThree=function(e,t,n,r){return r?Number(e*t)/n:Number(n*t)/e},e.shuffleArray=function(e){let t,n=e.length;for(;0!==n;)t=Math.floor(Math.random()*n),n--,[e[n],e[t]]=[e[t],e[n]];return e},e.toTitleCase=function(e){return e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()))},e.toTitleCaseLowerFirst=function(e){const t=e.replace(/\w\S*/g,(e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()));return t.charAt(0).toLowerCase()+t.slice(1)},e}({});
|
|
@@ -73,7 +73,7 @@ const typeValidator = {
|
|
|
73
73
|
buffer: (val) => typeof Buffer !== 'undefined' && Buffer.isBuffer(val),
|
|
74
74
|
|
|
75
75
|
/** Checks if the value is a Html Element. */
|
|
76
|
-
|
|
76
|
+
htmlelement: (val) => typeof HTMLElement !== 'undefined' && val instanceof HTMLElement,
|
|
77
77
|
|
|
78
78
|
/** Checks if the value is a non-null plain object or instance of a class. */
|
|
79
79
|
object: (val) => typeof val === 'object' && val !== null,
|
|
@@ -98,7 +98,7 @@ const typeValidator = {
|
|
|
98
98
|
'weakmap',
|
|
99
99
|
'weakset',
|
|
100
100
|
'promise',
|
|
101
|
-
'
|
|
101
|
+
'htmlelement',
|
|
102
102
|
'object',
|
|
103
103
|
],
|
|
104
104
|
};
|
|
@@ -53,7 +53,7 @@ const typeValidator = {
|
|
|
53
53
|
/** Checks if the value is a Buffer. */
|
|
54
54
|
buffer: (val) => typeof Buffer !== 'undefined' && Buffer.isBuffer(val),
|
|
55
55
|
/** Checks if the value is a Html Element. */
|
|
56
|
-
|
|
56
|
+
htmlelement: (val) => typeof HTMLElement !== 'undefined' && val instanceof HTMLElement,
|
|
57
57
|
/** Checks if the value is a non-null plain object or instance of a class. */
|
|
58
58
|
object: (val) => typeof val === 'object' && val !== null,
|
|
59
59
|
},
|
|
@@ -76,7 +76,7 @@ const typeValidator = {
|
|
|
76
76
|
'weakmap',
|
|
77
77
|
'weakset',
|
|
78
78
|
'promise',
|
|
79
|
-
'
|
|
79
|
+
'htmlelement',
|
|
80
80
|
'object',
|
|
81
81
|
],
|
|
82
82
|
};
|
|
@@ -188,7 +188,7 @@ class TinyCrypto {
|
|
|
188
188
|
decrypted += decipher.final(this.inputEncoding);
|
|
189
189
|
|
|
190
190
|
const { type } = this.#deserialize(decrypted);
|
|
191
|
-
return typeof type === 'string' ? type
|
|
191
|
+
return typeof type === 'string' ? type : 'unknown';
|
|
192
192
|
}
|
|
193
193
|
|
|
194
194
|
/**
|
|
@@ -458,29 +458,29 @@ class TinyCrypto {
|
|
|
458
458
|
function: () => {
|
|
459
459
|
throw new Error('Function cannot be serialized');
|
|
460
460
|
},
|
|
461
|
-
regexp: (data) => JSON.stringify({ __type: '
|
|
462
|
-
htmlElement: (data) => JSON.stringify({ __type: '
|
|
463
|
-
date: (data) => JSON.stringify({ __type: '
|
|
464
|
-
bigint: (data) => JSON.stringify({ __type: '
|
|
465
|
-
number: (data) => JSON.stringify({ __type: '
|
|
466
|
-
boolean: (data) => JSON.stringify({ __type: '
|
|
467
|
-
string: (data) => JSON.stringify({ __type: '
|
|
468
|
-
null: (data) => JSON.stringify({ __type: '
|
|
469
|
-
undefined: (data) => JSON.stringify({ __type: '
|
|
461
|
+
regexp: (data) => JSON.stringify({ __type: 'regexp', value: data.toString() }),
|
|
462
|
+
htmlElement: (data) => JSON.stringify({ __type: 'htmlelement', value: data.outerHTML }),
|
|
463
|
+
date: (data) => JSON.stringify({ __type: 'date', value: data.toISOString() }),
|
|
464
|
+
bigint: (data) => JSON.stringify({ __type: 'bigint', value: data.toString() }),
|
|
465
|
+
number: (data) => JSON.stringify({ __type: 'number', value: data }),
|
|
466
|
+
boolean: (data) => JSON.stringify({ __type: 'boolean', value: data }),
|
|
467
|
+
string: (data) => JSON.stringify({ __type: 'string', value: data }),
|
|
468
|
+
null: (data) => JSON.stringify({ __type: 'null' }),
|
|
469
|
+
undefined: (data) => JSON.stringify({ __type: 'undefined' }),
|
|
470
470
|
map: (data) =>
|
|
471
471
|
JSON.stringify({
|
|
472
|
-
__type: '
|
|
472
|
+
__type: 'map',
|
|
473
473
|
value: Array.from(data.entries()),
|
|
474
474
|
}),
|
|
475
475
|
set: (data) =>
|
|
476
476
|
JSON.stringify({
|
|
477
|
-
__type: '
|
|
477
|
+
__type: 'set',
|
|
478
478
|
value: Array.from(data.values()),
|
|
479
479
|
}),
|
|
480
|
-
symbol: (data) => JSON.stringify({ __type: '
|
|
481
|
-
array: (data) => JSON.stringify({ __type: '
|
|
482
|
-
object: (data) => JSON.stringify({ __type: '
|
|
483
|
-
buffer: (data) => JSON.stringify({ __type: '
|
|
480
|
+
symbol: (data) => JSON.stringify({ __type: 'symbol', value: data.description }),
|
|
481
|
+
array: (data) => JSON.stringify({ __type: 'array', value: data }),
|
|
482
|
+
object: (data) => JSON.stringify({ __type: 'object', value: data }),
|
|
483
|
+
buffer: (data) => JSON.stringify({ __type: 'buffer', value: data.toString('base64') }),
|
|
484
484
|
};
|
|
485
485
|
|
|
486
486
|
/**
|
|
@@ -492,47 +492,47 @@ class TinyCrypto {
|
|
|
492
492
|
* and the value is a function that deserializes the value to its original format.
|
|
493
493
|
*
|
|
494
494
|
* @type {Object}
|
|
495
|
-
* @property {Function}
|
|
496
|
-
* @property {Function}
|
|
497
|
-
* @property {Function}
|
|
498
|
-
* @property {Function}
|
|
499
|
-
* @property {Function}
|
|
500
|
-
* @property {Function}
|
|
501
|
-
* @property {Function}
|
|
502
|
-
* @property {Function}
|
|
503
|
-
* @property {Function}
|
|
504
|
-
* @property {Function}
|
|
505
|
-
* @property {Function}
|
|
506
|
-
* @property {Function}
|
|
507
|
-
* @property {Function}
|
|
508
|
-
* @property {Function}
|
|
509
|
-
* @property {Function}
|
|
495
|
+
* @property {Function} regexp - Deserializes a regular expression from its string representation (e.g., `/pattern/flags`).
|
|
496
|
+
* @property {Function} htmlelement - Deserializes an HTML element from its serialized outerHTML string (only works in browser environments).
|
|
497
|
+
* @property {Function} date - Deserializes a date from its ISO string representation.
|
|
498
|
+
* @property {Function} bigint - Deserializes a BigInt from its string representation.
|
|
499
|
+
* @property {Function} number - Deserializes a number from its string or numeric representation.
|
|
500
|
+
* @property {Function} boolean - Deserializes a boolean value from its string representation.
|
|
501
|
+
* @property {Function} null - Deserializes the `null` value.
|
|
502
|
+
* @property {Function} undefined - Deserializes the `undefined` value.
|
|
503
|
+
* @property {Function} map - Deserializes a Map from an array of key-value pairs.
|
|
504
|
+
* @property {Function} set - Deserializes a Set from an array of values.
|
|
505
|
+
* @property {Function} symbol - Deserializes a Symbol from its string description.
|
|
506
|
+
* @property {Function} array - Deserializes an array from its serialized representation.
|
|
507
|
+
* @property {Function} object - Deserializes a plain JSON object from its serialized representation.
|
|
508
|
+
* @property {Function} string - Deserializes a string from its serialized representation.
|
|
509
|
+
* @property {Function} buffer - Deserializes a Buffer from its base64-encoded string representation.
|
|
510
510
|
*/
|
|
511
511
|
#valueTypes = {
|
|
512
|
-
|
|
512
|
+
regexp: (value) => {
|
|
513
513
|
const match = value.match(/^\/(.*)\/([gimsuy]*)$/);
|
|
514
514
|
return match ? new RegExp(match[1], match[2]) : new RegExp(value);
|
|
515
515
|
},
|
|
516
|
-
|
|
516
|
+
htmlelement: (value) => {
|
|
517
517
|
if (typeof document === 'undefined')
|
|
518
518
|
throw new Error('HTMLElement deserialization is only supported in browsers');
|
|
519
519
|
const div = document.createElement('div');
|
|
520
520
|
div.innerHTML = value;
|
|
521
521
|
return div.firstElementChild;
|
|
522
522
|
},
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
523
|
+
date: (value) => new Date(value),
|
|
524
|
+
bigint: (value) => BigInt(value),
|
|
525
|
+
number: (value) => Number(value),
|
|
526
|
+
boolean: (value) => Boolean(value),
|
|
527
|
+
null: (value) => null,
|
|
528
|
+
undefined: (value) => undefined,
|
|
529
|
+
map: (value) => new Map(value),
|
|
530
|
+
set: (value) => new Set(value),
|
|
531
|
+
symbol: (value) => Symbol(value),
|
|
532
|
+
array: (value) => value,
|
|
533
|
+
object: (value) => value,
|
|
534
|
+
string: (value) => String(value),
|
|
535
|
+
buffer: (value) => Buffer.from(value, 'base64'),
|
|
536
536
|
};
|
|
537
537
|
|
|
538
538
|
/**
|
|
@@ -564,7 +564,7 @@ class TinyCrypto {
|
|
|
564
564
|
const parsed = JSON.parse(text);
|
|
565
565
|
const type = parsed.__type;
|
|
566
566
|
|
|
567
|
-
if (typeof type !== 'string') return { value: text, type: '
|
|
567
|
+
if (typeof type !== 'string') return { value: text, type: 'string' };
|
|
568
568
|
if (typeof this.#valueTypes[type] === 'function')
|
|
569
569
|
return {
|
|
570
570
|
value: this.#valueTypes[type](parsed.value),
|
|
@@ -586,10 +586,8 @@ class TinyCrypto {
|
|
|
586
586
|
* @throws {Error} If the types do not match.
|
|
587
587
|
*/
|
|
588
588
|
#validateDeserializedType(expected, actual) {
|
|
589
|
-
if (expected
|
|
590
|
-
throw new Error(
|
|
591
|
-
`Type mismatch: expected ${expected.toLowerCase()}, but got ${actual.toLowerCase()}`,
|
|
592
|
-
);
|
|
589
|
+
if (expected !== actual)
|
|
590
|
+
throw new Error(`Type mismatch: expected ${expected}, but got ${actual}`);
|
|
593
591
|
}
|
|
594
592
|
}
|
|
595
593
|
|
|
@@ -169,7 +169,7 @@ class TinyCrypto {
|
|
|
169
169
|
let decrypted = decipher.update(encryptedBuffer, null, this.inputEncoding);
|
|
170
170
|
decrypted += decipher.final(this.inputEncoding);
|
|
171
171
|
const { type } = this.#deserialize(decrypted);
|
|
172
|
-
return typeof type === 'string' ? type
|
|
172
|
+
return typeof type === 'string' ? type : 'unknown';
|
|
173
173
|
}
|
|
174
174
|
/**
|
|
175
175
|
* Saves the cryptographic key to a file.
|
|
@@ -440,27 +440,27 @@ class TinyCrypto {
|
|
|
440
440
|
function: () => {
|
|
441
441
|
throw new Error('Function cannot be serialized');
|
|
442
442
|
},
|
|
443
|
-
regexp: (data) => JSON.stringify({ __type: '
|
|
444
|
-
htmlElement: (data) => JSON.stringify({ __type: '
|
|
445
|
-
date: (data) => JSON.stringify({ __type: '
|
|
446
|
-
bigint: (data) => JSON.stringify({ __type: '
|
|
447
|
-
number: (data) => JSON.stringify({ __type: '
|
|
448
|
-
boolean: (data) => JSON.stringify({ __type: '
|
|
449
|
-
string: (data) => JSON.stringify({ __type: '
|
|
450
|
-
null: (data) => JSON.stringify({ __type: '
|
|
451
|
-
undefined: (data) => JSON.stringify({ __type: '
|
|
443
|
+
regexp: (data) => JSON.stringify({ __type: 'regexp', value: data.toString() }),
|
|
444
|
+
htmlElement: (data) => JSON.stringify({ __type: 'htmlelement', value: data.outerHTML }),
|
|
445
|
+
date: (data) => JSON.stringify({ __type: 'date', value: data.toISOString() }),
|
|
446
|
+
bigint: (data) => JSON.stringify({ __type: 'bigint', value: data.toString() }),
|
|
447
|
+
number: (data) => JSON.stringify({ __type: 'number', value: data }),
|
|
448
|
+
boolean: (data) => JSON.stringify({ __type: 'boolean', value: data }),
|
|
449
|
+
string: (data) => JSON.stringify({ __type: 'string', value: data }),
|
|
450
|
+
null: (data) => JSON.stringify({ __type: 'null' }),
|
|
451
|
+
undefined: (data) => JSON.stringify({ __type: 'undefined' }),
|
|
452
452
|
map: (data) => JSON.stringify({
|
|
453
|
-
__type: '
|
|
453
|
+
__type: 'map',
|
|
454
454
|
value: Array.from(data.entries()),
|
|
455
455
|
}),
|
|
456
456
|
set: (data) => JSON.stringify({
|
|
457
|
-
__type: '
|
|
457
|
+
__type: 'set',
|
|
458
458
|
value: Array.from(data.values()),
|
|
459
459
|
}),
|
|
460
|
-
symbol: (data) => JSON.stringify({ __type: '
|
|
461
|
-
array: (data) => JSON.stringify({ __type: '
|
|
462
|
-
object: (data) => JSON.stringify({ __type: '
|
|
463
|
-
buffer: (data) => JSON.stringify({ __type: '
|
|
460
|
+
symbol: (data) => JSON.stringify({ __type: 'symbol', value: data.description }),
|
|
461
|
+
array: (data) => JSON.stringify({ __type: 'array', value: data }),
|
|
462
|
+
object: (data) => JSON.stringify({ __type: 'object', value: data }),
|
|
463
|
+
buffer: (data) => JSON.stringify({ __type: 'buffer', value: data.toString('base64') }),
|
|
464
464
|
};
|
|
465
465
|
/**
|
|
466
466
|
* A mapping of data types to their deserialization functions.
|
|
@@ -471,47 +471,47 @@ class TinyCrypto {
|
|
|
471
471
|
* and the value is a function that deserializes the value to its original format.
|
|
472
472
|
*
|
|
473
473
|
* @type {Object}
|
|
474
|
-
* @property {Function}
|
|
475
|
-
* @property {Function}
|
|
476
|
-
* @property {Function}
|
|
477
|
-
* @property {Function}
|
|
478
|
-
* @property {Function}
|
|
479
|
-
* @property {Function}
|
|
480
|
-
* @property {Function}
|
|
481
|
-
* @property {Function}
|
|
482
|
-
* @property {Function}
|
|
483
|
-
* @property {Function}
|
|
484
|
-
* @property {Function}
|
|
485
|
-
* @property {Function}
|
|
486
|
-
* @property {Function}
|
|
487
|
-
* @property {Function}
|
|
488
|
-
* @property {Function}
|
|
474
|
+
* @property {Function} regexp - Deserializes a regular expression from its string representation (e.g., `/pattern/flags`).
|
|
475
|
+
* @property {Function} htmlelement - Deserializes an HTML element from its serialized outerHTML string (only works in browser environments).
|
|
476
|
+
* @property {Function} date - Deserializes a date from its ISO string representation.
|
|
477
|
+
* @property {Function} bigint - Deserializes a BigInt from its string representation.
|
|
478
|
+
* @property {Function} number - Deserializes a number from its string or numeric representation.
|
|
479
|
+
* @property {Function} boolean - Deserializes a boolean value from its string representation.
|
|
480
|
+
* @property {Function} null - Deserializes the `null` value.
|
|
481
|
+
* @property {Function} undefined - Deserializes the `undefined` value.
|
|
482
|
+
* @property {Function} map - Deserializes a Map from an array of key-value pairs.
|
|
483
|
+
* @property {Function} set - Deserializes a Set from an array of values.
|
|
484
|
+
* @property {Function} symbol - Deserializes a Symbol from its string description.
|
|
485
|
+
* @property {Function} array - Deserializes an array from its serialized representation.
|
|
486
|
+
* @property {Function} object - Deserializes a plain JSON object from its serialized representation.
|
|
487
|
+
* @property {Function} string - Deserializes a string from its serialized representation.
|
|
488
|
+
* @property {Function} buffer - Deserializes a Buffer from its base64-encoded string representation.
|
|
489
489
|
*/
|
|
490
490
|
#valueTypes = {
|
|
491
|
-
|
|
491
|
+
regexp: (value) => {
|
|
492
492
|
const match = value.match(/^\/(.*)\/([gimsuy]*)$/);
|
|
493
493
|
return match ? new RegExp(match[1], match[2]) : new RegExp(value);
|
|
494
494
|
},
|
|
495
|
-
|
|
495
|
+
htmlelement: (value) => {
|
|
496
496
|
if (typeof document === 'undefined')
|
|
497
497
|
throw new Error('HTMLElement deserialization is only supported in browsers');
|
|
498
498
|
const div = document.createElement('div');
|
|
499
499
|
div.innerHTML = value;
|
|
500
500
|
return div.firstElementChild;
|
|
501
501
|
},
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
502
|
+
date: (value) => new Date(value),
|
|
503
|
+
bigint: (value) => BigInt(value),
|
|
504
|
+
number: (value) => Number(value),
|
|
505
|
+
boolean: (value) => Boolean(value),
|
|
506
|
+
null: (value) => null,
|
|
507
|
+
undefined: (value) => undefined,
|
|
508
|
+
map: (value) => new Map(value),
|
|
509
|
+
set: (value) => new Set(value),
|
|
510
|
+
symbol: (value) => Symbol(value),
|
|
511
|
+
array: (value) => value,
|
|
512
|
+
object: (value) => value,
|
|
513
|
+
string: (value) => String(value),
|
|
514
|
+
buffer: (value) => Buffer.from(value, 'base64'),
|
|
515
515
|
};
|
|
516
516
|
/**
|
|
517
517
|
* Serializes a given data value into a JSON-compatible format based on its type.
|
|
@@ -542,7 +542,7 @@ class TinyCrypto {
|
|
|
542
542
|
const parsed = JSON.parse(text);
|
|
543
543
|
const type = parsed.__type;
|
|
544
544
|
if (typeof type !== 'string')
|
|
545
|
-
return { value: text, type: '
|
|
545
|
+
return { value: text, type: 'string' };
|
|
546
546
|
if (typeof this.#valueTypes[type] === 'function')
|
|
547
547
|
return {
|
|
548
548
|
value: this.#valueTypes[type](parsed.value),
|
|
@@ -565,8 +565,8 @@ class TinyCrypto {
|
|
|
565
565
|
* @throws {Error} If the types do not match.
|
|
566
566
|
*/
|
|
567
567
|
#validateDeserializedType(expected, actual) {
|
|
568
|
-
if (expected
|
|
569
|
-
throw new Error(`Type mismatch: expected ${expected
|
|
568
|
+
if (expected !== actual)
|
|
569
|
+
throw new Error(`Type mismatch: expected ${expected}, but got ${actual}`);
|
|
570
570
|
}
|
|
571
571
|
}
|
|
572
572
|
export default TinyCrypto;
|
package/docs/libs/TinyCrypto.md
CHANGED
|
@@ -79,7 +79,7 @@ const result = crypto.encrypt('Hello!');
|
|
|
79
79
|
Decrypts a previously encrypted value and returns the original data. You can optionally pass an `expectedType` to validate it.
|
|
80
80
|
|
|
81
81
|
```js
|
|
82
|
-
const plain = crypto.decrypt(result, '
|
|
82
|
+
const plain = crypto.decrypt(result, 'string');
|
|
83
83
|
```
|
|
84
84
|
|
|
85
85
|
---
|
|
@@ -136,7 +136,7 @@ Returns an object with the current settings:
|
|
|
136
136
|
"outputEncoding": "hex",
|
|
137
137
|
"inputEncoding": "utf8",
|
|
138
138
|
"authTagLength": 16,
|
|
139
|
-
"key": "..."
|
|
139
|
+
"key": "..."
|
|
140
140
|
}
|
|
141
141
|
```
|
|
142
142
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tiny-essentials",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"description": "Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "npm run test:mjs && npm run test:cjs && npm run test:js",
|