@ztimson/utils 0.21.2 → 0.21.4
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/dist/aset.d.ts +8 -0
- package/dist/index.cjs +1421 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +958 -716
- package/dist/index.mjs.map +1 -1
- package/dist/path-events.d.ts +15 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,1422 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`)}class R extends Promise{constructor(e){super((n,s)=>e(i=>n(i),i=>s(i),i=>this.progress=i));a(this,"listeners",[]);a(this,"_progress",0)}get progress(){return this._progress}set progress(e){e!=this._progress&&(this._progress=e,this.listeners.forEach(n=>n(e)))}static from(e){return e instanceof R?e:new R((n,s)=>e.then((...i)=>n(...i)).catch((...i)=>s(...i)))}from(e){const n=R.from(e);return this.onProgress(s=>n.progress=s),n}onProgress(e){return this.listeners.push(e),this}then(e,n){const s=super.then(e,n);return this.from(s)}catch(e){return this.from(super.catch(e))}finally(e){return this.from(super.finally(e))}}function Ct(r,t){r instanceof Blob||(r=new Blob(B(r)));const e=URL.createObjectURL(r);at(e,t),URL.revokeObjectURL(e)}function at(r,t){const e=document.createElement("a");e.href=r,e.download=t||r.split("/").pop(),document.body.appendChild(e),e.click(),document.body.removeChild(e)}function $t(r={}){return new Promise(t=>{const e=document.createElement("input");e.type="file",e.accept=r.accept||"*",e.style.display="none",e.multiple=!!r.multiple,e.onblur=e.onchange=async()=>{t(Array.from(e.files)),e.remove()},document.body.appendChild(e),e.click()})}function Nt(r,t=new Date){(typeof t=="number"||typeof t=="string")&&(t=new Date(t));const e=`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}_${t.getHours().toString().padStart(2,"0")}-${t.getMinutes().toString().padStart(2,"0")}-${t.getSeconds().toString().padStart(2,"0")}`;return r?r.replace("{{TIMESTAMP}}",e):e}function Lt(r){return new R((t,e,n)=>{const s=new XMLHttpRequest,i=new FormData;r.files.forEach(o=>i.append("file",o)),s.withCredentials=!!r.withCredentials,s.upload.addEventListener("progress",o=>o.lengthComputable?n(o.loaded/o.total):null),s.addEventListener("loadend",()=>t(T(s.responseText))),s.addEventListener("error",()=>e(T(s.responseText))),s.addEventListener("timeout",()=>e({error:"Request timed out"})),s.open("POST",r.url),Object.entries(r.headers||{}).forEach(([o,l])=>s.setRequestHeader(o,l)),s.send(i)})}class U{constructor(){a(this,"listeners",{})}static emit(t,...e){(this.listeners["*"]||[]).forEach(n=>n(t,...e)),(this.listeners[t.toString()]||[]).forEach(n=>n(...e))}static off(t,e){const n=t.toString();this.listeners[n]=(this.listeners[n]||[]).filter(s=>s===e)}static on(t,e){var s;const n=t.toString();return this.listeners[n]||(this.listeners[n]=[]),(s=this.listeners[n])==null||s.push(e),()=>this.off(t,e)}static once(t,e){return new Promise(n=>{const s=this.on(t,(...i)=>{n(i.length==1?i[0]:i),e&&e(...i),s()})})}emit(t,...e){(this.listeners["*"]||[]).forEach(n=>n(t,...e)),(this.listeners[t]||[]).forEach(n=>n(...e))}off(t,e){this.listeners[t]=(this.listeners[t]||[]).filter(n=>n===e)}on(t,e){var n;return this.listeners[t]||(this.listeners[t]=[]),(n=this.listeners[t])==null||n.push(e),()=>this.off(t,e)}once(t,e){return new Promise(n=>{const s=this.on(t,(...i)=>{n(i.length==1?i[0]:i),e&&e(...i),s()})})}}a(U,"listeners",{});class g extends Error{constructor(e,n){super(e);a(this,"_code");n!=null&&(this._code=n)}get code(){return this._code||this.constructor.code}set code(e){this._code=e}static from(e){const n=Number(e.statusCode)??Number(e.code),s=new this(e.message||e.toString());return Object.assign(s,{stack:e.stack,...e,code:n??void 0})}static instanceof(e){return e.constructor.code!=null}toString(){return this.message||super.toString()}}a(g,"code",500);class q extends g{constructor(t="Bad Request"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(q,"code",400);class F extends g{constructor(t="Unauthorized"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(F,"code",401);class G extends g{constructor(t="Payment Required"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(G,"code",402);class v extends g{constructor(t="Forbidden"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(v,"code",403);class H extends g{constructor(t="Not Found"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(H,"code",404);class Y extends g{constructor(t="Method Not Allowed"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(Y,"code",405);class K extends g{constructor(t="Not Acceptable"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(K,"code",406);class W extends g{constructor(t="Internal Server Error"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(W,"code",500);class J extends g{constructor(t="Not Implemented"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(J,"code",501);class z extends g{constructor(t="Bad Gateway"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(z,"code",502);class V extends g{constructor(t="Service Unavailable"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(V,"code",503);class Z extends g{constructor(t="Gateway Timeout"){super(t)}static instanceof(t){return t.constructor.code==this.code}}a(Z,"code",504);function jt(r,t){if(r>=200&&r<300)return null;switch(r){case 400:return new q(t);case 401:return new F(t);case 402:return new G(t);case 403:return new v(t);case 404:return new H(t);case 405:return new Y(t);case 406:return new K(t);case 500:return new W(t);case 501:return new J(t);case 502:return new z(t);case 503:return new V(t);case 504:return new Z(t);default:return new g(t,r)}}const b=class b{constructor(t={}){a(this,"interceptors",{});a(this,"headers",{});a(this,"url");this.url=t.url??null,this.headers=t.headers||{},t.interceptors&&t.interceptors.forEach(e=>b.addInterceptor(e))}static addInterceptor(t){const e=Object.keys(b.interceptors).length.toString();return b.interceptors[e]=t,()=>{b.interceptors[e]=null}}addInterceptor(t){const e=Object.keys(this.interceptors).length.toString();return this.interceptors[e]=t,()=>{this.interceptors[e]=null}}request(t={}){var s;if(!this.url&&!t.url)throw new Error("URL needs to be set");let e=((s=t.url)!=null&&s.startsWith("http")?t.url:(this.url||"")+(t.url||"")).replace(/([^:]\/)\/+/g,"$1");if(t.fragment&&(e.includes("#")?e.replace(/#.*(\?|\n)/g,(i,o)=>`#${t.fragment}${o}`):e+="#"+t.fragment),t.query){const i=Array.isArray(t.query)?t.query:Object.keys(t.query).map(o=>({key:o,value:t.query[o]}));e+=(e.includes("?")?"&":"?")+i.map(o=>`${o.key}=${o.value}`).join("&")}const n=w({"Content-Type":t.body?t.body instanceof FormData?"multipart/form-data":"application/json":void 0,...b.headers,...this.headers,...t.headers});return typeof t.body=="object"&&t.body!=null&&n["Content-Type"]=="application/json"&&(t.body=JSON.stringify(t.body)),new R((i,o,l)=>{try{fetch(e,{headers:n,method:t.method||(t.body?"POST":"GET"),body:t.body}).then(async u=>{var mt,yt;for(let h of[...Object.values(b.interceptors),...Object.values(this.interceptors)])await new Promise(D=>h(u,()=>D()));const I=u.headers.get("Content-Length"),rt=I?parseInt(I,10):0;let ft=0;const nt=(mt=u.body)==null?void 0:mt.getReader(),ie=new ReadableStream({start(h){function D(){nt==null||nt.read().then(j=>{if(j.done)return h.close();ft+=j.value.byteLength,l(ft/rt),h.enqueue(j.value),D()}).catch(j=>h.error(j))}D()}});if(u.data=new Response(ie),t.decode==null||t.decode){const h=(yt=u.headers.get("Content-Type"))==null?void 0:yt.toLowerCase();h!=null&&h.includes("form")?u.data=await u.data.formData():h!=null&&h.includes("json")?u.data=await u.data.json():h!=null&&h.includes("text")?u.data=await u.data.text():h!=null&&h.includes("application")&&(u.data=await u.data.blob())}u.ok?i(u):o(u)}).catch(u=>o(u))}catch(u){o(u)}})}};a(b,"interceptors",{}),a(b,"headers",{});let Q=b;function Tt(r){const t=r.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");return T(decodeURIComponent(atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join("")))}const N={CLEAR:"\x1B[0m",BRIGHT:"\x1B[1m",DIM:"\x1B[2m",UNDERSCORE:"\x1B[4m",BLINK:"\x1B[5m",REVERSE:"\x1B[7m",HIDDEN:"\x1B[8m"},L={BLACK:"\x1B[30m",RED:"\x1B[31m",GREEN:"\x1B[32m",YELLOW:"\x1B[33m",BLUE:"\x1B[34m",MAGENTA:"\x1B[35m",CYAN:"\x1B[36m",LIGHT_GREY:"\x1B[37m",GREY:"\x1B[90m",LIGHT_RED:"\x1B[91m",LIGHT_GREEN:"\x1B[92m",LIGHT_YELLOW:"\x1B[93m",LIGHT_BLUE:"\x1B[94m",LIGHT_MAGENTA:"\x1B[95m",LIGHT_CYAN:"\x1B[96m",WHITE:"\x1B[97m"},Pt={BLACK:"\x1B[40m",RED:"\x1B[41m",GREEN:"\x1B[42m",YELLOW:"\x1B[43m",BLUE:"\x1B[44m",MAGENTA:"\x1B[45m",CYAN:"\x1B[46m",WHITE:"\x1B[47m",GREY:"\x1B[100m"};var ut=(r=>(r[r.ERROR=0]="ERROR",r[r.WARN=1]="WARN",r[r.INFO=2]="INFO",r[r.LOG=3]="LOG",r[r.DEBUG=4]="DEBUG",r))(ut||{});const E=class E extends U{constructor(t){super(),this.namespace=t}format(...t){const e=new Date;return`${`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()} ${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padEnd(3,"0")}`}${this.namespace?` [${this.namespace}]`:""} ${t.map(s=>typeof s=="string"?s:it(s,2)).join(" ")}`}debug(...t){if(E.LOG_LEVEL<4)return;const e=this.format(...t);E.emit(4,e),console.debug(L.LIGHT_GREY+e+N.CLEAR)}log(...t){if(E.LOG_LEVEL<3)return;const e=this.format(...t);E.emit(3,e),console.log(N.CLEAR+e)}info(...t){if(E.LOG_LEVEL<2)return;const e=this.format(...t);E.emit(2,e),console.info(L.BLUE+e+N.CLEAR)}warn(...t){if(E.LOG_LEVEL<1)return;const e=this.format(...t);E.emit(1,e),console.warn(L.YELLOW+e+N.CLEAR)}error(...t){if(E.LOG_LEVEL<0)return;const e=this.format(...t);E.emit(0,e),console.error(L.RED+e+N.CLEAR)}};a(E,"LOG_LEVEL",4);let X=E;function It(r){const t=(l,u)=>u<1e-7?l:t(u,~~(l%u)),e=r.toString().length-2;let n=Math.pow(10,e),s=r*n;const i=t(s,n);s=~~(s/i),n=~~(n/i);const o=~~(s/n);return s-=o*n,`${o?o+" ":""}${~~s}/${~~n}`}function Dt(r){let t=r.split(" ");const e=t.length==2?Number(t[0]):0;return t=t.pop().split("/"),e+Number(t[0])/Number(t[1])}const x="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",_="0123456789",tt="~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/",Mt=x+_+tt;function kt(r,t=2){if(r===0)return"0 Bytes";const e=1024,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],s=Math.floor(Math.log(r)/Math.log(e));return parseFloat((r/Math.pow(e,s)).toFixed(t))+" "+n[s]}function Ut(r){const t=/(\+?1)?.*?(\d{3}).*?(\d{3}).*?(\d{4})/g.exec(r);if(!t)throw new Error(`Number cannot be parsed: ${r}`);return`${t[1]??""} (${t[2]}) ${t[3]}-${t[4]}`.trim()}function qt(r,t,e){return`${r.slice(0,e)}${t}${r.slice(e+1)}`}function Ft(r,t,e=" ",n=!0){return n?r.toString().padStart(t,e):r.toString().padEnd(t,e)}function Gt(r){return Array(r).fill(null).map(()=>Math.round(Math.random()*15).toString(16)).join("")}function vt(r,t=Mt){return Array(r).fill(null).map(()=>{const e=~~(Math.random()*t.length);return t[e]}).join("")}function Ht(r,t=!1,e=!1,n=!1){if(!t&&!e&&!n)throw new Error("Must enable at least one: letters, numbers, symbols");return Array(r).fill(null).map(()=>{let s;do{const i=~~(Math.random()*3);t&&i==0?s=x[~~(Math.random()*x.length)]:e&&i==1?s=_[~~(Math.random()*_.length)]:n&&i==2&&(s=tt[~~(Math.random()*tt.length)])}while(!s);return s}).join("")}function Yt(r,t){if(typeof t=="string"&&(t=new RegExp(t,"g")),!t.global)throw new TypeError("Regular expression must be global.");let e=[],n;for(;(n=t.exec(r))!==null;)e.push(n);return e}function Kt(r){const t=new RegExp("(?:(?<protocol>[\\w\\d]+)\\:\\/\\/)?(?:(?<user>.+)\\@)?(?<host>(?<domain>[^:\\/\\?#@\\n]+)(?:\\:(?<port>\\d*))?)(?<path>\\/.*?)?(?:\\?(?<query>.*?))?(?:#(?<fragment>.*?))?$","gm").exec(r),e=(t==null?void 0:t.groups)??{},n=e.domain.split(".");if(e.port!=null&&(e.port=Number(e.port)),n.length>2&&(e.domain=n.splice(-2,2).join("."),e.subdomain=n.join(".")),e.query){const s=e.query.split("&"),i={};s.forEach(o=>{const[l,u]=o.split("=");i[l]=u}),e.query=i}return e}function lt(r){var t=Wt(zt(Vt(Jt(r),8*r.length)));return t.toLowerCase()}function Wt(r){for(var t,e="0123456789ABCDEF",n="",s=0;s<r.length;s++)t=r.charCodeAt(s),n+=e.charAt(t>>>4&15)+e.charAt(15&t);return n}function Jt(r){for(var t=Array(r.length>>2),e=0;e<t.length;e++)t[e]=0;for(e=0;e<8*r.length;e+=8)t[e>>5]|=(255&r.charCodeAt(e/8))<<e%32;return t}function zt(r){for(var t="",e=0;e<32*r.length;e+=8)t+=String.fromCharCode(r[e>>5]>>>e%32&255);return t}function Vt(r,t){r[t>>5]|=128<<t%32,r[14+(t+64>>>9<<4)]=t;for(var e=1732584193,n=-271733879,s=-1732584194,i=271733878,o=0;o<r.length;o+=16){var l=e,u=n,I=s,rt=i;n=y(n=y(n=y(n=y(n=m(n=m(n=m(n=m(n=f(n=f(n=f(n=f(n=d(n=d(n=d(n=d(n,s=d(s,i=d(i,e=d(e,n,s,i,r[o+0],7,-680876936),n,s,r[o+1],12,-389564586),e,n,r[o+2],17,606105819),i,e,r[o+3],22,-1044525330),s=d(s,i=d(i,e=d(e,n,s,i,r[o+4],7,-176418897),n,s,r[o+5],12,1200080426),e,n,r[o+6],17,-1473231341),i,e,r[o+7],22,-45705983),s=d(s,i=d(i,e=d(e,n,s,i,r[o+8],7,1770035416),n,s,r[o+9],12,-1958414417),e,n,r[o+10],17,-42063),i,e,r[o+11],22,-1990404162),s=d(s,i=d(i,e=d(e,n,s,i,r[o+12],7,1804603682),n,s,r[o+13],12,-40341101),e,n,r[o+14],17,-1502002290),i,e,r[o+15],22,1236535329),s=f(s,i=f(i,e=f(e,n,s,i,r[o+1],5,-165796510),n,s,r[o+6],9,-1069501632),e,n,r[o+11],14,643717713),i,e,r[o+0],20,-373897302),s=f(s,i=f(i,e=f(e,n,s,i,r[o+5],5,-701558691),n,s,r[o+10],9,38016083),e,n,r[o+15],14,-660478335),i,e,r[o+4],20,-405537848),s=f(s,i=f(i,e=f(e,n,s,i,r[o+9],5,568446438),n,s,r[o+14],9,-1019803690),e,n,r[o+3],14,-187363961),i,e,r[o+8],20,1163531501),s=f(s,i=f(i,e=f(e,n,s,i,r[o+13],5,-1444681467),n,s,r[o+2],9,-51403784),e,n,r[o+7],14,1735328473),i,e,r[o+12],20,-1926607734),s=m(s,i=m(i,e=m(e,n,s,i,r[o+5],4,-378558),n,s,r[o+8],11,-2022574463),e,n,r[o+11],16,1839030562),i,e,r[o+14],23,-35309556),s=m(s,i=m(i,e=m(e,n,s,i,r[o+1],4,-1530992060),n,s,r[o+4],11,1272893353),e,n,r[o+7],16,-155497632),i,e,r[o+10],23,-1094730640),s=m(s,i=m(i,e=m(e,n,s,i,r[o+13],4,681279174),n,s,r[o+0],11,-358537222),e,n,r[o+3],16,-722521979),i,e,r[o+6],23,76029189),s=m(s,i=m(i,e=m(e,n,s,i,r[o+9],4,-640364487),n,s,r[o+12],11,-421815835),e,n,r[o+15],16,530742520),i,e,r[o+2],23,-995338651),s=y(s,i=y(i,e=y(e,n,s,i,r[o+0],6,-198630844),n,s,r[o+7],10,1126891415),e,n,r[o+14],15,-1416354905),i,e,r[o+5],21,-57434055),s=y(s,i=y(i,e=y(e,n,s,i,r[o+12],6,1700485571),n,s,r[o+3],10,-1894986606),e,n,r[o+10],15,-1051523),i,e,r[o+1],21,-2054922799),s=y(s,i=y(i,e=y(e,n,s,i,r[o+8],6,1873313359),n,s,r[o+15],10,-30611744),e,n,r[o+6],15,-1560198380),i,e,r[o+13],21,1309151649),s=y(s,i=y(i,e=y(e,n,s,i,r[o+4],6,-145523070),n,s,r[o+11],10,-1120210379),e,n,r[o+2],15,718787259),i,e,r[o+9],21,-343485551),e=A(e,l),n=A(n,u),s=A(s,I),i=A(i,rt)}return Array(e,n,s,i)}function P(r,t,e,n,s,i){return A(Zt(A(A(t,r),A(n,i)),s),e)}function d(r,t,e,n,s,i,o){return P(t&e|~t&n,r,t,s,i,o)}function f(r,t,e,n,s,i,o){return P(t&n|e&~n,r,t,s,i,o)}function m(r,t,e,n,s,i,o){return P(t^e^n,r,t,s,i,o)}function y(r,t,e,n,s,i,o){return P(e^(t|~n),r,t,s,i,o)}function A(r,t){var e=(65535&r)+(65535&t);return(r>>16)+(t>>16)+(e>>16)<<16|65535&e}function Zt(r,t){return r<<t|r>>>32-t}function Qt(r){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(r)}function Xt(r,t="mp"){return r?`https://www.gravatar.com/avatar/${lt(r)}?d=${t}`:""}function xt(r){return r.replace(/[.*+?^${}()|\[\]\\]/g,"\\$&")}function _t(r,...t){const e=[];for(let n=0;n<r.length||n<t.length;n++)r[n]&&e.push(r[n]),t[n]&&e.push(t[n]);return new p(e.join(""))}function ht(r,...t){let e=[];for(let i=0;i<r.length||i<t.length;i++)r[i]&&e.push(r[i]),t[i]&&e.push(t[i]);const[n,s]=e.join("").split(":");return p.toString(n,s==null?void 0:s.split(""))}class et extends Error{}class p{constructor(t){a(this,"module");a(this,"fullPath");a(this,"path");a(this,"name");a(this,"methods");var o;if(typeof t=="object")return Object.assign(this,t);let[e,n,s]=t.split(":");s||(s=n||"*"),(e=="*"||!e&&s=="*")&&(e="",s="*");let i=e.split("/").filter(l=>!!l);this.module=((o=i.splice(0,1)[0])==null?void 0:o.toLowerCase())||"",this.fullPath=e,this.path=i.join("/"),this.name=i.pop()||"",this.methods=new S(s.split(""))}get all(){return this.methods.has("*")}set all(t){t?new S(["*"]):this.methods.delete("*")}get none(){return this.methods.has("n")}set none(t){t?this.methods=new S(["n"]):this.methods.delete("n")}get create(){return!this.methods.has("n")&&(this.methods.has("*")||this.methods.has("c"))}set create(t){t?this.methods.delete("n").add("c"):this.methods.delete("c")}get read(){return!this.methods.has("n")&&(this.methods.has("*")||this.methods.has("r"))}set read(t){t?this.methods.delete("n").add("r"):this.methods.delete("r")}get update(){return!this.methods.has("n")&&(this.methods.has("*")||this.methods.has("u"))}set update(t){t?this.methods.delete("n").add("u"):this.methods.delete("u")}get delete(){return!this.methods.has("n")&&(this.methods.has("*")||this.methods.has("d"))}set delete(t){t?this.methods.delete("n").add("d"):this.methods.delete("d")}static combine(...t){let e=!1;const n=t.map(s=>new p(s)).toSorted((s,i)=>{const o=s.fullPath.length,l=i.fullPath.length;return o<l?1:o>l?-1:0}).reduce((s,i)=>(i.none&&(e=!0),s?(e||(i.all&&(s.all=!0),(i.all||i.create)&&(s.create=!0),(i.all||i.read)&&(s.read=!0),(i.all||i.update)&&(s.update=!0),(i.all||i.delete)&&(s.delete=!0),s.methods=[...s.methods,...i.methods]),s):i),null);return n.methods=new S(n.methods),n.raw=ht`${n.fullPath}:${n.methods}`,n}static has(t,...e){const n=B(e).map(i=>new p(i)),s=B(t).map(i=>new p(i));return!!n.find(i=>{if(!i.fullPath&&i.all)return!0;const o=s.filter(u=>i.fullPath.startsWith(u.fullPath));if(!o.length)return!1;const l=p.combine(...o);return!l.none&&(l.all||new S(l.methods).intersection(new S(i.methods)).length)})}static hasAll(t,...e){return e.filter(n=>p.has(t,n)).length==e.length}static hasFatal(t,...e){if(!p.has(t,...e))throw new et(`Requires one of: ${B(e).join(", ")}`)}static hasAllFatal(t,...e){if(!p.hasAll(t,...e))throw new et(`Requires all: ${B(e).join(", ")}`)}static toString(t,e){let n=B(t).filter(s=>s!=null).join("/");return n=n==null?void 0:n.trim().replaceAll(/\/{2,}/g,"/").replaceAll(/(^\/|\/$)/g,""),e!=null&&e.length&&(n+=`:${B(e).map(s=>s.toLowerCase()).join("")}`),n}toString(){return p.toString(this.fullPath,this.methods)}}class te{constructor(){a(this,"listeners",[])}emit(t,...e){const n=new p(t);this.listeners.filter(s=>p.has(s[0],t)).forEach(async s=>s[1](n,...e))}off(t){this.listeners=this.listeners.filter(e=>e[1]!=t)}on(t,e){return B(t).forEach(n=>this.listeners.push([new p(n),e])),()=>this.off(e)}once(t,e){return new Promise(n=>{const s=this.on(t,(i,...o)=>{n(o.length<2?o[0]:o),e&&e(i,...o),s()})})}relayEvents(t){t.on("*",(e,...n)=>this.emit(e,...n))}}function ee(r){(typeof r=="number"||typeof r=="string")&&(r=new Date(r));let t=r.getHours(),e="AM";return t>=12?(t>12&&(t-=12),e="PM"):t==0&&(t=12),`${r.getFullYear()}-${(r.getMonth()+1).toString().padStart(2,"0")}-${r.getDate().toString().padStart(2,"0")}, ${t}:${r.getMinutes().toString().padStart(2,"0")} ${e}`}function dt(r){return new Promise(t=>setTimeout(t,r))}async function re(r,t=100){for(;await r();)await dt(t)}function ne(r){return(r instanceof Date?r.getTime():r)-new Date().getTime()}function se(){return Object.keys({})}c.ASet=S,c.BadGatewayError=z,c.BadRequestError=q,c.Cache=Ot,c.CliBackground=Pt,c.CliEffects=N,c.CliForeground=L,c.CustomError=g,c.ForbiddenError=v,c.GatewayTimeoutError=Z,c.Http=Q,c.InternalServerError=W,c.JSONAttemptParse=T,c.JSONSanitize=it,c.LOG_LEVEL=ut,c.Logger=X,c.MethodNotAllowedError=Y,c.NotAcceptableError=K,c.NotFoundError=H,c.NotImplementedError=J,c.PE=_t,c.PES=ht,c.PathError=et,c.PathEvent=p,c.PathEventEmitter=te,c.PaymentRequiredError=G,c.PromiseProgress=R,c.ServiceUnavailableError=V,c.TypedEmitter=U,c.UnauthorizedError=F,c.addUnique=Et,c.arrayDiff=St,c.caseInsensitiveSort=bt,c.clean=w,c.csv=Rt,c.dec2Frac=It,c.deepCopy=C,c.deepMerge=st,c.dotNotation=O,c.downloadFile=Ct,c.downloadUrl=at,c.encodeQuery=gt,c.errorFromCode=jt,c.escapeRegex=xt,c.fileBrowser=$t,c.findByProp=Bt,c.flattenArr=ot,c.flattenObj=M,c.formData=pt,c.formatBytes=kt,c.formatDate=ee,c.formatPhoneNumber=Ut,c.fracToDec=Dt,c.gravatar=Xt,c.includes=k,c.insertAt=qt,c.isEqual=$,c.jwtDecode=Tt,c.makeArray=B,c.makeUnique=ct,c.matchAll=Yt,c.md5=lt,c.mixin=wt,c.pad=Ft,c.parseUrl=Kt,c.randomHex=Gt,c.randomString=vt,c.randomStringBuilder=Ht,c.sleep=dt,c.sleepWhile=re,c.sortByProp=At,c.timeUntil=ne,c.timestampFilename=Nt,c.tyoeKeys=se,c.uploadWithProgress=Lt,c.validateEmail=Qt,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(global, factory) {
|
|
2
|
+
typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.utils = {}));
|
|
3
|
+
})(this, function(exports2) {
|
|
4
|
+
"use strict";var __defProp = Object.defineProperty;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
7
|
+
|
|
8
|
+
function clean(obj, undefinedOnly = false) {
|
|
9
|
+
if (obj == null) throw new Error("Cannot clean a NULL value");
|
|
10
|
+
if (Array.isArray(obj)) {
|
|
11
|
+
obj = obj.filter((o) => o != null);
|
|
12
|
+
} else {
|
|
13
|
+
Object.entries(obj).forEach(([key, value]) => {
|
|
14
|
+
if (undefinedOnly && value === void 0 || !undefinedOnly && value == null) delete obj[key];
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return obj;
|
|
18
|
+
}
|
|
19
|
+
function deepCopy(value) {
|
|
20
|
+
return structuredClone(value);
|
|
21
|
+
}
|
|
22
|
+
function deepMerge(target, ...sources) {
|
|
23
|
+
sources.forEach((s) => {
|
|
24
|
+
for (const key in s) {
|
|
25
|
+
if (s[key] && typeof s[key] == "object" && !Array.isArray(s[key])) {
|
|
26
|
+
if (!target[key]) target[key] = {};
|
|
27
|
+
deepMerge(target[key], s[key]);
|
|
28
|
+
} else {
|
|
29
|
+
target[key] = s[key];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
return target;
|
|
34
|
+
}
|
|
35
|
+
function dotNotation(obj, prop, set) {
|
|
36
|
+
if (obj == null || !prop) return void 0;
|
|
37
|
+
return prop.split(/[.[\]]/g).filter((prop2) => prop2.length).reduce((obj2, prop2, i, arr) => {
|
|
38
|
+
if (prop2[0] == '"' || prop2[0] == "'") prop2 = prop2.slice(1, -1);
|
|
39
|
+
if (!(obj2 == null ? void 0 : obj2.hasOwnProperty(prop2))) {
|
|
40
|
+
if (set == void 0) return void 0;
|
|
41
|
+
obj2[prop2] = {};
|
|
42
|
+
}
|
|
43
|
+
if (set !== void 0 && i == arr.length - 1)
|
|
44
|
+
return obj2[prop2] = set;
|
|
45
|
+
return obj2[prop2];
|
|
46
|
+
}, obj);
|
|
47
|
+
}
|
|
48
|
+
function encodeQuery(data) {
|
|
49
|
+
return Object.entries(data).map(
|
|
50
|
+
([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value)
|
|
51
|
+
).join("&");
|
|
52
|
+
}
|
|
53
|
+
function flattenObj(obj, parent, result = {}) {
|
|
54
|
+
if (typeof obj === "object" && !Array.isArray(obj)) {
|
|
55
|
+
for (const key of Object.keys(obj)) {
|
|
56
|
+
const propName = parent ? parent + "." + key : key;
|
|
57
|
+
if (typeof obj[key] === "object") {
|
|
58
|
+
flattenObj(obj[key], propName, result);
|
|
59
|
+
} else {
|
|
60
|
+
result[propName] = obj[key];
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function formData(target) {
|
|
67
|
+
const data = new FormData();
|
|
68
|
+
Object.entries(target).forEach(([key, value]) => data.append(key, value));
|
|
69
|
+
return data;
|
|
70
|
+
}
|
|
71
|
+
function includes(target, values, allowMissing = false) {
|
|
72
|
+
if (target == void 0) return allowMissing;
|
|
73
|
+
if (Array.isArray(values)) return values.findIndex((e, i) => !includes(target[i], values[i], allowMissing)) == -1;
|
|
74
|
+
const type = typeof values;
|
|
75
|
+
if (type != typeof target) return false;
|
|
76
|
+
if (type == "object") {
|
|
77
|
+
return Object.keys(values).find((key) => !includes(target[key], values[key], allowMissing)) == null;
|
|
78
|
+
}
|
|
79
|
+
if (type == "function") return target.toString() == values.toString();
|
|
80
|
+
return target == values;
|
|
81
|
+
}
|
|
82
|
+
function isEqual(a, b) {
|
|
83
|
+
const ta = typeof a, tb = typeof b;
|
|
84
|
+
if (ta != "object" || a == null || (tb != "object" || b == null))
|
|
85
|
+
return ta == "function" && tb == "function" ? a.toString() == b.toString() : a === b;
|
|
86
|
+
const keys = Object.keys(a);
|
|
87
|
+
if (keys.length != Object.keys(b).length) return false;
|
|
88
|
+
return Object.keys(a).every((key) => isEqual(a[key], b[key]));
|
|
89
|
+
}
|
|
90
|
+
function mixin(target, constructors) {
|
|
91
|
+
constructors.forEach((c) => {
|
|
92
|
+
Object.getOwnPropertyNames(c.prototype).forEach((name) => {
|
|
93
|
+
Object.defineProperty(
|
|
94
|
+
target.prototype,
|
|
95
|
+
name,
|
|
96
|
+
Object.getOwnPropertyDescriptor(c.prototype, name) || /* @__PURE__ */ Object.create(null)
|
|
97
|
+
);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function JSONAttemptParse(json) {
|
|
102
|
+
try {
|
|
103
|
+
return JSON.parse(json);
|
|
104
|
+
} catch {
|
|
105
|
+
return json;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function JSONSanitize(obj, space) {
|
|
109
|
+
let cache = [];
|
|
110
|
+
return JSON.stringify(obj, (key, value) => {
|
|
111
|
+
if (typeof value === "object" && value !== null) {
|
|
112
|
+
if (cache.includes(value)) return;
|
|
113
|
+
cache.push(value);
|
|
114
|
+
}
|
|
115
|
+
return value;
|
|
116
|
+
}, space);
|
|
117
|
+
}
|
|
118
|
+
function addUnique(array, el) {
|
|
119
|
+
if (array.indexOf(el) === -1) array.push(el);
|
|
120
|
+
return array;
|
|
121
|
+
}
|
|
122
|
+
function arrayDiff(a, b) {
|
|
123
|
+
return makeUnique([
|
|
124
|
+
...a.filter((v1) => !b.includes((v2) => isEqual(v1, v2))),
|
|
125
|
+
...b.filter((v1) => !a.includes((v2) => isEqual(v1, v2)))
|
|
126
|
+
]);
|
|
127
|
+
}
|
|
128
|
+
function caseInsensitiveSort(prop) {
|
|
129
|
+
return function(a, b) {
|
|
130
|
+
const aVal = dotNotation(a, prop);
|
|
131
|
+
const bVal = dotNotation(b, prop);
|
|
132
|
+
if (typeof aVal !== "string" || typeof bVal !== "string") return 1;
|
|
133
|
+
return aVal.toLowerCase().localeCompare(bVal.toLowerCase());
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function findByProp(prop, value) {
|
|
137
|
+
return (v) => isEqual(dotNotation(v, prop), value);
|
|
138
|
+
}
|
|
139
|
+
function flattenArr(arr, result = []) {
|
|
140
|
+
arr.forEach((el) => Array.isArray(el) ? flattenArr(el, result) : result.push(el));
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
function sortByProp(prop, reverse = false) {
|
|
144
|
+
return function(a, b) {
|
|
145
|
+
const aVal = dotNotation(a, prop);
|
|
146
|
+
const bVal = dotNotation(b, prop);
|
|
147
|
+
if (typeof aVal == "number" && typeof bVal == "number")
|
|
148
|
+
return (reverse ? -1 : 1) * (aVal - bVal);
|
|
149
|
+
if (aVal > bVal) return reverse ? -1 : 1;
|
|
150
|
+
if (aVal < bVal) return reverse ? 1 : -1;
|
|
151
|
+
return 0;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function makeUnique(arr) {
|
|
155
|
+
for (let i = arr.length - 1; i >= 0; i--) {
|
|
156
|
+
if (arr.slice(0, i).find((n) => isEqual(n, arr[i]))) arr.splice(i, 1);
|
|
157
|
+
}
|
|
158
|
+
return arr;
|
|
159
|
+
}
|
|
160
|
+
function makeArray(value) {
|
|
161
|
+
return Array.isArray(value) ? value : [value];
|
|
162
|
+
}
|
|
163
|
+
class ASet extends Array {
|
|
164
|
+
/** Number of elements in set */
|
|
165
|
+
get size() {
|
|
166
|
+
return this.length;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Array to create set from, duplicate values will be removed
|
|
170
|
+
* @param {T[]} elements Elements which will be added to set
|
|
171
|
+
*/
|
|
172
|
+
constructor(elements = []) {
|
|
173
|
+
super();
|
|
174
|
+
if (!!(elements == null ? void 0 : elements["forEach"]))
|
|
175
|
+
elements.forEach((el) => this.add(el));
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Add elements to set if unique
|
|
179
|
+
* @param items
|
|
180
|
+
*/
|
|
181
|
+
add(...items) {
|
|
182
|
+
items.filter((el) => !this.has(el)).forEach((el) => this.push(el));
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Delete elements from set
|
|
187
|
+
* @param items Elements that will be deleted
|
|
188
|
+
*/
|
|
189
|
+
delete(...items) {
|
|
190
|
+
items.forEach((el) => {
|
|
191
|
+
const index = this.indexOf(el);
|
|
192
|
+
if (index != -1) this.splice(index, 1);
|
|
193
|
+
});
|
|
194
|
+
return this;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Create list of elements this set has which the comparison set does not
|
|
198
|
+
* @param {ASet<T>} set Set to compare against
|
|
199
|
+
* @return {ASet<T>} Different elements
|
|
200
|
+
*/
|
|
201
|
+
difference(set) {
|
|
202
|
+
return new ASet(this.filter((el) => !set.has(el)));
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Check if set includes element
|
|
206
|
+
* @param {T} el Element to look for
|
|
207
|
+
* @return {boolean} True if element was found, false otherwise
|
|
208
|
+
*/
|
|
209
|
+
has(el) {
|
|
210
|
+
return this.indexOf(el) != -1;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
|
|
214
|
+
*
|
|
215
|
+
* @param {T} search Element to find
|
|
216
|
+
* @param {number} fromIndex Starting index position
|
|
217
|
+
* @return {number} Element index number or -1 if missing
|
|
218
|
+
*/
|
|
219
|
+
indexOf(search, fromIndex) {
|
|
220
|
+
return super.findIndex((el) => isEqual(el, search), fromIndex);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Create list of elements this set has in common with the comparison set
|
|
224
|
+
* @param {ASet<T>} set Set to compare against
|
|
225
|
+
* @return {boolean} Set of common elements
|
|
226
|
+
*/
|
|
227
|
+
intersection(set) {
|
|
228
|
+
return new ASet(this.filter((el) => set.has(el)));
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Check if this set has no elements in common with the comparison set
|
|
232
|
+
* @param {ASet<T>} set Set to compare against
|
|
233
|
+
* @return {boolean} True if nothing in common, false otherwise
|
|
234
|
+
*/
|
|
235
|
+
isDisjointFrom(set) {
|
|
236
|
+
return this.intersection(set).size == 0;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Check if all elements in this set are included in the comparison set
|
|
240
|
+
* @param {ASet<T>} set Set to compare against
|
|
241
|
+
* @return {boolean} True if all elements are included, false otherwise
|
|
242
|
+
*/
|
|
243
|
+
isSubsetOf(set) {
|
|
244
|
+
return this.findIndex((el) => !set.has(el)) == -1;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Check if all elements from comparison set are included in this set
|
|
248
|
+
* @param {ASet<T>} set Set to compare against
|
|
249
|
+
* @return {boolean} True if all elements are included, false otherwise
|
|
250
|
+
*/
|
|
251
|
+
isSuperset(set) {
|
|
252
|
+
return set.findIndex((el) => !this.has(el)) == -1;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Create list of elements that are only in one set but not both (XOR)
|
|
256
|
+
* @param {ASet<T>} set Set to compare against
|
|
257
|
+
* @return {ASet<T>} New set of unique elements
|
|
258
|
+
*/
|
|
259
|
+
symmetricDifference(set) {
|
|
260
|
+
return new ASet([...this.difference(set), ...set.difference(this)]);
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Create joined list of elements included in this & the comparison set
|
|
264
|
+
* @param {ASet<T>} set Set join
|
|
265
|
+
* @return {ASet<T>} New set of both previous sets combined
|
|
266
|
+
*/
|
|
267
|
+
union(set) {
|
|
268
|
+
return new ASet([...this, ...set]);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
class Cache {
|
|
272
|
+
/**
|
|
273
|
+
* Create new cache
|
|
274
|
+
*
|
|
275
|
+
* @param {keyof T} key Default property to use as primary key
|
|
276
|
+
* @param options
|
|
277
|
+
*/
|
|
278
|
+
constructor(key, options = {}) {
|
|
279
|
+
__publicField(this, "store", {});
|
|
280
|
+
/** Whether cache is complete */
|
|
281
|
+
__publicField(this, "complete", false);
|
|
282
|
+
/**
|
|
283
|
+
* Get all cached items
|
|
284
|
+
*
|
|
285
|
+
* @return {T[]} Array of items
|
|
286
|
+
*/
|
|
287
|
+
__publicField(this, "values", this.all());
|
|
288
|
+
this.key = key;
|
|
289
|
+
this.options = options;
|
|
290
|
+
if (options.storageKey && !options.storage && typeof Storage !== "undefined")
|
|
291
|
+
options.storage = localStorage;
|
|
292
|
+
if (options.storageKey && options.storage) {
|
|
293
|
+
const stored = options.storage.getItem(options.storageKey);
|
|
294
|
+
if (stored) {
|
|
295
|
+
try {
|
|
296
|
+
Object.assign(this.store, JSON.parse(stored));
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return new Proxy(this, {
|
|
302
|
+
get: (target, prop) => {
|
|
303
|
+
if (prop in target) return target[prop];
|
|
304
|
+
return target.store[prop];
|
|
305
|
+
},
|
|
306
|
+
set: (target, prop, value) => {
|
|
307
|
+
if (prop in target) target[prop] = value;
|
|
308
|
+
else target.store[prop] = value;
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
getKey(value) {
|
|
314
|
+
if (!this.key) throw new Error("No key defined");
|
|
315
|
+
return value[this.key];
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Get all cached items
|
|
319
|
+
*
|
|
320
|
+
* @return {T[]} Array of items
|
|
321
|
+
*/
|
|
322
|
+
all() {
|
|
323
|
+
return Object.values(this.store);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Add a new item to the cache. Like set, but finds key automatically
|
|
327
|
+
*
|
|
328
|
+
* @param {T} value Item to add to cache
|
|
329
|
+
* @param {number | undefined} ttl Override default expiry
|
|
330
|
+
* @return {this}
|
|
331
|
+
*/
|
|
332
|
+
add(value, ttl = this.ttl) {
|
|
333
|
+
const key = this.getKey(value);
|
|
334
|
+
this.set(key, value, ttl);
|
|
335
|
+
return this;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Add several rows to the cache
|
|
339
|
+
*
|
|
340
|
+
* @param {T[]} rows Several items that will be cached using the default key
|
|
341
|
+
* @param complete Mark cache as complete & reliable, defaults to true
|
|
342
|
+
* @return {this}
|
|
343
|
+
*/
|
|
344
|
+
addAll(rows, complete = true) {
|
|
345
|
+
rows.forEach((r) => this.add(r));
|
|
346
|
+
this.complete = complete;
|
|
347
|
+
return this;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Remove all keys from cache
|
|
351
|
+
*/
|
|
352
|
+
clear() {
|
|
353
|
+
this.store = {};
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Delete an item from the cache
|
|
357
|
+
*
|
|
358
|
+
* @param {K} key Item's primary key
|
|
359
|
+
*/
|
|
360
|
+
delete(key) {
|
|
361
|
+
delete this.store[key];
|
|
362
|
+
if (this.options.storageKey && this.options.storage)
|
|
363
|
+
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Return cache as an array of key-value pairs
|
|
367
|
+
* @return {[K, T][]} Key-value pairs array
|
|
368
|
+
*/
|
|
369
|
+
entries() {
|
|
370
|
+
return Object.entries(this.store);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Get item from the cache
|
|
374
|
+
* @param {K} key Key to lookup
|
|
375
|
+
* @return {T} Cached item
|
|
376
|
+
*/
|
|
377
|
+
get(key) {
|
|
378
|
+
return this.store[key];
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Get a list of cached keys
|
|
382
|
+
*
|
|
383
|
+
* @return {K[]} Array of keys
|
|
384
|
+
*/
|
|
385
|
+
keys() {
|
|
386
|
+
return Object.keys(this.store);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Get map of cached items
|
|
390
|
+
*
|
|
391
|
+
* @return {Record<K, T>}
|
|
392
|
+
*/
|
|
393
|
+
map() {
|
|
394
|
+
return structuredClone(this.store);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Add an item to the cache manually specifying the key
|
|
398
|
+
*
|
|
399
|
+
* @param {K} key Key item will be cached under
|
|
400
|
+
* @param {T} value Item to cache
|
|
401
|
+
* @param {number | undefined} ttl Override default expiry in seconds
|
|
402
|
+
* @return {this}
|
|
403
|
+
*/
|
|
404
|
+
set(key, value, ttl = this.options.ttl) {
|
|
405
|
+
this.store[key] = value;
|
|
406
|
+
if (this.options.storageKey && this.options.storage)
|
|
407
|
+
this.options.storage.setItem(this.options.storageKey, JSON.stringify(this.store));
|
|
408
|
+
if (ttl) setTimeout(() => {
|
|
409
|
+
this.complete = false;
|
|
410
|
+
this.delete(key);
|
|
411
|
+
}, ttl * 1e3);
|
|
412
|
+
return this;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function csv(target, flatten = true) {
|
|
416
|
+
const headers = target.reduce((acc, row) => {
|
|
417
|
+
Object.keys(flatten ? flattenObj(row) : row).forEach((key) => {
|
|
418
|
+
if (!acc.includes(key)) acc.push(key);
|
|
419
|
+
});
|
|
420
|
+
return acc;
|
|
421
|
+
}, []);
|
|
422
|
+
return [
|
|
423
|
+
headers.join(","),
|
|
424
|
+
...target.map((row) => headers.map((h) => {
|
|
425
|
+
const value = dotNotation(row, h);
|
|
426
|
+
const type = typeof value;
|
|
427
|
+
if (type == "string" && value.includes(",")) return `"${value}"`;
|
|
428
|
+
if (type == "object") return `"${JSON.stringify(value)}"`;
|
|
429
|
+
return value;
|
|
430
|
+
}).join(","))
|
|
431
|
+
].join("\n");
|
|
432
|
+
}
|
|
433
|
+
class PromiseProgress extends Promise {
|
|
434
|
+
constructor(executor) {
|
|
435
|
+
super((resolve, reject) => executor(
|
|
436
|
+
(value) => resolve(value),
|
|
437
|
+
(reason) => reject(reason),
|
|
438
|
+
(progress) => this.progress = progress
|
|
439
|
+
));
|
|
440
|
+
__publicField(this, "listeners", []);
|
|
441
|
+
__publicField(this, "_progress", 0);
|
|
442
|
+
}
|
|
443
|
+
get progress() {
|
|
444
|
+
return this._progress;
|
|
445
|
+
}
|
|
446
|
+
set progress(p) {
|
|
447
|
+
if (p == this._progress) return;
|
|
448
|
+
this._progress = p;
|
|
449
|
+
this.listeners.forEach((l) => l(p));
|
|
450
|
+
}
|
|
451
|
+
static from(promise) {
|
|
452
|
+
if (promise instanceof PromiseProgress) return promise;
|
|
453
|
+
return new PromiseProgress((res, rej) => promise.then((...args) => res(...args)).catch((...args) => rej(...args)));
|
|
454
|
+
}
|
|
455
|
+
from(promise) {
|
|
456
|
+
const newPromise = PromiseProgress.from(promise);
|
|
457
|
+
this.onProgress((p) => newPromise.progress = p);
|
|
458
|
+
return newPromise;
|
|
459
|
+
}
|
|
460
|
+
onProgress(callback) {
|
|
461
|
+
this.listeners.push(callback);
|
|
462
|
+
return this;
|
|
463
|
+
}
|
|
464
|
+
then(res, rej) {
|
|
465
|
+
const resp = super.then(res, rej);
|
|
466
|
+
return this.from(resp);
|
|
467
|
+
}
|
|
468
|
+
catch(rej) {
|
|
469
|
+
return this.from(super.catch(rej));
|
|
470
|
+
}
|
|
471
|
+
finally(res) {
|
|
472
|
+
return this.from(super.finally(res));
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
function downloadFile(blob, name) {
|
|
476
|
+
if (!(blob instanceof Blob)) blob = new Blob(makeArray(blob));
|
|
477
|
+
const url = URL.createObjectURL(blob);
|
|
478
|
+
downloadUrl(url, name);
|
|
479
|
+
URL.revokeObjectURL(url);
|
|
480
|
+
}
|
|
481
|
+
function downloadUrl(href, name) {
|
|
482
|
+
const a = document.createElement("a");
|
|
483
|
+
a.href = href;
|
|
484
|
+
a.download = name || href.split("/").pop();
|
|
485
|
+
document.body.appendChild(a);
|
|
486
|
+
a.click();
|
|
487
|
+
document.body.removeChild(a);
|
|
488
|
+
}
|
|
489
|
+
function fileBrowser(options = {}) {
|
|
490
|
+
return new Promise((res) => {
|
|
491
|
+
const input = document.createElement("input");
|
|
492
|
+
input.type = "file";
|
|
493
|
+
input.accept = options.accept || "*";
|
|
494
|
+
input.style.display = "none";
|
|
495
|
+
input.multiple = !!options.multiple;
|
|
496
|
+
input.onblur = input.onchange = async () => {
|
|
497
|
+
res(Array.from(input.files));
|
|
498
|
+
input.remove();
|
|
499
|
+
};
|
|
500
|
+
document.body.appendChild(input);
|
|
501
|
+
input.click();
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
function timestampFilename(name, date = /* @__PURE__ */ new Date()) {
|
|
505
|
+
if (typeof date == "number" || typeof date == "string") date = new Date(date);
|
|
506
|
+
const timestamp = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}_${date.getHours().toString().padStart(2, "0")}-${date.getMinutes().toString().padStart(2, "0")}-${date.getSeconds().toString().padStart(2, "0")}`;
|
|
507
|
+
return name ? name.replace("{{TIMESTAMP}}", timestamp) : timestamp;
|
|
508
|
+
}
|
|
509
|
+
function uploadWithProgress(options) {
|
|
510
|
+
return new PromiseProgress((res, rej, prog) => {
|
|
511
|
+
const xhr = new XMLHttpRequest();
|
|
512
|
+
const formData2 = new FormData();
|
|
513
|
+
options.files.forEach((f) => formData2.append("file", f));
|
|
514
|
+
xhr.withCredentials = !!options.withCredentials;
|
|
515
|
+
xhr.upload.addEventListener("progress", (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
|
|
516
|
+
xhr.addEventListener("loadend", () => res(JSONAttemptParse(xhr.responseText)));
|
|
517
|
+
xhr.addEventListener("error", () => rej(JSONAttemptParse(xhr.responseText)));
|
|
518
|
+
xhr.addEventListener("timeout", () => rej({ error: "Request timed out" }));
|
|
519
|
+
xhr.open("POST", options.url);
|
|
520
|
+
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
|
|
521
|
+
xhr.send(formData2);
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
class TypedEmitter {
|
|
525
|
+
constructor() {
|
|
526
|
+
__publicField(this, "listeners", {});
|
|
527
|
+
}
|
|
528
|
+
static emit(event, ...args) {
|
|
529
|
+
(this.listeners["*"] || []).forEach((l) => l(event, ...args));
|
|
530
|
+
(this.listeners[event.toString()] || []).forEach((l) => l(...args));
|
|
531
|
+
}
|
|
532
|
+
static off(event, listener) {
|
|
533
|
+
const e = event.toString();
|
|
534
|
+
this.listeners[e] = (this.listeners[e] || []).filter((l) => l === listener);
|
|
535
|
+
}
|
|
536
|
+
static on(event, listener) {
|
|
537
|
+
var _a;
|
|
538
|
+
const e = event.toString();
|
|
539
|
+
if (!this.listeners[e]) this.listeners[e] = [];
|
|
540
|
+
(_a = this.listeners[e]) == null ? void 0 : _a.push(listener);
|
|
541
|
+
return () => this.off(event, listener);
|
|
542
|
+
}
|
|
543
|
+
static once(event, listener) {
|
|
544
|
+
return new Promise((res) => {
|
|
545
|
+
const unsubscribe = this.on(event, (...args) => {
|
|
546
|
+
res(args.length == 1 ? args[0] : args);
|
|
547
|
+
if (listener) listener(...args);
|
|
548
|
+
unsubscribe();
|
|
549
|
+
});
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
emit(event, ...args) {
|
|
553
|
+
(this.listeners["*"] || []).forEach((l) => l(event, ...args));
|
|
554
|
+
(this.listeners[event] || []).forEach((l) => l(...args));
|
|
555
|
+
}
|
|
556
|
+
off(event, listener) {
|
|
557
|
+
this.listeners[event] = (this.listeners[event] || []).filter((l) => l === listener);
|
|
558
|
+
}
|
|
559
|
+
on(event, listener) {
|
|
560
|
+
var _a;
|
|
561
|
+
if (!this.listeners[event]) this.listeners[event] = [];
|
|
562
|
+
(_a = this.listeners[event]) == null ? void 0 : _a.push(listener);
|
|
563
|
+
return () => this.off(event, listener);
|
|
564
|
+
}
|
|
565
|
+
once(event, listener) {
|
|
566
|
+
return new Promise((res) => {
|
|
567
|
+
const unsubscribe = this.on(event, (...args) => {
|
|
568
|
+
res(args.length == 1 ? args[0] : args);
|
|
569
|
+
if (listener) listener(...args);
|
|
570
|
+
unsubscribe();
|
|
571
|
+
});
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
__publicField(TypedEmitter, "listeners", {});
|
|
576
|
+
class CustomError extends Error {
|
|
577
|
+
constructor(message, code) {
|
|
578
|
+
super(message);
|
|
579
|
+
__publicField(this, "_code");
|
|
580
|
+
if (code != null) this._code = code;
|
|
581
|
+
}
|
|
582
|
+
get code() {
|
|
583
|
+
return this._code || this.constructor.code;
|
|
584
|
+
}
|
|
585
|
+
set code(c) {
|
|
586
|
+
this._code = c;
|
|
587
|
+
}
|
|
588
|
+
static from(err) {
|
|
589
|
+
const code = Number(err.statusCode) ?? Number(err.code);
|
|
590
|
+
const newErr = new this(err.message || err.toString());
|
|
591
|
+
return Object.assign(newErr, {
|
|
592
|
+
stack: err.stack,
|
|
593
|
+
...err,
|
|
594
|
+
code: code ?? void 0
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
static instanceof(err) {
|
|
598
|
+
return err.constructor.code != void 0;
|
|
599
|
+
}
|
|
600
|
+
toString() {
|
|
601
|
+
return this.message || super.toString();
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
__publicField(CustomError, "code", 500);
|
|
605
|
+
class BadRequestError extends CustomError {
|
|
606
|
+
constructor(message = "Bad Request") {
|
|
607
|
+
super(message);
|
|
608
|
+
}
|
|
609
|
+
static instanceof(err) {
|
|
610
|
+
return err.constructor.code == this.code;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
__publicField(BadRequestError, "code", 400);
|
|
614
|
+
class UnauthorizedError extends CustomError {
|
|
615
|
+
constructor(message = "Unauthorized") {
|
|
616
|
+
super(message);
|
|
617
|
+
}
|
|
618
|
+
static instanceof(err) {
|
|
619
|
+
return err.constructor.code == this.code;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
__publicField(UnauthorizedError, "code", 401);
|
|
623
|
+
class PaymentRequiredError extends CustomError {
|
|
624
|
+
constructor(message = "Payment Required") {
|
|
625
|
+
super(message);
|
|
626
|
+
}
|
|
627
|
+
static instanceof(err) {
|
|
628
|
+
return err.constructor.code == this.code;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
__publicField(PaymentRequiredError, "code", 402);
|
|
632
|
+
class ForbiddenError extends CustomError {
|
|
633
|
+
constructor(message = "Forbidden") {
|
|
634
|
+
super(message);
|
|
635
|
+
}
|
|
636
|
+
static instanceof(err) {
|
|
637
|
+
return err.constructor.code == this.code;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
__publicField(ForbiddenError, "code", 403);
|
|
641
|
+
class NotFoundError extends CustomError {
|
|
642
|
+
constructor(message = "Not Found") {
|
|
643
|
+
super(message);
|
|
644
|
+
}
|
|
645
|
+
static instanceof(err) {
|
|
646
|
+
return err.constructor.code == this.code;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
__publicField(NotFoundError, "code", 404);
|
|
650
|
+
class MethodNotAllowedError extends CustomError {
|
|
651
|
+
constructor(message = "Method Not Allowed") {
|
|
652
|
+
super(message);
|
|
653
|
+
}
|
|
654
|
+
static instanceof(err) {
|
|
655
|
+
return err.constructor.code == this.code;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
__publicField(MethodNotAllowedError, "code", 405);
|
|
659
|
+
class NotAcceptableError extends CustomError {
|
|
660
|
+
constructor(message = "Not Acceptable") {
|
|
661
|
+
super(message);
|
|
662
|
+
}
|
|
663
|
+
static instanceof(err) {
|
|
664
|
+
return err.constructor.code == this.code;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
__publicField(NotAcceptableError, "code", 406);
|
|
668
|
+
class InternalServerError extends CustomError {
|
|
669
|
+
constructor(message = "Internal Server Error") {
|
|
670
|
+
super(message);
|
|
671
|
+
}
|
|
672
|
+
static instanceof(err) {
|
|
673
|
+
return err.constructor.code == this.code;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
__publicField(InternalServerError, "code", 500);
|
|
677
|
+
class NotImplementedError extends CustomError {
|
|
678
|
+
constructor(message = "Not Implemented") {
|
|
679
|
+
super(message);
|
|
680
|
+
}
|
|
681
|
+
static instanceof(err) {
|
|
682
|
+
return err.constructor.code == this.code;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
__publicField(NotImplementedError, "code", 501);
|
|
686
|
+
class BadGatewayError extends CustomError {
|
|
687
|
+
constructor(message = "Bad Gateway") {
|
|
688
|
+
super(message);
|
|
689
|
+
}
|
|
690
|
+
static instanceof(err) {
|
|
691
|
+
return err.constructor.code == this.code;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
__publicField(BadGatewayError, "code", 502);
|
|
695
|
+
class ServiceUnavailableError extends CustomError {
|
|
696
|
+
constructor(message = "Service Unavailable") {
|
|
697
|
+
super(message);
|
|
698
|
+
}
|
|
699
|
+
static instanceof(err) {
|
|
700
|
+
return err.constructor.code == this.code;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
__publicField(ServiceUnavailableError, "code", 503);
|
|
704
|
+
class GatewayTimeoutError extends CustomError {
|
|
705
|
+
constructor(message = "Gateway Timeout") {
|
|
706
|
+
super(message);
|
|
707
|
+
}
|
|
708
|
+
static instanceof(err) {
|
|
709
|
+
return err.constructor.code == this.code;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
__publicField(GatewayTimeoutError, "code", 504);
|
|
713
|
+
function errorFromCode(code, message) {
|
|
714
|
+
if (code >= 200 && code < 300) return null;
|
|
715
|
+
switch (code) {
|
|
716
|
+
case 400:
|
|
717
|
+
return new BadRequestError(message);
|
|
718
|
+
case 401:
|
|
719
|
+
return new UnauthorizedError(message);
|
|
720
|
+
case 402:
|
|
721
|
+
return new PaymentRequiredError(message);
|
|
722
|
+
case 403:
|
|
723
|
+
return new ForbiddenError(message);
|
|
724
|
+
case 404:
|
|
725
|
+
return new NotFoundError(message);
|
|
726
|
+
case 405:
|
|
727
|
+
return new MethodNotAllowedError(message);
|
|
728
|
+
case 406:
|
|
729
|
+
return new NotAcceptableError(message);
|
|
730
|
+
case 500:
|
|
731
|
+
return new InternalServerError(message);
|
|
732
|
+
case 501:
|
|
733
|
+
return new NotImplementedError(message);
|
|
734
|
+
case 502:
|
|
735
|
+
return new BadGatewayError(message);
|
|
736
|
+
case 503:
|
|
737
|
+
return new ServiceUnavailableError(message);
|
|
738
|
+
case 504:
|
|
739
|
+
return new GatewayTimeoutError(message);
|
|
740
|
+
default:
|
|
741
|
+
return new CustomError(message, code);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
const _Http = class _Http {
|
|
745
|
+
constructor(defaults = {}) {
|
|
746
|
+
__publicField(this, "interceptors", {});
|
|
747
|
+
__publicField(this, "headers", {});
|
|
748
|
+
__publicField(this, "url");
|
|
749
|
+
this.url = defaults.url ?? null;
|
|
750
|
+
this.headers = defaults.headers || {};
|
|
751
|
+
if (defaults.interceptors) {
|
|
752
|
+
defaults.interceptors.forEach((i) => _Http.addInterceptor(i));
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
static addInterceptor(fn) {
|
|
756
|
+
const key = Object.keys(_Http.interceptors).length.toString();
|
|
757
|
+
_Http.interceptors[key] = fn;
|
|
758
|
+
return () => {
|
|
759
|
+
_Http.interceptors[key] = null;
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
addInterceptor(fn) {
|
|
763
|
+
const key = Object.keys(this.interceptors).length.toString();
|
|
764
|
+
this.interceptors[key] = fn;
|
|
765
|
+
return () => {
|
|
766
|
+
this.interceptors[key] = null;
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
request(opts = {}) {
|
|
770
|
+
var _a;
|
|
771
|
+
if (!this.url && !opts.url) throw new Error("URL needs to be set");
|
|
772
|
+
let url = (((_a = opts.url) == null ? void 0 : _a.startsWith("http")) ? opts.url : (this.url || "") + (opts.url || "")).replace(/([^:]\/)\/+/g, "$1");
|
|
773
|
+
if (opts.fragment) url.includes("#") ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += "#" + opts.fragment;
|
|
774
|
+
if (opts.query) {
|
|
775
|
+
const q = Array.isArray(opts.query) ? opts.query : Object.keys(opts.query).map((k) => ({ key: k, value: opts.query[k] }));
|
|
776
|
+
url += (url.includes("?") ? "&" : "?") + q.map((q2) => `${q2.key}=${q2.value}`).join("&");
|
|
777
|
+
}
|
|
778
|
+
const headers = clean({
|
|
779
|
+
"Content-Type": !opts.body ? void 0 : opts.body instanceof FormData ? "multipart/form-data" : "application/json",
|
|
780
|
+
..._Http.headers,
|
|
781
|
+
...this.headers,
|
|
782
|
+
...opts.headers
|
|
783
|
+
});
|
|
784
|
+
if (typeof opts.body == "object" && opts.body != null && headers["Content-Type"] == "application/json")
|
|
785
|
+
opts.body = JSON.stringify(opts.body);
|
|
786
|
+
return new PromiseProgress((res, rej, prog) => {
|
|
787
|
+
try {
|
|
788
|
+
fetch(url, {
|
|
789
|
+
headers,
|
|
790
|
+
method: opts.method || (opts.body ? "POST" : "GET"),
|
|
791
|
+
body: opts.body
|
|
792
|
+
}).then(async (resp) => {
|
|
793
|
+
var _a2, _b;
|
|
794
|
+
for (let fn of [...Object.values(_Http.interceptors), ...Object.values(this.interceptors)]) {
|
|
795
|
+
await new Promise((res2) => fn(resp, () => res2()));
|
|
796
|
+
}
|
|
797
|
+
const contentLength = resp.headers.get("Content-Length");
|
|
798
|
+
const total = contentLength ? parseInt(contentLength, 10) : 0;
|
|
799
|
+
let loaded = 0;
|
|
800
|
+
const reader = (_a2 = resp.body) == null ? void 0 : _a2.getReader();
|
|
801
|
+
const stream = new ReadableStream({
|
|
802
|
+
start(controller) {
|
|
803
|
+
function push() {
|
|
804
|
+
reader == null ? void 0 : reader.read().then((event) => {
|
|
805
|
+
if (event.done) return controller.close();
|
|
806
|
+
loaded += event.value.byteLength;
|
|
807
|
+
prog(loaded / total);
|
|
808
|
+
controller.enqueue(event.value);
|
|
809
|
+
push();
|
|
810
|
+
}).catch((error) => controller.error(error));
|
|
811
|
+
}
|
|
812
|
+
push();
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
resp.data = new Response(stream);
|
|
816
|
+
if (opts.decode == null || opts.decode) {
|
|
817
|
+
const content = (_b = resp.headers.get("Content-Type")) == null ? void 0 : _b.toLowerCase();
|
|
818
|
+
if (content == null ? void 0 : content.includes("form")) resp.data = await resp.data.formData();
|
|
819
|
+
else if (content == null ? void 0 : content.includes("json")) resp.data = await resp.data.json();
|
|
820
|
+
else if (content == null ? void 0 : content.includes("text")) resp.data = await resp.data.text();
|
|
821
|
+
else if (content == null ? void 0 : content.includes("application")) resp.data = await resp.data.blob();
|
|
822
|
+
}
|
|
823
|
+
if (resp.ok) res(resp);
|
|
824
|
+
else rej(resp);
|
|
825
|
+
}).catch((err) => rej(err));
|
|
826
|
+
} catch (err) {
|
|
827
|
+
rej(err);
|
|
828
|
+
}
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
__publicField(_Http, "interceptors", {});
|
|
833
|
+
__publicField(_Http, "headers", {});
|
|
834
|
+
let Http = _Http;
|
|
835
|
+
function jwtDecode(token) {
|
|
836
|
+
const base64 = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
837
|
+
return JSONAttemptParse(decodeURIComponent(atob(base64).split("").map(function(c) {
|
|
838
|
+
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
|
|
839
|
+
}).join("")));
|
|
840
|
+
}
|
|
841
|
+
const CliEffects = {
|
|
842
|
+
CLEAR: "\x1B[0m",
|
|
843
|
+
BRIGHT: "\x1B[1m",
|
|
844
|
+
DIM: "\x1B[2m",
|
|
845
|
+
UNDERSCORE: "\x1B[4m",
|
|
846
|
+
BLINK: "\x1B[5m",
|
|
847
|
+
REVERSE: "\x1B[7m",
|
|
848
|
+
HIDDEN: "\x1B[8m"
|
|
849
|
+
};
|
|
850
|
+
const CliForeground = {
|
|
851
|
+
BLACK: "\x1B[30m",
|
|
852
|
+
RED: "\x1B[31m",
|
|
853
|
+
GREEN: "\x1B[32m",
|
|
854
|
+
YELLOW: "\x1B[33m",
|
|
855
|
+
BLUE: "\x1B[34m",
|
|
856
|
+
MAGENTA: "\x1B[35m",
|
|
857
|
+
CYAN: "\x1B[36m",
|
|
858
|
+
LIGHT_GREY: "\x1B[37m",
|
|
859
|
+
GREY: "\x1B[90m",
|
|
860
|
+
LIGHT_RED: "\x1B[91m",
|
|
861
|
+
LIGHT_GREEN: "\x1B[92m",
|
|
862
|
+
LIGHT_YELLOW: "\x1B[93m",
|
|
863
|
+
LIGHT_BLUE: "\x1B[94m",
|
|
864
|
+
LIGHT_MAGENTA: "\x1B[95m",
|
|
865
|
+
LIGHT_CYAN: "\x1B[96m",
|
|
866
|
+
WHITE: "\x1B[97m"
|
|
867
|
+
};
|
|
868
|
+
const CliBackground = {
|
|
869
|
+
BLACK: "\x1B[40m",
|
|
870
|
+
RED: "\x1B[41m",
|
|
871
|
+
GREEN: "\x1B[42m",
|
|
872
|
+
YELLOW: "\x1B[43m",
|
|
873
|
+
BLUE: "\x1B[44m",
|
|
874
|
+
MAGENTA: "\x1B[45m",
|
|
875
|
+
CYAN: "\x1B[46m",
|
|
876
|
+
WHITE: "\x1B[47m",
|
|
877
|
+
GREY: "\x1B[100m"
|
|
878
|
+
};
|
|
879
|
+
var LOG_LEVEL = /* @__PURE__ */ ((LOG_LEVEL2) => {
|
|
880
|
+
LOG_LEVEL2[LOG_LEVEL2["ERROR"] = 0] = "ERROR";
|
|
881
|
+
LOG_LEVEL2[LOG_LEVEL2["WARN"] = 1] = "WARN";
|
|
882
|
+
LOG_LEVEL2[LOG_LEVEL2["INFO"] = 2] = "INFO";
|
|
883
|
+
LOG_LEVEL2[LOG_LEVEL2["LOG"] = 3] = "LOG";
|
|
884
|
+
LOG_LEVEL2[LOG_LEVEL2["DEBUG"] = 4] = "DEBUG";
|
|
885
|
+
return LOG_LEVEL2;
|
|
886
|
+
})(LOG_LEVEL || {});
|
|
887
|
+
const _Logger = class _Logger extends TypedEmitter {
|
|
888
|
+
constructor(namespace) {
|
|
889
|
+
super();
|
|
890
|
+
this.namespace = namespace;
|
|
891
|
+
}
|
|
892
|
+
format(...text) {
|
|
893
|
+
const now = /* @__PURE__ */ new Date();
|
|
894
|
+
const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padEnd(3, "0")}`;
|
|
895
|
+
return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ""} ${text.map((t) => typeof t == "string" ? t : JSONSanitize(t, 2)).join(" ")}`;
|
|
896
|
+
}
|
|
897
|
+
debug(...args) {
|
|
898
|
+
if (_Logger.LOG_LEVEL < 4) return;
|
|
899
|
+
const str = this.format(...args);
|
|
900
|
+
_Logger.emit(4, str);
|
|
901
|
+
console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
|
|
902
|
+
}
|
|
903
|
+
log(...args) {
|
|
904
|
+
if (_Logger.LOG_LEVEL < 3) return;
|
|
905
|
+
const str = this.format(...args);
|
|
906
|
+
_Logger.emit(3, str);
|
|
907
|
+
console.log(CliEffects.CLEAR + str);
|
|
908
|
+
}
|
|
909
|
+
info(...args) {
|
|
910
|
+
if (_Logger.LOG_LEVEL < 2) return;
|
|
911
|
+
const str = this.format(...args);
|
|
912
|
+
_Logger.emit(2, str);
|
|
913
|
+
console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
|
|
914
|
+
}
|
|
915
|
+
warn(...args) {
|
|
916
|
+
if (_Logger.LOG_LEVEL < 1) return;
|
|
917
|
+
const str = this.format(...args);
|
|
918
|
+
_Logger.emit(1, str);
|
|
919
|
+
console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
|
|
920
|
+
}
|
|
921
|
+
error(...args) {
|
|
922
|
+
if (_Logger.LOG_LEVEL < 0) return;
|
|
923
|
+
const str = this.format(...args);
|
|
924
|
+
_Logger.emit(0, str);
|
|
925
|
+
console.error(CliForeground.RED + str + CliEffects.CLEAR);
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
__publicField(_Logger, "LOG_LEVEL", 4);
|
|
929
|
+
let Logger = _Logger;
|
|
930
|
+
function dec2Frac(num) {
|
|
931
|
+
const gcd = (a, b) => {
|
|
932
|
+
if (b < 1e-7) return a;
|
|
933
|
+
return gcd(b, ~~(a % b));
|
|
934
|
+
};
|
|
935
|
+
const len = num.toString().length - 2;
|
|
936
|
+
let denominator = Math.pow(10, len);
|
|
937
|
+
let numerator = num * denominator;
|
|
938
|
+
const divisor = gcd(numerator, denominator);
|
|
939
|
+
numerator = ~~(numerator / divisor);
|
|
940
|
+
denominator = ~~(denominator / divisor);
|
|
941
|
+
const remainder = ~~(numerator / denominator);
|
|
942
|
+
numerator -= remainder * denominator;
|
|
943
|
+
return `${remainder ? remainder + " " : ""}${~~numerator}/${~~denominator}`;
|
|
944
|
+
}
|
|
945
|
+
function fracToDec(frac) {
|
|
946
|
+
let split = frac.split(" ");
|
|
947
|
+
const whole = split.length == 2 ? Number(split[0]) : 0;
|
|
948
|
+
split = split.pop().split("/");
|
|
949
|
+
return whole + Number(split[0]) / Number(split[1]);
|
|
950
|
+
}
|
|
951
|
+
const LETTER_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
952
|
+
const NUMBER_LIST = "0123456789";
|
|
953
|
+
const SYMBOL_LIST = "~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/";
|
|
954
|
+
const CHAR_LIST = LETTER_LIST + NUMBER_LIST + SYMBOL_LIST;
|
|
955
|
+
function formatBytes(bytes, decimals = 2) {
|
|
956
|
+
if (bytes === 0) return "0 Bytes";
|
|
957
|
+
const k = 1024;
|
|
958
|
+
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
|
|
959
|
+
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
960
|
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i];
|
|
961
|
+
}
|
|
962
|
+
function formatPhoneNumber(number) {
|
|
963
|
+
const parts = /(\+?1)?.*?(\d{3}).*?(\d{3}).*?(\d{4})/g.exec(number);
|
|
964
|
+
if (!parts) throw new Error(`Number cannot be parsed: ${number}`);
|
|
965
|
+
return `${parts[1] ?? ""} (${parts[2]}) ${parts[3]}-${parts[4]}`.trim();
|
|
966
|
+
}
|
|
967
|
+
function insertAt(target, str, index) {
|
|
968
|
+
return `${target.slice(0, index)}${str}${target.slice(index + 1)}`;
|
|
969
|
+
}
|
|
970
|
+
function pad(text, length, char = " ", start = true) {
|
|
971
|
+
if (start) return text.toString().padStart(length, char);
|
|
972
|
+
return text.toString().padEnd(length, char);
|
|
973
|
+
}
|
|
974
|
+
function randomHex(length) {
|
|
975
|
+
return Array(length).fill(null).map(() => Math.round(Math.random() * 15).toString(16)).join("");
|
|
976
|
+
}
|
|
977
|
+
function randomString(length, pool = CHAR_LIST) {
|
|
978
|
+
return Array(length).fill(null).map(() => {
|
|
979
|
+
const n = ~~(Math.random() * pool.length);
|
|
980
|
+
return pool[n];
|
|
981
|
+
}).join("");
|
|
982
|
+
}
|
|
983
|
+
function randomStringBuilder(length, letters = false, numbers = false, symbols = false) {
|
|
984
|
+
if (!letters && !numbers && !symbols) throw new Error("Must enable at least one: letters, numbers, symbols");
|
|
985
|
+
return Array(length).fill(null).map(() => {
|
|
986
|
+
let c;
|
|
987
|
+
do {
|
|
988
|
+
const type = ~~(Math.random() * 3);
|
|
989
|
+
if (letters && type == 0) {
|
|
990
|
+
c = LETTER_LIST[~~(Math.random() * LETTER_LIST.length)];
|
|
991
|
+
} else if (numbers && type == 1) {
|
|
992
|
+
c = NUMBER_LIST[~~(Math.random() * NUMBER_LIST.length)];
|
|
993
|
+
} else if (symbols && type == 2) {
|
|
994
|
+
c = SYMBOL_LIST[~~(Math.random() * SYMBOL_LIST.length)];
|
|
995
|
+
}
|
|
996
|
+
} while (!c);
|
|
997
|
+
return c;
|
|
998
|
+
}).join("");
|
|
999
|
+
}
|
|
1000
|
+
function matchAll(value, regex) {
|
|
1001
|
+
if (typeof regex === "string") {
|
|
1002
|
+
regex = new RegExp(regex, "g");
|
|
1003
|
+
}
|
|
1004
|
+
if (!regex.global) {
|
|
1005
|
+
throw new TypeError("Regular expression must be global.");
|
|
1006
|
+
}
|
|
1007
|
+
let ret = [];
|
|
1008
|
+
let match;
|
|
1009
|
+
while ((match = regex.exec(value)) !== null) {
|
|
1010
|
+
ret.push(match);
|
|
1011
|
+
}
|
|
1012
|
+
return ret;
|
|
1013
|
+
}
|
|
1014
|
+
function parseUrl(url) {
|
|
1015
|
+
const processed = new RegExp(
|
|
1016
|
+
"(?:(?<protocol>[\\w\\d]+)\\:\\/\\/)?(?:(?<user>.+)\\@)?(?<host>(?<domain>[^:\\/\\?#@\\n]+)(?:\\:(?<port>\\d*))?)(?<path>\\/.*?)?(?:\\?(?<query>.*?))?(?:#(?<fragment>.*?))?$",
|
|
1017
|
+
"gm"
|
|
1018
|
+
).exec(url);
|
|
1019
|
+
const groups = (processed == null ? void 0 : processed.groups) ?? {};
|
|
1020
|
+
const domains = groups.domain.split(".");
|
|
1021
|
+
if (groups["port"] != null) groups.port = Number(groups.port);
|
|
1022
|
+
if (domains.length > 2) {
|
|
1023
|
+
groups.domain = domains.splice(-2, 2).join(".");
|
|
1024
|
+
groups.subdomain = domains.join(".");
|
|
1025
|
+
}
|
|
1026
|
+
if (groups.query) {
|
|
1027
|
+
const split = groups.query.split("&"), query = {};
|
|
1028
|
+
split.forEach((q) => {
|
|
1029
|
+
const [key, val] = q.split("=");
|
|
1030
|
+
query[key] = val;
|
|
1031
|
+
});
|
|
1032
|
+
groups.query = query;
|
|
1033
|
+
}
|
|
1034
|
+
return groups;
|
|
1035
|
+
}
|
|
1036
|
+
function md5(d) {
|
|
1037
|
+
var r = M(V(Y(X(d), 8 * d.length)));
|
|
1038
|
+
return r.toLowerCase();
|
|
1039
|
+
}
|
|
1040
|
+
function M(d) {
|
|
1041
|
+
for (var _, m = "0123456789ABCDEF", f = "", r = 0; r < d.length; r++) _ = d.charCodeAt(r), f += m.charAt(_ >>> 4 & 15) + m.charAt(15 & _);
|
|
1042
|
+
return f;
|
|
1043
|
+
}
|
|
1044
|
+
function X(d) {
|
|
1045
|
+
for (var _ = Array(d.length >> 2), m = 0; m < _.length; m++) _[m] = 0;
|
|
1046
|
+
for (m = 0; m < 8 * d.length; m += 8) _[m >> 5] |= (255 & d.charCodeAt(m / 8)) << m % 32;
|
|
1047
|
+
return _;
|
|
1048
|
+
}
|
|
1049
|
+
function V(d) {
|
|
1050
|
+
for (var _ = "", m = 0; m < 32 * d.length; m += 8) _ += String.fromCharCode(d[m >> 5] >>> m % 32 & 255);
|
|
1051
|
+
return _;
|
|
1052
|
+
}
|
|
1053
|
+
function Y(d, _) {
|
|
1054
|
+
d[_ >> 5] |= 128 << _ % 32, d[14 + (_ + 64 >>> 9 << 4)] = _;
|
|
1055
|
+
for (var m = 1732584193, f = -271733879, r = -1732584194, i = 271733878, n = 0; n < d.length; n += 16) {
|
|
1056
|
+
var h = m, t = f, g = r, e = i;
|
|
1057
|
+
f = md5_ii(f = md5_ii(f = md5_ii(f = md5_ii(f = md5_hh(f = md5_hh(f = md5_hh(f = md5_hh(f = md5_gg(f = md5_gg(f = md5_gg(f = md5_gg(f = md5_ff(f = md5_ff(f = md5_ff(f = md5_ff(f, r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 0], 7, -680876936), f, r, d[n + 1], 12, -389564586), m, f, d[n + 2], 17, 606105819), i, m, d[n + 3], 22, -1044525330), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 4], 7, -176418897), f, r, d[n + 5], 12, 1200080426), m, f, d[n + 6], 17, -1473231341), i, m, d[n + 7], 22, -45705983), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 8], 7, 1770035416), f, r, d[n + 9], 12, -1958414417), m, f, d[n + 10], 17, -42063), i, m, d[n + 11], 22, -1990404162), r = md5_ff(r, i = md5_ff(i, m = md5_ff(m, f, r, i, d[n + 12], 7, 1804603682), f, r, d[n + 13], 12, -40341101), m, f, d[n + 14], 17, -1502002290), i, m, d[n + 15], 22, 1236535329), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 1], 5, -165796510), f, r, d[n + 6], 9, -1069501632), m, f, d[n + 11], 14, 643717713), i, m, d[n + 0], 20, -373897302), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 5], 5, -701558691), f, r, d[n + 10], 9, 38016083), m, f, d[n + 15], 14, -660478335), i, m, d[n + 4], 20, -405537848), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 9], 5, 568446438), f, r, d[n + 14], 9, -1019803690), m, f, d[n + 3], 14, -187363961), i, m, d[n + 8], 20, 1163531501), r = md5_gg(r, i = md5_gg(i, m = md5_gg(m, f, r, i, d[n + 13], 5, -1444681467), f, r, d[n + 2], 9, -51403784), m, f, d[n + 7], 14, 1735328473), i, m, d[n + 12], 20, -1926607734), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 5], 4, -378558), f, r, d[n + 8], 11, -2022574463), m, f, d[n + 11], 16, 1839030562), i, m, d[n + 14], 23, -35309556), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 1], 4, -1530992060), f, r, d[n + 4], 11, 1272893353), m, f, d[n + 7], 16, -155497632), i, m, d[n + 10], 23, -1094730640), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 13], 4, 681279174), f, r, d[n + 0], 11, -358537222), m, f, d[n + 3], 16, -722521979), i, m, d[n + 6], 23, 76029189), r = md5_hh(r, i = md5_hh(i, m = md5_hh(m, f, r, i, d[n + 9], 4, -640364487), f, r, d[n + 12], 11, -421815835), m, f, d[n + 15], 16, 530742520), i, m, d[n + 2], 23, -995338651), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 0], 6, -198630844), f, r, d[n + 7], 10, 1126891415), m, f, d[n + 14], 15, -1416354905), i, m, d[n + 5], 21, -57434055), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 12], 6, 1700485571), f, r, d[n + 3], 10, -1894986606), m, f, d[n + 10], 15, -1051523), i, m, d[n + 1], 21, -2054922799), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 8], 6, 1873313359), f, r, d[n + 15], 10, -30611744), m, f, d[n + 6], 15, -1560198380), i, m, d[n + 13], 21, 1309151649), r = md5_ii(r, i = md5_ii(i, m = md5_ii(m, f, r, i, d[n + 4], 6, -145523070), f, r, d[n + 11], 10, -1120210379), m, f, d[n + 2], 15, 718787259), i, m, d[n + 9], 21, -343485551), m = safe_add(m, h), f = safe_add(f, t), r = safe_add(r, g), i = safe_add(i, e);
|
|
1058
|
+
}
|
|
1059
|
+
return Array(m, f, r, i);
|
|
1060
|
+
}
|
|
1061
|
+
function md5_cmn(d, _, m, f, r, i) {
|
|
1062
|
+
return safe_add(bit_rol(safe_add(safe_add(_, d), safe_add(f, i)), r), m);
|
|
1063
|
+
}
|
|
1064
|
+
function md5_ff(d, _, m, f, r, i, n) {
|
|
1065
|
+
return md5_cmn(_ & m | ~_ & f, d, _, r, i, n);
|
|
1066
|
+
}
|
|
1067
|
+
function md5_gg(d, _, m, f, r, i, n) {
|
|
1068
|
+
return md5_cmn(_ & f | m & ~f, d, _, r, i, n);
|
|
1069
|
+
}
|
|
1070
|
+
function md5_hh(d, _, m, f, r, i, n) {
|
|
1071
|
+
return md5_cmn(_ ^ m ^ f, d, _, r, i, n);
|
|
1072
|
+
}
|
|
1073
|
+
function md5_ii(d, _, m, f, r, i, n) {
|
|
1074
|
+
return md5_cmn(m ^ (_ | ~f), d, _, r, i, n);
|
|
1075
|
+
}
|
|
1076
|
+
function safe_add(d, _) {
|
|
1077
|
+
var m = (65535 & d) + (65535 & _);
|
|
1078
|
+
return (d >> 16) + (_ >> 16) + (m >> 16) << 16 | 65535 & m;
|
|
1079
|
+
}
|
|
1080
|
+
function bit_rol(d, _) {
|
|
1081
|
+
return d << _ | d >>> 32 - _;
|
|
1082
|
+
}
|
|
1083
|
+
function validateEmail(email) {
|
|
1084
|
+
return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email);
|
|
1085
|
+
}
|
|
1086
|
+
function gravatar(email, def = "mp") {
|
|
1087
|
+
if (!email) return "";
|
|
1088
|
+
return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
|
|
1089
|
+
}
|
|
1090
|
+
function escapeRegex(value) {
|
|
1091
|
+
return value.replace(/[.*+?^${}()|\[\]\\]/g, "\\$&");
|
|
1092
|
+
}
|
|
1093
|
+
function PE(str, ...args) {
|
|
1094
|
+
const combined = [];
|
|
1095
|
+
for (let i = 0; i < str.length || i < args.length; i++) {
|
|
1096
|
+
if (str[i]) combined.push(str[i]);
|
|
1097
|
+
if (args[i]) combined.push(args[i]);
|
|
1098
|
+
}
|
|
1099
|
+
return new PathEvent(combined.join(""));
|
|
1100
|
+
}
|
|
1101
|
+
function PES(str, ...args) {
|
|
1102
|
+
let combined = [];
|
|
1103
|
+
for (let i = 0; i < str.length || i < args.length; i++) {
|
|
1104
|
+
if (str[i]) combined.push(str[i]);
|
|
1105
|
+
if (args[i]) combined.push(args[i]);
|
|
1106
|
+
}
|
|
1107
|
+
const [paths, methods] = combined.join("").split(":");
|
|
1108
|
+
return PathEvent.toString(paths, methods == null ? void 0 : methods.split(""));
|
|
1109
|
+
}
|
|
1110
|
+
class PathError extends Error {
|
|
1111
|
+
}
|
|
1112
|
+
class PathEvent {
|
|
1113
|
+
constructor(Event) {
|
|
1114
|
+
/** First directory in path */
|
|
1115
|
+
__publicField(this, "module");
|
|
1116
|
+
/** Entire path, including the module & name */
|
|
1117
|
+
__publicField(this, "fullPath");
|
|
1118
|
+
/** Path including the name, excluding the module */
|
|
1119
|
+
__publicField(this, "path");
|
|
1120
|
+
/** Last sagment of path */
|
|
1121
|
+
__publicField(this, "name");
|
|
1122
|
+
/** List of methods */
|
|
1123
|
+
__publicField(this, "methods");
|
|
1124
|
+
var _a;
|
|
1125
|
+
if (typeof Event == "object") return Object.assign(this, Event);
|
|
1126
|
+
let [p, scope, method] = Event.split(":");
|
|
1127
|
+
if (!method) method = scope || "*";
|
|
1128
|
+
if (p == "*" || !p && method == "*") {
|
|
1129
|
+
p = "";
|
|
1130
|
+
method = "*";
|
|
1131
|
+
}
|
|
1132
|
+
let temp = p.split("/").filter((p2) => !!p2);
|
|
1133
|
+
this.module = ((_a = temp.splice(0, 1)[0]) == null ? void 0 : _a.toLowerCase()) || "";
|
|
1134
|
+
this.fullPath = p;
|
|
1135
|
+
this.path = temp.join("/");
|
|
1136
|
+
this.name = temp.pop() || "";
|
|
1137
|
+
this.methods = new ASet(method.split(""));
|
|
1138
|
+
}
|
|
1139
|
+
/** All/Wildcard specified */
|
|
1140
|
+
get all() {
|
|
1141
|
+
return this.methods.has("*");
|
|
1142
|
+
}
|
|
1143
|
+
set all(v) {
|
|
1144
|
+
v ? new ASet(["*"]) : this.methods.delete("*");
|
|
1145
|
+
}
|
|
1146
|
+
/** None specified */
|
|
1147
|
+
get none() {
|
|
1148
|
+
return this.methods.has("n");
|
|
1149
|
+
}
|
|
1150
|
+
set none(v) {
|
|
1151
|
+
v ? this.methods = new ASet(["n"]) : this.methods.delete("n");
|
|
1152
|
+
}
|
|
1153
|
+
/** Create method specified */
|
|
1154
|
+
get create() {
|
|
1155
|
+
return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("c"));
|
|
1156
|
+
}
|
|
1157
|
+
set create(v) {
|
|
1158
|
+
v ? this.methods.delete("n").add("c") : this.methods.delete("c");
|
|
1159
|
+
}
|
|
1160
|
+
/** Read method specified */
|
|
1161
|
+
get read() {
|
|
1162
|
+
return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("r"));
|
|
1163
|
+
}
|
|
1164
|
+
set read(v) {
|
|
1165
|
+
v ? this.methods.delete("n").add("r") : this.methods.delete("r");
|
|
1166
|
+
}
|
|
1167
|
+
/** Update method specified */
|
|
1168
|
+
get update() {
|
|
1169
|
+
return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("u"));
|
|
1170
|
+
}
|
|
1171
|
+
set update(v) {
|
|
1172
|
+
v ? this.methods.delete("n").add("u") : this.methods.delete("u");
|
|
1173
|
+
}
|
|
1174
|
+
/** Delete method specified */
|
|
1175
|
+
get delete() {
|
|
1176
|
+
return !this.methods.has("n") && (this.methods.has("*") || this.methods.has("d"));
|
|
1177
|
+
}
|
|
1178
|
+
set delete(v) {
|
|
1179
|
+
v ? this.methods.delete("n").add("d") : this.methods.delete("d");
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
|
|
1183
|
+
* combined until a "none" is reached
|
|
1184
|
+
*
|
|
1185
|
+
* @param {string | PathEvent} paths Events as strings or pre-parsed
|
|
1186
|
+
* @return {PathEvent} Final combined permission
|
|
1187
|
+
*/
|
|
1188
|
+
static combine(...paths) {
|
|
1189
|
+
let hitNone = false;
|
|
1190
|
+
const combined = paths.map((p) => new PathEvent(p)).toSorted((p1, p2) => {
|
|
1191
|
+
const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
|
|
1192
|
+
return l1 < l2 ? 1 : l1 > l2 ? -1 : 0;
|
|
1193
|
+
}).reduce((acc, p) => {
|
|
1194
|
+
if (p.none) hitNone = true;
|
|
1195
|
+
if (!acc) return p;
|
|
1196
|
+
if (hitNone) return acc;
|
|
1197
|
+
acc.methods = [...acc.methods, ...p.methods];
|
|
1198
|
+
return acc;
|
|
1199
|
+
}, null);
|
|
1200
|
+
combined.methods = new ASet(combined.methods);
|
|
1201
|
+
return combined;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Filter a set of paths based on the target
|
|
1205
|
+
*
|
|
1206
|
+
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
|
|
1207
|
+
* @param filter {...PathEvent} Must container one of
|
|
1208
|
+
* @return {boolean} Whether there is any overlap
|
|
1209
|
+
*/
|
|
1210
|
+
static filter(target, ...filter) {
|
|
1211
|
+
const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
|
|
1212
|
+
const parsedFind = makeArray(filter).map((pe) => new PathEvent(pe));
|
|
1213
|
+
return parsedTarget.filter((t) => {
|
|
1214
|
+
if (!t.fullPath && t.all) return true;
|
|
1215
|
+
return !!parsedFind.find((f) => t.fullPath.startsWith(f.fullPath) && (f.all || t.all || t.methods.intersection(f.methods).length));
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* Squash 2 sets of paths & return true if any overlap is found
|
|
1220
|
+
*
|
|
1221
|
+
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
|
|
1222
|
+
* @param has Target must have at least one of these path
|
|
1223
|
+
* @return {boolean} Whether there is any overlap
|
|
1224
|
+
*/
|
|
1225
|
+
static has(target, ...has) {
|
|
1226
|
+
const parsedRequired = makeArray(has).map((pe) => new PathEvent(pe));
|
|
1227
|
+
const parsedTarget = makeArray(target).map((pe) => new PathEvent(pe));
|
|
1228
|
+
return !!parsedRequired.find((r) => {
|
|
1229
|
+
if (!r.fullPath && r.all) return true;
|
|
1230
|
+
const filtered = parsedTarget.filter((p) => r.fullPath.startsWith(p.fullPath));
|
|
1231
|
+
if (!filtered.length) return false;
|
|
1232
|
+
const combined = PathEvent.combine(...filtered);
|
|
1233
|
+
return !combined.none && (combined.all || new ASet(combined.methods).intersection(new ASet(r.methods)).length);
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Squash 2 sets of paths & return true if the target has all paths
|
|
1238
|
+
*
|
|
1239
|
+
* @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
|
|
1240
|
+
* @param has Target must have all these paths
|
|
1241
|
+
* @return {boolean} Whether there is any overlap
|
|
1242
|
+
*/
|
|
1243
|
+
static hasAll(target, ...has) {
|
|
1244
|
+
return has.filter((h) => PathEvent.has(target, h)).length == has.length;
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Same as `has` but raises an error if there is no overlap
|
|
1248
|
+
*
|
|
1249
|
+
* @param {string | string[]} target Array of Events as strings or pre-parsed
|
|
1250
|
+
* @param has Target must have at least one of these path
|
|
1251
|
+
*/
|
|
1252
|
+
static hasFatal(target, ...has) {
|
|
1253
|
+
if (!PathEvent.has(target, ...has)) throw new PathError(`Requires one of: ${makeArray(has).join(", ")}`);
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* Same as `hasAll` but raises an error if the target is missing any paths
|
|
1257
|
+
*
|
|
1258
|
+
* @param {string | string[]} target Array of Events as strings or pre-parsed
|
|
1259
|
+
* @param has Target must have all these paths
|
|
1260
|
+
*/
|
|
1261
|
+
static hasAllFatal(target, ...has) {
|
|
1262
|
+
if (!PathEvent.hasAll(target, ...has)) throw new PathError(`Requires all: ${makeArray(has).join(", ")}`);
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Create event string from its components
|
|
1266
|
+
*
|
|
1267
|
+
* @param {string | string[]} path Event path
|
|
1268
|
+
* @param {Method} methods Event method
|
|
1269
|
+
* @return {string} String representation of Event
|
|
1270
|
+
*/
|
|
1271
|
+
static toString(path, methods) {
|
|
1272
|
+
let p = makeArray(path).filter((p2) => p2 != null).join("/");
|
|
1273
|
+
p = p == null ? void 0 : p.trim().replaceAll(/\/{2,}/g, "/").replaceAll(/(^\/|\/$)/g, "");
|
|
1274
|
+
if (methods == null ? void 0 : methods.length) p += `:${makeArray(methods).map((m) => m.toLowerCase()).join("")}`;
|
|
1275
|
+
return p;
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Filter a set of paths based on this event
|
|
1279
|
+
*
|
|
1280
|
+
* @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
|
|
1281
|
+
* @return {boolean} Whether there is any overlap
|
|
1282
|
+
*/
|
|
1283
|
+
filter(target) {
|
|
1284
|
+
return PathEvent.filter(target, this);
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* Create event string from its components
|
|
1288
|
+
*
|
|
1289
|
+
* @return {string} String representation of Event
|
|
1290
|
+
*/
|
|
1291
|
+
toString() {
|
|
1292
|
+
return PathEvent.toString(this.fullPath, this.methods);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
class PathEventEmitter {
|
|
1296
|
+
constructor() {
|
|
1297
|
+
__publicField(this, "listeners", []);
|
|
1298
|
+
}
|
|
1299
|
+
emit(event, ...args) {
|
|
1300
|
+
const parsed = new PathEvent(event);
|
|
1301
|
+
this.listeners.filter((l) => PathEvent.has(l[0], event)).forEach(async (l) => l[1](parsed, ...args));
|
|
1302
|
+
}
|
|
1303
|
+
off(listener) {
|
|
1304
|
+
this.listeners = this.listeners.filter((l) => l[1] != listener);
|
|
1305
|
+
}
|
|
1306
|
+
on(event, listener) {
|
|
1307
|
+
makeArray(event).forEach((e) => this.listeners.push([new PathEvent(e), listener]));
|
|
1308
|
+
return () => this.off(listener);
|
|
1309
|
+
}
|
|
1310
|
+
once(event, listener) {
|
|
1311
|
+
return new Promise((res) => {
|
|
1312
|
+
const unsubscribe = this.on(event, (event2, ...args) => {
|
|
1313
|
+
res(args.length < 2 ? args[0] : args);
|
|
1314
|
+
if (listener) listener(event2, ...args);
|
|
1315
|
+
unsubscribe();
|
|
1316
|
+
});
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
relayEvents(emitter) {
|
|
1320
|
+
emitter.on("*", (event, ...args) => this.emit(event, ...args));
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
function formatDate(date) {
|
|
1324
|
+
if (typeof date == "number" || typeof date == "string") date = new Date(date);
|
|
1325
|
+
let hours = date.getHours(), postfix = "AM";
|
|
1326
|
+
if (hours >= 12) {
|
|
1327
|
+
if (hours > 12) hours -= 12;
|
|
1328
|
+
postfix = "PM";
|
|
1329
|
+
} else if (hours == 0) hours = 12;
|
|
1330
|
+
return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}, ${hours}:${date.getMinutes().toString().padStart(2, "0")} ${postfix}`;
|
|
1331
|
+
}
|
|
1332
|
+
function sleep(ms) {
|
|
1333
|
+
return new Promise((res) => setTimeout(res, ms));
|
|
1334
|
+
}
|
|
1335
|
+
async function sleepWhile(fn, checkInterval = 100) {
|
|
1336
|
+
while (await fn()) await sleep(checkInterval);
|
|
1337
|
+
}
|
|
1338
|
+
function timeUntil(date) {
|
|
1339
|
+
return (date instanceof Date ? date.getTime() : date) - (/* @__PURE__ */ new Date()).getTime();
|
|
1340
|
+
}
|
|
1341
|
+
function tyoeKeys() {
|
|
1342
|
+
return Object.keys({});
|
|
1343
|
+
}
|
|
1344
|
+
exports2.ASet = ASet;
|
|
1345
|
+
exports2.BadGatewayError = BadGatewayError;
|
|
1346
|
+
exports2.BadRequestError = BadRequestError;
|
|
1347
|
+
exports2.Cache = Cache;
|
|
1348
|
+
exports2.CliBackground = CliBackground;
|
|
1349
|
+
exports2.CliEffects = CliEffects;
|
|
1350
|
+
exports2.CliForeground = CliForeground;
|
|
1351
|
+
exports2.CustomError = CustomError;
|
|
1352
|
+
exports2.ForbiddenError = ForbiddenError;
|
|
1353
|
+
exports2.GatewayTimeoutError = GatewayTimeoutError;
|
|
1354
|
+
exports2.Http = Http;
|
|
1355
|
+
exports2.InternalServerError = InternalServerError;
|
|
1356
|
+
exports2.JSONAttemptParse = JSONAttemptParse;
|
|
1357
|
+
exports2.JSONSanitize = JSONSanitize;
|
|
1358
|
+
exports2.LOG_LEVEL = LOG_LEVEL;
|
|
1359
|
+
exports2.Logger = Logger;
|
|
1360
|
+
exports2.MethodNotAllowedError = MethodNotAllowedError;
|
|
1361
|
+
exports2.NotAcceptableError = NotAcceptableError;
|
|
1362
|
+
exports2.NotFoundError = NotFoundError;
|
|
1363
|
+
exports2.NotImplementedError = NotImplementedError;
|
|
1364
|
+
exports2.PE = PE;
|
|
1365
|
+
exports2.PES = PES;
|
|
1366
|
+
exports2.PathError = PathError;
|
|
1367
|
+
exports2.PathEvent = PathEvent;
|
|
1368
|
+
exports2.PathEventEmitter = PathEventEmitter;
|
|
1369
|
+
exports2.PaymentRequiredError = PaymentRequiredError;
|
|
1370
|
+
exports2.PromiseProgress = PromiseProgress;
|
|
1371
|
+
exports2.ServiceUnavailableError = ServiceUnavailableError;
|
|
1372
|
+
exports2.TypedEmitter = TypedEmitter;
|
|
1373
|
+
exports2.UnauthorizedError = UnauthorizedError;
|
|
1374
|
+
exports2.addUnique = addUnique;
|
|
1375
|
+
exports2.arrayDiff = arrayDiff;
|
|
1376
|
+
exports2.caseInsensitiveSort = caseInsensitiveSort;
|
|
1377
|
+
exports2.clean = clean;
|
|
1378
|
+
exports2.csv = csv;
|
|
1379
|
+
exports2.dec2Frac = dec2Frac;
|
|
1380
|
+
exports2.deepCopy = deepCopy;
|
|
1381
|
+
exports2.deepMerge = deepMerge;
|
|
1382
|
+
exports2.dotNotation = dotNotation;
|
|
1383
|
+
exports2.downloadFile = downloadFile;
|
|
1384
|
+
exports2.downloadUrl = downloadUrl;
|
|
1385
|
+
exports2.encodeQuery = encodeQuery;
|
|
1386
|
+
exports2.errorFromCode = errorFromCode;
|
|
1387
|
+
exports2.escapeRegex = escapeRegex;
|
|
1388
|
+
exports2.fileBrowser = fileBrowser;
|
|
1389
|
+
exports2.findByProp = findByProp;
|
|
1390
|
+
exports2.flattenArr = flattenArr;
|
|
1391
|
+
exports2.flattenObj = flattenObj;
|
|
1392
|
+
exports2.formData = formData;
|
|
1393
|
+
exports2.formatBytes = formatBytes;
|
|
1394
|
+
exports2.formatDate = formatDate;
|
|
1395
|
+
exports2.formatPhoneNumber = formatPhoneNumber;
|
|
1396
|
+
exports2.fracToDec = fracToDec;
|
|
1397
|
+
exports2.gravatar = gravatar;
|
|
1398
|
+
exports2.includes = includes;
|
|
1399
|
+
exports2.insertAt = insertAt;
|
|
1400
|
+
exports2.isEqual = isEqual;
|
|
1401
|
+
exports2.jwtDecode = jwtDecode;
|
|
1402
|
+
exports2.makeArray = makeArray;
|
|
1403
|
+
exports2.makeUnique = makeUnique;
|
|
1404
|
+
exports2.matchAll = matchAll;
|
|
1405
|
+
exports2.md5 = md5;
|
|
1406
|
+
exports2.mixin = mixin;
|
|
1407
|
+
exports2.pad = pad;
|
|
1408
|
+
exports2.parseUrl = parseUrl;
|
|
1409
|
+
exports2.randomHex = randomHex;
|
|
1410
|
+
exports2.randomString = randomString;
|
|
1411
|
+
exports2.randomStringBuilder = randomStringBuilder;
|
|
1412
|
+
exports2.sleep = sleep;
|
|
1413
|
+
exports2.sleepWhile = sleepWhile;
|
|
1414
|
+
exports2.sortByProp = sortByProp;
|
|
1415
|
+
exports2.timeUntil = timeUntil;
|
|
1416
|
+
exports2.timestampFilename = timestampFilename;
|
|
1417
|
+
exports2.tyoeKeys = tyoeKeys;
|
|
1418
|
+
exports2.uploadWithProgress = uploadWithProgress;
|
|
1419
|
+
exports2.validateEmail = validateEmail;
|
|
1420
|
+
Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
|
|
1421
|
+
});
|
|
3
1422
|
//# sourceMappingURL=index.cjs.map
|