UNPKG

funtool

Version:

A modern, efficient, and modular JavaScript utility library designed to enhance developer productivity.

3 lines (2 loc) 10 kB
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).funtool={})}(this,(function(e){"use strict";class n{constructor(e,t){if(e){if(!n.isValid(e))throw new Error("Invalid ObjectId hex string.");this.hex=e.toLowerCase()}else this.hex=function(e=Math.random){return(Math.floor(Date.now()/1e3).toString(16).padStart(8,"0")+Array.from({length:16},(()=>Math.floor(16*e()).toString(16))).join("")).slice(0,24)}(t)}static isValid(e){return"string"==typeof e&&/^[a-fA-F0-9]{24}$/.test(e)}static createFromHexString(e){return new n(e)}static createWithPrefix(e){return e+(new n).toHexString()}toHex(){return this.hex}toBuffer(){const e=new Uint8Array(12);for(let n=0;n<12;n++)e[n]=parseInt(this.hex.slice(2*n,2*n+2),16);return e}equals(e){return this.hex===e.hex}static parse(e,t=!1){if(t){if(!n.isValid(e))throw new Error(`Invalid strict ObjectId: ${e}`);return new n(e)}const r=e.match(/[a-fA-F0-9]{24}/);if(!r)throw new Error(`Invalid format for ObjectId: ${e}`);return new n(r[0])}toHexString(){return this.hex}toUUIDString(){const e=this.hex.padEnd(32,"0");return[e.slice(0,8),e.slice(8,12),e.slice(12,16),e.slice(16,20),e.slice(20)].join("-")}toString(){return this.toHexString()}toBase64(){return Buffer.from(this.toBuffer()).toString("base64")}short(e=""){return e+this.toBase64().replace(/=+$/,"")}getTimestamp(){return 1e3*parseInt(this.hex.slice(0,8),16)}compare(e){return this.hex.localeCompare(e.hex)}clone(){return new n(this.hex)}toJSON(){return this.toHexString()}}function t(e){const[n,t]=e.split(",");if(!n||!t)throw new Error("Invalid base64 format");const r=n.match(/:(.*?);/),o=r?.[1]||"application/octet-stream",i=o.split("/")[1]||"bin",a=atob(t),l=Uint8Array.from(a,(e=>e.charCodeAt(0)));return{blob:new Blob([l],{type:o}),mime:o,ext:i}}const r=[{name:"Edge (Chromium)",regex:/Edg\/([\d.]+)/},{name:"Edge (Legacy)",regex:/Edge\/([\d.]+)/},{name:"Opera",regex:/OPR\/([\d.]+)/},{name:"Vivaldi",regex:/Vivaldi\/([\d.]+)/},{name:"Chrome",regex:/Chrome\/([\d.]+)/},{name:"Firefox",regex:/Firefox\/([\d.]+)/},{name:"Safari",regex:/Version\/([\d.]+).*Safari/},{name:"Internet Explorer",regex:/MSIE ([\d.]+);/},{name:"Internet Explorer",regex:/Trident\/7.0.*rv:([\d.]+)/},{name:"Samsung Internet",regex:/SamsungBrowser\/([\d.]+)/}],o=[{name:"Windows",regex:/Windows NT ([\d.]+)/},{name:"macOS",regex:/Mac OS X ([\d_]+)/,versionReplace:/_/g},{name:"iOS",regex:/\(iP(?:hone|ad|od); CPU (?:iPhone )?OS ([\d_]+)/,versionReplace:/_/g},{name:"Android",regex:/Android ([\d.]+)/},{name:"Linux",regex:/Linux/},{name:"Chrome OS",regex:/CrOS [\w\d_]+ ([\d.]+)/},{name:"Windows Phone",regex:/Windows Phone ([\d.]+)/}],i=[{type:"Mobile",regex:/Mobile|iPhone|Android/},{type:"Tablet",regex:/Tablet|iPad/},{type:"SmartTV",regex:/SmartTV|SMART-TV|Smart-TV|NetCast.TV|AppleTV|Roku/},{type:"Console",regex:/Xbox|PlayStation/},{type:"Wearable",regex:/Watch|Wearable/}],a=[{name:"Blink",regex:/Chrome\/([\d.]+)/},{name:"WebKit",regex:/AppleWebKit\/([\d.]+)/},{name:"Gecko",regex:/Gecko\/([\d.]+)/},{name:"Trident",regex:/Trident\/([\d.]+)/},{name:"EdgeHTML",regex:/EdgeHTML\/([\d.]+)/}];function l(e){const n=e||("undefined"!=typeof navigator?navigator.userAgent:""),t={browser:{name:null,version:null,majorVersion:null},os:{name:null,version:null,majorVersion:null},device:{type:"Unknown",model:null,vendor:null},engine:{name:null,version:null},originalUA:n};for(const{name:e,regex:o}of r){const r=n.match(o);if(r){const n=r[1];t.browser={name:e,version:n,majorVersion:n?.split(".")[0]??null};break}}for(const{name:e,regex:r,versionReplace:i}of o){const o=n.match(r);if(o){let n=o[1]||null;n&&i&&(n=n.replace(i,".")),t.os={name:e,version:n,majorVersion:n?.split(".")[0]??null};break}}for(const{name:e,regex:r}of a){const o=n.match(r);if(o){t.engine={name:e,version:o[1]||null};break}}for(const{type:e,regex:r}of i)if(r.test(n)){t.device.type=e,/iPhone/.test(n)?t.device.model="iPhone":/iPad/.test(n)?t.device.model="iPad":/Android/.test(n)&&(t.device.model="Android Device");break}return"Unknown"===t.device.type&&(t.device.type="Desktop"),t}e.ObjectId=n,e.awaitTo=function(e){var n;return(null!==(n=e)&&"object"==typeof n&&"function"==typeof n.then?e:Promise.resolve(e)).then((e=>[null,e])).catch((e=>[e,void 0]))},e.base64ToBlob=t,e.base64ToFormData=function(e,n){const{blob:r,ext:o}=t(e),i=n?.key||"file";let a=n?.filename;a?a.includes(".")||(a+=`.${o}`):a=`${Date.now()}.${o}`;const l=new FormData;return l.append(i,r,a),l},e.currying=function(e){const{fn:n,done:t}=e;return function e(r=[]){const o=(...o)=>{const i=[...r,...o];return t&&t(i)?n(...i):e(i)};return o.map=n=>e(r.map(n)),o.filter=n=>e(r.filter(n)),o.value=()=>n(...r),o.valueOf=()=>o.value(),o.toString=()=>String(o.value()),o}()},e.debounce=function(e,n=500){let t=null,r=null,o=null,i=null,a=null;const l=()=>{if(r)try{const n=e.apply(o,r);return i?.(n),s(),n}catch(e){throw a?.(e),s(),e}},s=()=>{t=null,r=null,o=null,i=null,a=null};function c(...e){return t&&clearTimeout(t),r=e,o=this,new Promise(((e,r)=>{i=e,a=r,t=setTimeout((()=>{l()}),n)}))}return c.cancel=function(){t&&clearTimeout(t),a?.("Debounced call canceled"),s()},c.flush=function(){return t&&clearTimeout(t),Promise.resolve(l())},c.pending=function(){return!!t},c},e.debounceSync=function(e,n=500){let t=null,r=null,o=null;const i=()=>{t=null,r=null,o=null},a=()=>{if(r)try{const n=e.apply(o,r);return i(),n}catch(e){throw i(),e}};function l(...e){t&&clearTimeout(t),r=e,o=this,t=setTimeout((()=>{a()}),n)}return l.cancel=()=>{t&&clearTimeout(t),i()},l.flush=()=>(t&&clearTimeout(t),a()),l.pending=()=>!!t,l},e.generateVerificationCode=function(e=4,n){if(e<=0)return"";const t=/[0Ool1]/g;let r=n?.charset||"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";if(!1!==n?.excludeConfusing&&(r=r.replace(t,"")),!r)throw new Error("Character set is empty after removing confusing characters.");return Array.from({length:e},(()=>{const e=Math.floor(Math.random()*r.length);return r.charAt(e)})).join("")},e.getBrowserType=function(){const e=l();if(!e.browser.name||!e.browser.version)return null;const n=e.browser.name.toLowerCase(),t=parseInt(e.browser.majorVersion||"0");switch(n){case"internet explorer":return t>=7&&t<=10?`IE${t}`:11===t?"IE11":null;case"edge (chromium)":case"edge (legacy)":return"Edge";case"firefox":return"FireFox";case"opera":return"Opera";case"chrome":return"Chrome";case"safari":return"Safari";default:return null}},e.getUA=function(e){return void 0!==e?e:"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""},e.noop=function(){},e.parseQuery=e=>"object"!=typeof e||null==e?"":Object.keys(e).map((n=>{const t=e[n];return null==t?"":`${encodeURIComponent(n)}=${encodeURIComponent(t)}`})).filter(Boolean).join("&"),e.parseQueryDeep=e=>{const n=(e,t)=>null==e?[]:"object"!=typeof e||Array.isArray(e)?Array.isArray(e)?e.flatMap((e=>n(e,`${t}[]`))):[`${t}=${encodeURIComponent(String(e))}`]:Object.keys(e).flatMap((r=>n(e[r],`${t}[${encodeURIComponent(r)}]`)));return"object"!=typeof e||null==e?"":Object.keys(e).flatMap((t=>n(e[t],encodeURIComponent(t)))).join("&")},e.parseQueryDeepWith=(e,n)=>{const t=(e,r)=>{if(null==e)return[];if("object"==typeof e&&!Array.isArray(e))return Object.keys(e).flatMap((n=>t(e[n],[...r,n])));if(Array.isArray(e))return e.flatMap(((e,n)=>t(e,[...r,String(n)])));return[`${n(r.map(encodeURIComponent))}=${encodeURIComponent(String(e))}`]};return"object"!=typeof e||null==e?"":Object.keys(e).flatMap((n=>t(e[n],[n]))).join("&")},e.parseQueryWith=(e,n)=>"object"!=typeof e||null==e?"":Object.entries(e).map((([e,t])=>n(e,t))).filter((e=>"string"==typeof e)).join("&"),e.parseUA=l,e.randomFloat=function(e=0,n=1){return Math.random()*(n-e)+e},e.randomInt=function(e=0,n=1){return Math.floor(Math.random()*(n-e))+e},e.throttle=function(e,n=500){let t=null,r=null,o=null,i=null,a=null;const l=()=>{t=Date.now();const n=e.apply(i,o);return a?.(n),s(),n},s=()=>{r=null,o=null,i=null,a=null};function c(...e){const s=Date.now(),c=t?n-(s-t):0;return o=e,i=this,new Promise((e=>{a=e,c<=0?l():r||(r=setTimeout(l,c))}))}return c.cancel=()=>{r&&clearTimeout(r),s()},c.flush=()=>r?(clearTimeout(r),Promise.resolve(l())):Promise.resolve(void 0),c.pending=()=>Boolean(r),c},e.throttleSync=function(e,n=500){let t=null,r=null,o=null,i=null;const a=()=>{t=Date.now(),e.apply(i,o),l()},l=()=>{r=null,o=null,i=null};function s(...e){const l=Date.now(),s=t?n-(l-t):0;o=e,i=this,s<=0?a():r||(r=setTimeout(a,s))}return s.cancel=()=>{r&&clearTimeout(r),l()},s.flush=()=>{r&&(clearTimeout(r),a())},s.pending=()=>Boolean(r),s},e.urlParse=function(e){const[n,t]=e.split("#"),[r,o]=n.split("?");let i="",a="",l="/";const s=r.match(/^([a-zA-Z]+:)?\/\//);if(s){i=s[1]||"";const e=r.slice(i.length+2),n=e.indexOf("/");n>=0?(a=e.slice(0,n),l=e.slice(n)||"/"):(a=e,l="/")}else l=r||"/";let c=a,u="";const f=a.indexOf(":");f>=0&&(c=a.slice(0,f),u=a.slice(f+1));const d=i+"//"+a,m={};if(o){const e=o.split("&");for(const n of e){if(!n)continue;const[e,t]=n.split("="),r=decodeURIComponent(e||"").trim();if(!r)continue;const o=void 0!==t?decodeURIComponent(t).trim():"";let i;i=/^\d+(\.\d+)?$/.test(o)?Number(o):"true"===o||"false"!==o&&o,m.hasOwnProperty(r)?Array.isArray(m[r])?m[r].push(i):m[r]=[m[r],i]:m[r]=i}}return{host:a,hostname:c,pathname:l,port:u,protocol:i,origin:d,href:e,search:o?`?${o}`:"",hash:t?`#${decodeURIComponent(t)}`:"",query:m}},e.urlStringify=function(e){const{protocol:n="",hostname:t,port:r="",pathname:o="/",query:i={},hash:a=""}=e,l=n?n.endsWith(":")?n:`${n}:`:"",s=r?`${t}:${r}`:t,c=o.startsWith("/")?o:`/${o}`,u=Object.entries(i).flatMap((([e,n])=>{if(!e||null==n)return[];const t=e=>encodeURIComponent(String(e));return Array.isArray(n)?n.map((n=>`${encodeURIComponent(e)}=${t(n)}`)):`${encodeURIComponent(e)}=${t(n)}`})).join("&");return`${l}//${s}${c}${u?`?${u}`:""}${a?a.startsWith("#")?a:`#${a}`:""}`}})); //# sourceMappingURL=index.umd.js.map