@heimdallr-sdk/utils
Advanced tools
Comparing version 0.0.20 to 0.0.21
@@ -1,1 +0,1 @@ | ||
var HEIMDALLR_UTILS=function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;const E=e=>Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var R;(R||(R={})).NAME="@heimdallr-sdk";var a,O,c,i,C,l,S,u,T,p,I,L,d,A,U,f,x,D,N,y,g,P,h,m,H,M,F,$,w,b,B,_,j,G,k,v,K="[".concat(R.NAME,"]:");(O=a||(a={}))[O.FATAL=1]="FATAL",O[O.ERROR=2]="ERROR",O[O.WARN=3]="WARN",O[O.INFO=4]="INFO",O[O.DEBUG=5]="DEBUG",(i=c||(c={})).SESSION_ID="HEIMDALLR_SDK_SESSION_ID",i.USER_ID="HEIMDALLR_SDK_USER_ID",i.APP="HEIMDALLR_SDK_APP_ID",(l=C||(C={})).GET="GET",l.POST="POST",l.PUT="PUT",l.DELETE="DELETE",(u=S||(S={}))[u.LIFECYCLE=1]="LIFECYCLE",u[u.ERROR=2]="ERROR",u[u.PERFORMANCE=3]="PERFORMANCE",u[u.API=4]="API",u[u.DOM=5]="DOM",u[u.ROUTE=6]="ROUTE",u[u.CONSOLE=7]="CONSOLE",u[u.RECORD=8]="RECORD",u[u.VUE=9]="VUE",u[u.CUSTOMER=10]="CUSTOMER",u[u.EXTEND=11]="EXTEND",(p=T||(T={}))[p.CODEERROR=21]="CODEERROR",p[p.RESOURCEERROR=22]="RESOURCEERROR",p[p.UNHANDLEDREJECTION=23]="UNHANDLEDREJECTION",p[p.PAGECRASH=24]="PAGECRASH",(L=I||(I={}))[L.BEACON=1]="BEACON",L[L.IMG=2]="IMG",L[L.GET=3]="GET",L[L.POST=4]="POST",(A=d||(d={}))[A.CLICK=51]="CLICK",(f=U||(U={})).LOG="log",f.INFO="info",f.WARN="warn",f.ERROR="error",f.ASSERT="assert",(D=x||(x={}))[D.XHR=41]="XHR",D[D.FETCH=42]="FETCH",(y=N||(N={}))[y.FMP=31]="FMP",y[y.FPS=32]="FPS",y[y.BASIC=33]="BASIC",y[y.VITALS=34]="VITALS",y[y.RESOURCE=35]="RESOURCE",(P=g||(g={}))[P.HASH=61]="HASH",P[P.HISTORY=62]="HISTORY",(m=h||(h={}))[m.CUSTOMER=111]="CUSTOMER",(M=H||(H={})).LOCAL="local",M.SESSION="session",M.COOKIE="cookie",M.GLOBAL="global",($=F||(F={}))[$.LOAD=11]="LOAD",$[$.UNLOAD=12]="UNLOAD",(b=w||(w={}))[b.MOBILE=1]="MOBILE",b[b.PC=2]="PC",(_=B||(B={}))[_.BROWSER=1]="BROWSER",_[_.WECHAT=2]="WECHAT",_[_.NODE=3]="NODE",(G=j||(j={}))[G.ROUTE=11]="ROUTE",G[G.CLICK=12]="CLICK",G[G.CONSOLE=13]="CONSOLE",G[G.XHR=14]="XHR",G[G.FETCH=15]="FETCH",G[G.UNHANDLEDREJECTION=16]="UNHANDLEDREJECTION",G[G.RESOURCE=17]="RESOURCE",G[G.CODE_ERROR=18]="CODE_ERROR",G[G.CUSTOMER=19]="CUSTOMER",G[G.FRAMEWORK=20]="FRAMEWORK",G[G.LIFECYCLE=21]="LIFECYCLE",G[G.CRASH=22]="CRASH",(v=k||(k={}))[v.API=21]="API",v[v.ROUTE=22]="ROUTE",v[v.CLICK=23]="CLICK",v[v.ERROR=24]="ERROR",v[v.LIFECYCLE=25]="LIFECYCLE",v[v.CUSTOMER=26]="CUSTOMER";const W=e=>{let t=null;switch(e){case H.LOCAL:t=localStorage;break;case H.SESSION:t=sessionStorage}return t},J=e=>{if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""},X=(e,t,r)=>new Promise(((n,o)=>{const s=new XMLHttpRequest;s.open(e,t,!0),e===C.POST&&("string"==typeof r||r instanceof URLSearchParams?s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):s.setRequestHeader("Content-Type","application/json;charset=UTF-8")),s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE){const e=(e=>{const t={};return e.trim().split(/[\r\n]+/).forEach((e=>{const[r,n]=e.split(": ");t[r]=n})),t})(s.getAllResponseHeaders());if(s.status>=200&&s.status<300)try{const t=s.responseText?JSON.parse(s.responseText):null;n({status:s.status,statusText:s.statusText,headers:e,data:t})}catch(e){o(new Error(`Failed to parse response: ${s.responseText}`))}else o({status:s.status,statusText:s.statusText,headers:e,data:s.responseText})}},s.onerror=()=>{o(new Error("Network error"))};try{e===C.POST?"string"==typeof r||r instanceof URLSearchParams?s.send(r):s.send(JSON.stringify(r)):s.send()}catch(e){o(e)}}));return e.beacon=(e,t)=>{if(!e||"string"!=typeof e)return console.error("Invalid URL"),!1;if(!t||"object"!=typeof t)return console.error("Invalid data"),!1;const r=new FormData;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];"string"==typeof n||n instanceof Blob||(n=JSON.stringify(n)),r.append(e,n)}return navigator.sendBeacon(e,r)},e.countBytes=e=>(new TextEncoder).encode(e).length,e.delCookie=e=>{if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const r=J(e);null!=r&&(document.cookie=`${e}=${r};expires=${t.toUTCString()}`)},e.formatDecimal=(e,t)=>!isFinite(e)||isNaN(e)||!Number.isInteger(t)||t<0?e:parseFloat(e.toFixed(t)),e.formateUrlPath=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,e.generateUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),e.get=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?";return X(C.GET,`${e}${n}${r}`,null)},e.getCookie=J,e.getDeepPropByDot=(e,t)=>{if(!e||!t)return null;const E=((e,t)=>{for(var E in t||(t={}))n.call(t,E)&&s(e,E,t[E]);if(r)for(var E of r(t))o.call(t,E)&&s(e,E,t[E]);return e})({},t),R=e.split(".");let a=E;for(const e of R){const t=a[e];if(!t)return null;a=t}return a},e.getStore=(e,t,r=!0)=>{if(!e||!t)return"";const n=W(e);if(!n)return"";let o="";try{const e=t.split("."),[s]=e;o=n.getItem(s),r&&(o=JSON.parse(o),e.length>1&&(o=e.slice(1).reduce(((e,t)=>e[t]),o)))}catch(e){console.error(K,e)}return o},e.getUrlPath=e=>{try{const{pathname:t}=new URL(e);return t.endsWith("/")&&t.length>1?t.slice(0,-1):t}catch(e){return""}},e.hasConsole=()=>"undefined"!=typeof console,e.imgRequest=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?",o=`${e}${n}${r}`,s=new Image;s.src=o,setTimeout((()=>{s.src=""}),0)},e.obj2query=E,e.post=(e,t)=>X(C.POST,e,t),e.replaceOld=(e,t,r,n)=>{if(void 0!==e&&(t in e||n)){const n=r(e[t]);"function"==typeof n&&(e[t]=n)}},e.setCookie=(e,t,r)=>{if(!e||!t||!r)return;const n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${n.toUTCString()}`},e.setStore=(e,t,r)=>{if(!t)return;const n=W(e);n&&n.setItem(t,JSON.stringify(r))},e.setUrlQuery=(e,t={})=>{const r=[];return Object.keys(t).forEach((e=>{r.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${r.join("&")}`},e.splitStringByBytes=(e,t)=>{const r=(new TextEncoder).encode(e),n=new TextDecoder,o=[];let s=0;for(;s<r.length;){let e=s+t;for(;e>s&&128==(192&r[e]);)e--;o.push(n.decode(r.subarray(s,e))),s=e}return o},e.throttle=(e,t)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}},e.xhr=X,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); | ||
var HEIMDALLR_UTILS=function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;const E=e=>Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var R,a=((R=a||{}).NAME="@heimdallr-sdk",R);var O=(e=>(e[e.FATAL=1]="FATAL",e[e.ERROR=2]="ERROR",e[e.WARN=3]="WARN",e[e.INFO=4]="INFO",e[e.DEBUG=5]="DEBUG",e))(O||{}),c=(e=>(e.SESSION_ID="HEIMDALLR_SDK_SESSION_ID",e.USER_ID="HEIMDALLR_SDK_USER_ID",e.APP="HEIMDALLR_SDK_APP_ID",e))(c||{}),i=(e=>(e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE",e))(i||{}),C=(e=>(e[e.LIFECYCLE=1]="LIFECYCLE",e[e.ERROR=2]="ERROR",e[e.PERFORMANCE=3]="PERFORMANCE",e[e.API=4]="API",e[e.DOM=5]="DOM",e[e.ROUTE=6]="ROUTE",e[e.CONSOLE=7]="CONSOLE",e[e.RECORD=8]="RECORD",e[e.VUE=9]="VUE",e[e.CUSTOMER=10]="CUSTOMER",e[e.EXTEND=11]="EXTEND",e))(C||{}),l=(e=>(e[e.CODEERROR=21]="CODEERROR",e[e.RESOURCEERROR=22]="RESOURCEERROR",e[e.UNHANDLEDREJECTION=23]="UNHANDLEDREJECTION",e[e.PAGECRASH=24]="PAGECRASH",e))(l||{}),S=(e=>(e[e.BEACON=1]="BEACON",e[e.IMG=2]="IMG",e[e.GET=3]="GET",e[e.POST=4]="POST",e))(S||{}),u=(e=>(e[e.CLICK=51]="CLICK",e))(u||{}),T=(e=>(e.LOG="log",e.INFO="info",e.WARN="warn",e.ERROR="error",e.ASSERT="assert",e))(T||{}),p=(e=>(e[e.XHR=41]="XHR",e[e.FETCH=42]="FETCH",e))(p||{}),L=(e=>(e[e.FMP=31]="FMP",e[e.FPS=32]="FPS",e[e.BASIC=33]="BASIC",e[e.VITALS=34]="VITALS",e[e.RESOURCE=35]="RESOURCE",e))(L||{}),I=(e=>(e[e.HASH=61]="HASH",e[e.HISTORY=62]="HISTORY",e))(I||{}),d=(e=>(e[e.CUSTOMER=111]="CUSTOMER",e))(d||{}),A=(e=>(e.LOCAL="local",e.SESSION="session",e.COOKIE="cookie",e.GLOBAL="global",e))(A||{}),U=(e=>(e[e.LOAD=11]="LOAD",e[e.UNLOAD=12]="UNLOAD",e))(U||{}),f=(e=>(e[e.MOBILE=1]="MOBILE",e[e.PC=2]="PC",e))(f||{}),x=(e=>(e[e.BROWSER=1]="BROWSER",e[e.WECHAT=2]="WECHAT",e[e.NODE=3]="NODE",e))(x||{}),D=(e=>(e[e.ROUTE=11]="ROUTE",e[e.CLICK=12]="CLICK",e[e.CONSOLE=13]="CONSOLE",e[e.XHR=14]="XHR",e[e.FETCH=15]="FETCH",e[e.UNHANDLEDREJECTION=16]="UNHANDLEDREJECTION",e[e.RESOURCE=17]="RESOURCE",e[e.CODE_ERROR=18]="CODE_ERROR",e[e.CUSTOMER=19]="CUSTOMER",e[e.FRAMEWORK=20]="FRAMEWORK",e[e.LIFECYCLE=21]="LIFECYCLE",e[e.CRASH=22]="CRASH",e))(D||{}),N=(e=>(e[e.API=21]="API",e[e.ROUTE=22]="ROUTE",e[e.CLICK=23]="CLICK",e[e.ERROR=24]="ERROR",e[e.LIFECYCLE=25]="LIFECYCLE",e[e.CUSTOMER=26]="CUSTOMER",e))(N||{});const g=e=>{let t=null;switch(e){case A.LOCAL:t=localStorage;break;case A.SESSION:t=sessionStorage}return t},y=e=>{if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""},m=(e,t,r)=>new Promise(((n,o)=>{const s=new XMLHttpRequest;if(e===i.GET&&r){const e=new URLSearchParams(r),n=t.includes("?")?"&":"?";t+=`${n}${e.toString()}`}s.open(e,t,!0),e!==i.GET&&("string"==typeof r||r instanceof URLSearchParams?s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):s.setRequestHeader("Content-Type","application/json;charset=UTF-8")),s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE){const e=(e=>{const t={};return e.trim().split(/[\r\n]+/).forEach((e=>{const[r,n]=e.split(": ");t[r]=n})),t})(s.getAllResponseHeaders());if(s.status>=200&&s.status<300){try{const t=s.responseText?JSON.parse(s.responseText):null;n({status:s.status,statusText:s.statusText,headers:e,data:t})}catch(e){o(new Error(`Failed to parse response: ${s.responseText}`))}return}o({status:s.status,statusText:s.statusText,headers:e,data:s.responseText})}},s.onerror=()=>{o(new Error("Network error"))};try{if(e!==i.GET)return"string"==typeof r||r instanceof URLSearchParams?void s.send(r):void s.send(JSON.stringify(r));s.send()}catch(e){o(e)}}));return e.beacon=(e,t)=>{if(!e||"string"!=typeof e)return console.error("Invalid URL"),!1;if(!t||"object"!=typeof t)return console.error("Invalid data"),!1;const r=new FormData;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];"string"==typeof n||n instanceof Blob||(n=JSON.stringify(n)),r.append(e,n)}return navigator.sendBeacon(e,r)},e.countBytes=e=>(new TextEncoder).encode(e).length,e.delCookie=e=>{if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const r=y(e);null!=r&&(document.cookie=`${e}=${r};expires=${t.toUTCString()}`)},e.formatDecimal=(e,t)=>!isFinite(e)||isNaN(e)||!Number.isInteger(t)||t<0?e:parseFloat(e.toFixed(t)),e.formateUrlPath=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,e.generateUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),e.get=(e,t)=>m(i.GET,e,t),e.getCookie=y,e.getDeepPropByDot=(e,t)=>{if(!e||!t)return null;const E=((e,t)=>{for(var E in t||(t={}))n.call(t,E)&&s(e,E,t[E]);if(r)for(var E of r(t))o.call(t,E)&&s(e,E,t[E]);return e})({},t),R=e.split(".");let a=E;for(const e of R){const t=a[e];if(!t)return null;a=t}return a},e.getStore=(e,t,r=!0)=>{if(!e||!t)return"";const n=g(e);if(!n)return"";let o="";try{const e=t.split("."),[s]=e;o=n.getItem(s),r&&(o=JSON.parse(o),e.length>1&&(o=e.slice(1).reduce(((e,t)=>e[t]),o)))}catch(e){console.error("[@heimdallr-sdk]:",e)}return o},e.getUrlPath=e=>{const t=/^[a-zA-Z]+:\/\//.test(e);try{const{pathname:r}=new URL(e,t?void 0:"http://temporaryurl.com");return r.endsWith("/")&&r.length>1?r.slice(0,-1):r}catch(e){return""}},e.imgRequest=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?",o=`${e}${n}${r}`,s=new Image;s.src=o,setTimeout((()=>{s.src=""}),0)},e.obj2query=E,e.post=(e,t)=>m(i.POST,e,t),e.replaceOld=(e,t,r,n)=>{if(void 0!==e&&(t in e||n)){const n=r(e[t]);"function"==typeof n&&(e[t]=n)}},e.setCookie=(e,t,r)=>{if(!e||!t||!r)return;const n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${n.toUTCString()}`},e.setStore=(e,t,r)=>{if(!t)return;const n=g(e);n&&n.setItem(t,JSON.stringify(r))},e.setUrlQuery=(e,t={})=>{const r=[];return Object.keys(t).forEach((e=>{r.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${r.join("&")}`},e.splitStringByBytes=(e,t)=>{const r=(new TextEncoder).encode(e),n=new TextDecoder,o=[];let s=0;for(;s<r.length;){let e=s+t;for(;e>s&&128==(192&r[e]);)e--;o.push(n.decode(r.subarray(s,e))),s=e}return o},e.throttle=(e,t)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}},e.xhr=m,Object.defineProperty(e,"__esModule",{value:!0}),e}({}); |
@@ -1,457 +0,1 @@ | ||
(function (global, factory) { | ||
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.HEIMDALLR_UTILS = {})); | ||
})(this, (function (exports) { 'use strict'; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __propIsEnum = Object.prototype.propertyIsEnumerable; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
var __spreadValues = (a, b) => { | ||
for (var prop in b || (b = {})) | ||
if (__hasOwnProp.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
if (__getOwnPropSymbols) | ||
for (var prop of __getOwnPropSymbols(b)) { | ||
if (__propIsEnum.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
} | ||
return a; | ||
}; | ||
const hasConsole = () => typeof console !== "undefined"; | ||
const formateUrlPath = (host, path) => `${/^http(s|):\/\//.test(host || "") ? host : `//${(host || "").replace(/^http(s|):\/\//, "")}`}/${(path || "")[0] === "/" ? path.substring(1) : path}`; | ||
const getUrlPath = (url) => { | ||
try { | ||
const { pathname } = new URL(url); | ||
return pathname.endsWith("/") && pathname.length > 1 ? pathname.slice(0, -1) : pathname; | ||
} catch (error) { | ||
return ""; | ||
} | ||
}; | ||
const setUrlQuery = (url, query = {}) => { | ||
const queryArr = []; | ||
Object.keys(query).forEach((k) => { | ||
queryArr.push(`${k}=${query[k]}`); | ||
}); | ||
return `${url}${url.indexOf("?") !== -1 ? "&" : "?"}${queryArr.join("&")}`; | ||
}; | ||
const getDeepPropByDot = (keyPath, obj) => { | ||
if (!keyPath || !obj) { | ||
return null; | ||
} | ||
const copyTarget = __spreadValues({}, obj); | ||
const paths = keyPath.split("."); | ||
let result = copyTarget; | ||
for (const key of paths) { | ||
const value = result[key]; | ||
if (!value) { | ||
return null; | ||
} | ||
result = value; | ||
} | ||
return result; | ||
}; | ||
const obj2query = (params) => Object.keys(params).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join("&"); | ||
const generateUUID = () => { | ||
const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; | ||
return template.replace(/[xy]/g, (c) => { | ||
const r = Math.random() * 16 | 0; | ||
const v = c === "x" ? r : r & 3 | 8; | ||
return v.toString(16); | ||
}); | ||
}; | ||
const throttle = (fn, delay) => { | ||
let lastCall = 0; | ||
return function(...args) { | ||
const now = Date.now(); | ||
if (now - lastCall >= delay) { | ||
lastCall = now; | ||
fn.apply(this, args); | ||
} | ||
}; | ||
}; | ||
const replaceOld = (source, name, replacement, isForced) => { | ||
if (source === void 0) | ||
return; | ||
if (name in source || isForced) { | ||
const original = source[name]; | ||
const wrapped = replacement(original); | ||
if (typeof wrapped === "function") { | ||
source[name] = wrapped; | ||
} | ||
} | ||
}; | ||
const formatDecimal = (num, decimal) => { | ||
if (!isFinite(num) || isNaN(num)) { | ||
return num; | ||
} | ||
if (!Number.isInteger(decimal) || decimal < 0) { | ||
return num; | ||
} | ||
return parseFloat(num.toFixed(decimal)); | ||
}; | ||
const countBytes = (str) => { | ||
const encoder = new TextEncoder(); | ||
return encoder.encode(str).length; | ||
}; | ||
const splitStringByBytes = (str, maxBytes) => { | ||
const encoder = new TextEncoder(); | ||
const bytes = encoder.encode(str); | ||
const decoder = new TextDecoder(); | ||
const chunks = []; | ||
let start = 0; | ||
while (start < bytes.length) { | ||
let end = start + maxBytes; | ||
while (end > start && (bytes[end] & 192) === 128) { | ||
end--; | ||
} | ||
chunks.push(decoder.decode(bytes.subarray(start, end))); | ||
start = end; | ||
} | ||
return chunks; | ||
}; | ||
var SDK; | ||
(function(SDK2) { | ||
SDK2["NAME"] = "@heimdallr-sdk"; | ||
})(SDK || (SDK = {})); | ||
var TAG = "[".concat(SDK.NAME, "]:"); | ||
var BreadcrumbLevel; | ||
(function(BreadcrumbLevel2) { | ||
BreadcrumbLevel2[BreadcrumbLevel2["FATAL"] = 1] = "FATAL"; | ||
BreadcrumbLevel2[BreadcrumbLevel2["ERROR"] = 2] = "ERROR"; | ||
BreadcrumbLevel2[BreadcrumbLevel2["WARN"] = 3] = "WARN"; | ||
BreadcrumbLevel2[BreadcrumbLevel2["INFO"] = 4] = "INFO"; | ||
BreadcrumbLevel2[BreadcrumbLevel2["DEBUG"] = 5] = "DEBUG"; | ||
})(BreadcrumbLevel || (BreadcrumbLevel = {})); | ||
var StoreKeyType; | ||
(function(StoreKeyType2) { | ||
StoreKeyType2["SESSION_ID"] = "HEIMDALLR_SDK_SESSION_ID"; | ||
StoreKeyType2["USER_ID"] = "HEIMDALLR_SDK_USER_ID"; | ||
StoreKeyType2["APP"] = "HEIMDALLR_SDK_APP_ID"; | ||
})(StoreKeyType || (StoreKeyType = {})); | ||
var MethodTypes; | ||
(function(MethodTypes2) { | ||
MethodTypes2["GET"] = "GET"; | ||
MethodTypes2["POST"] = "POST"; | ||
MethodTypes2["PUT"] = "PUT"; | ||
MethodTypes2["DELETE"] = "DELETE"; | ||
})(MethodTypes || (MethodTypes = {})); | ||
var EventTypes; | ||
(function(EventTypes2) { | ||
EventTypes2[EventTypes2["LIFECYCLE"] = 1] = "LIFECYCLE"; | ||
EventTypes2[EventTypes2["ERROR"] = 2] = "ERROR"; | ||
EventTypes2[EventTypes2["PERFORMANCE"] = 3] = "PERFORMANCE"; | ||
EventTypes2[EventTypes2["API"] = 4] = "API"; | ||
EventTypes2[EventTypes2["DOM"] = 5] = "DOM"; | ||
EventTypes2[EventTypes2["ROUTE"] = 6] = "ROUTE"; | ||
EventTypes2[EventTypes2["CONSOLE"] = 7] = "CONSOLE"; | ||
EventTypes2[EventTypes2["RECORD"] = 8] = "RECORD"; | ||
EventTypes2[EventTypes2["VUE"] = 9] = "VUE"; | ||
EventTypes2[EventTypes2["CUSTOMER"] = 10] = "CUSTOMER"; | ||
EventTypes2[EventTypes2["EXTEND"] = 11] = "EXTEND"; | ||
})(EventTypes || (EventTypes = {})); | ||
var BrowserErrorTypes; | ||
(function(BrowserErrorTypes2) { | ||
BrowserErrorTypes2[BrowserErrorTypes2["CODEERROR"] = 21] = "CODEERROR"; | ||
BrowserErrorTypes2[BrowserErrorTypes2["RESOURCEERROR"] = 22] = "RESOURCEERROR"; | ||
BrowserErrorTypes2[BrowserErrorTypes2["UNHANDLEDREJECTION"] = 23] = "UNHANDLEDREJECTION"; | ||
BrowserErrorTypes2[BrowserErrorTypes2["PAGECRASH"] = 24] = "PAGECRASH"; | ||
})(BrowserErrorTypes || (BrowserErrorTypes = {})); | ||
var BrowserReportType; | ||
(function(BrowserReportType2) { | ||
BrowserReportType2[BrowserReportType2["BEACON"] = 1] = "BEACON"; | ||
BrowserReportType2[BrowserReportType2["IMG"] = 2] = "IMG"; | ||
BrowserReportType2[BrowserReportType2["GET"] = 3] = "GET"; | ||
BrowserReportType2[BrowserReportType2["POST"] = 4] = "POST"; | ||
})(BrowserReportType || (BrowserReportType = {})); | ||
var DomTypes; | ||
(function(DomTypes2) { | ||
DomTypes2[DomTypes2["CLICK"] = 51] = "CLICK"; | ||
})(DomTypes || (DomTypes = {})); | ||
var ConsoleTypes; | ||
(function(ConsoleTypes2) { | ||
ConsoleTypes2["LOG"] = "log"; | ||
ConsoleTypes2["INFO"] = "info"; | ||
ConsoleTypes2["WARN"] = "warn"; | ||
ConsoleTypes2["ERROR"] = "error"; | ||
ConsoleTypes2["ASSERT"] = "assert"; | ||
})(ConsoleTypes || (ConsoleTypes = {})); | ||
var HttpTypes; | ||
(function(HttpTypes2) { | ||
HttpTypes2[HttpTypes2["XHR"] = 41] = "XHR"; | ||
HttpTypes2[HttpTypes2["FETCH"] = 42] = "FETCH"; | ||
})(HttpTypes || (HttpTypes = {})); | ||
var PerTypes; | ||
(function(PerTypes2) { | ||
PerTypes2[PerTypes2["FMP"] = 31] = "FMP"; | ||
PerTypes2[PerTypes2["FPS"] = 32] = "FPS"; | ||
PerTypes2[PerTypes2["BASIC"] = 33] = "BASIC"; | ||
PerTypes2[PerTypes2["VITALS"] = 34] = "VITALS"; | ||
PerTypes2[PerTypes2["RESOURCE"] = 35] = "RESOURCE"; | ||
})(PerTypes || (PerTypes = {})); | ||
var RouteTypes; | ||
(function(RouteTypes2) { | ||
RouteTypes2[RouteTypes2["HASH"] = 61] = "HASH"; | ||
RouteTypes2[RouteTypes2["HISTORY"] = 62] = "HISTORY"; | ||
})(RouteTypes || (RouteTypes = {})); | ||
var CustomerTypes; | ||
(function(CustomerTypes2) { | ||
CustomerTypes2[CustomerTypes2["CUSTOMER"] = 111] = "CUSTOMER"; | ||
})(CustomerTypes || (CustomerTypes = {})); | ||
var StoreType; | ||
(function(StoreType2) { | ||
StoreType2["LOCAL"] = "local"; | ||
StoreType2["SESSION"] = "session"; | ||
StoreType2["COOKIE"] = "cookie"; | ||
StoreType2["GLOBAL"] = "global"; | ||
})(StoreType || (StoreType = {})); | ||
var PageLifeType; | ||
(function(PageLifeType2) { | ||
PageLifeType2[PageLifeType2["LOAD"] = 11] = "LOAD"; | ||
PageLifeType2[PageLifeType2["UNLOAD"] = 12] = "UNLOAD"; | ||
})(PageLifeType || (PageLifeType = {})); | ||
var DeviceType; | ||
(function(DeviceType2) { | ||
DeviceType2[DeviceType2["MOBILE"] = 1] = "MOBILE"; | ||
DeviceType2[DeviceType2["PC"] = 2] = "PC"; | ||
})(DeviceType || (DeviceType = {})); | ||
var PlatformTypes; | ||
(function(PlatformTypes2) { | ||
PlatformTypes2[PlatformTypes2["BROWSER"] = 1] = "BROWSER"; | ||
PlatformTypes2[PlatformTypes2["WECHAT"] = 2] = "WECHAT"; | ||
PlatformTypes2[PlatformTypes2["NODE"] = 3] = "NODE"; | ||
})(PlatformTypes || (PlatformTypes = {})); | ||
var BrowserBreadcrumbTypes; | ||
(function(BrowserBreadcrumbTypes2) { | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["ROUTE"] = 11] = "ROUTE"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CLICK"] = 12] = "CLICK"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CONSOLE"] = 13] = "CONSOLE"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["XHR"] = 14] = "XHR"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["FETCH"] = 15] = "FETCH"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["UNHANDLEDREJECTION"] = 16] = "UNHANDLEDREJECTION"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["RESOURCE"] = 17] = "RESOURCE"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CODE_ERROR"] = 18] = "CODE_ERROR"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CUSTOMER"] = 19] = "CUSTOMER"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["FRAMEWORK"] = 20] = "FRAMEWORK"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["LIFECYCLE"] = 21] = "LIFECYCLE"; | ||
BrowserBreadcrumbTypes2[BrowserBreadcrumbTypes2["CRASH"] = 22] = "CRASH"; | ||
})(BrowserBreadcrumbTypes || (BrowserBreadcrumbTypes = {})); | ||
var WxBreadcrumbTypes; | ||
(function(WxBreadcrumbTypes2) { | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["API"] = 21] = "API"; | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["ROUTE"] = 22] = "ROUTE"; | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["CLICK"] = 23] = "CLICK"; | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["ERROR"] = 24] = "ERROR"; | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["LIFECYCLE"] = 25] = "LIFECYCLE"; | ||
WxBreadcrumbTypes2[WxBreadcrumbTypes2["CUSTOMER"] = 26] = "CUSTOMER"; | ||
})(WxBreadcrumbTypes || (WxBreadcrumbTypes = {})); | ||
const getStoreIns = (type) => { | ||
let store = null; | ||
switch (type) { | ||
case StoreType.LOCAL: | ||
store = localStorage; | ||
break; | ||
case StoreType.SESSION: | ||
store = sessionStorage; | ||
break; | ||
} | ||
return store; | ||
}; | ||
const getStore = (type, keyPath, needParse = true) => { | ||
if (!type || !keyPath) { | ||
return ""; | ||
} | ||
const store = getStoreIns(type); | ||
if (!store) { | ||
return ""; | ||
} | ||
let result = ""; | ||
try { | ||
const paths = keyPath.split("."); | ||
const [key] = paths; | ||
result = store.getItem(key); | ||
if (needParse) { | ||
result = JSON.parse(result); | ||
if (paths.length > 1) { | ||
result = paths.slice(1).reduce((pre, cur) => pre[cur], result); | ||
} | ||
} | ||
} catch (err) { | ||
console.error(TAG, err); | ||
} | ||
return result; | ||
}; | ||
const setStore = (type, key, data) => { | ||
if (!key) { | ||
return; | ||
} | ||
const store = getStoreIns(type); | ||
if (!store) { | ||
return; | ||
} | ||
store.setItem(key, JSON.stringify(data)); | ||
}; | ||
const setCookie = (key, value, days) => { | ||
if (!key || !value || !days) { | ||
return; | ||
} | ||
const exp = new Date(); | ||
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1e3); | ||
document.cookie = `${key}=${encodeURIComponent(value)};expires=${exp.toUTCString()}`; | ||
}; | ||
const getCookie = (key) => { | ||
if (!key) { | ||
return ""; | ||
} | ||
const arr = document.cookie.match(new RegExp(`(^| )${key}=([^;]*)(;|$)`)); | ||
if (arr != null) { | ||
return decodeURIComponent(arr[2]); | ||
} | ||
return ""; | ||
}; | ||
const delCookie = (key) => { | ||
if (!key) { | ||
return; | ||
} | ||
const exp = new Date(); | ||
exp.setTime(exp.getTime() - 1); | ||
const cval = getCookie(key); | ||
if (cval != null) { | ||
document.cookie = `${key}=${cval};expires=${exp.toUTCString()}`; | ||
} | ||
}; | ||
const parseHeaders = (headers) => { | ||
const headerObj = {}; | ||
headers.trim().split(/[\r\n]+/).forEach((line) => { | ||
const [key, value] = line.split(": "); | ||
headerObj[key] = value; | ||
}); | ||
return headerObj; | ||
}; | ||
const beacon = (url, data) => { | ||
if (!url || typeof url !== "string") { | ||
console.error("Invalid URL"); | ||
return false; | ||
} | ||
if (!data || typeof data !== "object") { | ||
console.error("Invalid data"); | ||
return false; | ||
} | ||
const formData = new FormData(); | ||
for (const key in data) { | ||
if (Object.prototype.hasOwnProperty.call(data, key)) { | ||
let value = data[key]; | ||
if (typeof value !== "string" && !(value instanceof Blob)) { | ||
value = JSON.stringify(value); | ||
} | ||
formData.append(key, value); | ||
} | ||
} | ||
return navigator.sendBeacon(url, formData); | ||
}; | ||
const get = (url, data) => { | ||
const queryString = obj2query(data); | ||
const separator = url.includes("?") ? "&" : "?"; | ||
return xhr(MethodTypes.GET, `${url}${separator}${queryString}`, null); | ||
}; | ||
const post = (url, data) => xhr(MethodTypes.POST, url, data); | ||
const xhr = (method, url, data) => { | ||
return new Promise((resolve, reject) => { | ||
const xhr2 = new XMLHttpRequest(); | ||
xhr2.open(method, url, true); | ||
if (method === MethodTypes.POST) { | ||
if (typeof data === "string" || data instanceof URLSearchParams) { | ||
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); | ||
} else { | ||
xhr2.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); | ||
} | ||
} | ||
xhr2.onreadystatechange = () => { | ||
if (xhr2.readyState === XMLHttpRequest.DONE) { | ||
const responseHeaders = parseHeaders(xhr2.getAllResponseHeaders()); | ||
if (xhr2.status >= 200 && xhr2.status < 300) { | ||
try { | ||
const responseData = xhr2.responseText ? JSON.parse(xhr2.responseText) : null; | ||
resolve({ | ||
status: xhr2.status, | ||
statusText: xhr2.statusText, | ||
headers: responseHeaders, | ||
data: responseData | ||
}); | ||
} catch (error) { | ||
reject(new Error(`Failed to parse response: ${xhr2.responseText}`)); | ||
} | ||
} else { | ||
reject({ | ||
status: xhr2.status, | ||
statusText: xhr2.statusText, | ||
headers: responseHeaders, | ||
data: xhr2.responseText | ||
}); | ||
} | ||
} | ||
}; | ||
xhr2.onerror = () => { | ||
reject(new Error("Network error")); | ||
}; | ||
try { | ||
if (method === MethodTypes.POST) { | ||
if (typeof data === "string" || data instanceof URLSearchParams) { | ||
xhr2.send(data); | ||
} else { | ||
xhr2.send(JSON.stringify(data)); | ||
} | ||
} else { | ||
xhr2.send(); | ||
} | ||
} catch (error) { | ||
reject(error); | ||
} | ||
}); | ||
}; | ||
const imgRequest = (url, data) => { | ||
const queryString = obj2query(data); | ||
const separator = url.includes("?") ? "&" : "?"; | ||
const fullUrl = `${url}${separator}${queryString}`; | ||
const img = new Image(); | ||
img.src = fullUrl; | ||
setTimeout(() => { | ||
img.src = ""; | ||
}, 0); | ||
}; | ||
exports.beacon = beacon; | ||
exports.countBytes = countBytes; | ||
exports.delCookie = delCookie; | ||
exports.formatDecimal = formatDecimal; | ||
exports.formateUrlPath = formateUrlPath; | ||
exports.generateUUID = generateUUID; | ||
exports.get = get; | ||
exports.getCookie = getCookie; | ||
exports.getDeepPropByDot = getDeepPropByDot; | ||
exports.getStore = getStore; | ||
exports.getUrlPath = getUrlPath; | ||
exports.hasConsole = hasConsole; | ||
exports.imgRequest = imgRequest; | ||
exports.obj2query = obj2query; | ||
exports.post = post; | ||
exports.replaceOld = replaceOld; | ||
exports.setCookie = setCookie; | ||
exports.setStore = setStore; | ||
exports.setUrlQuery = setUrlQuery; | ||
exports.splitStringByBytes = splitStringByBytes; | ||
exports.throttle = throttle; | ||
exports.xhr = xhr; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
})); | ||
/* follow me on Github! @LuciferHuang */ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HEIMDALLR_UTILS={})}(this,(function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,s=(e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;const E=e=>Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&");var R,a=((R=a||{}).NAME="@heimdallr-sdk",R);var i=(e=>(e[e.FATAL=1]="FATAL",e[e.ERROR=2]="ERROR",e[e.WARN=3]="WARN",e[e.INFO=4]="INFO",e[e.DEBUG=5]="DEBUG",e))(i||{}),c=(e=>(e.SESSION_ID="HEIMDALLR_SDK_SESSION_ID",e.USER_ID="HEIMDALLR_SDK_USER_ID",e.APP="HEIMDALLR_SDK_APP_ID",e))(c||{}),O=(e=>(e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE",e))(O||{}),l=(e=>(e[e.LIFECYCLE=1]="LIFECYCLE",e[e.ERROR=2]="ERROR",e[e.PERFORMANCE=3]="PERFORMANCE",e[e.API=4]="API",e[e.DOM=5]="DOM",e[e.ROUTE=6]="ROUTE",e[e.CONSOLE=7]="CONSOLE",e[e.RECORD=8]="RECORD",e[e.VUE=9]="VUE",e[e.CUSTOMER=10]="CUSTOMER",e[e.EXTEND=11]="EXTEND",e))(l||{}),C=(e=>(e[e.CODEERROR=21]="CODEERROR",e[e.RESOURCEERROR=22]="RESOURCEERROR",e[e.UNHANDLEDREJECTION=23]="UNHANDLEDREJECTION",e[e.PAGECRASH=24]="PAGECRASH",e))(C||{}),u=(e=>(e[e.BEACON=1]="BEACON",e[e.IMG=2]="IMG",e[e.GET=3]="GET",e[e.POST=4]="POST",e))(u||{}),S=(e=>(e[e.CLICK=51]="CLICK",e))(S||{}),p=(e=>(e.LOG="log",e.INFO="info",e.WARN="warn",e.ERROR="error",e.ASSERT="assert",e))(p||{}),T=(e=>(e[e.XHR=41]="XHR",e[e.FETCH=42]="FETCH",e))(T||{}),d=(e=>(e[e.FMP=31]="FMP",e[e.FPS=32]="FPS",e[e.BASIC=33]="BASIC",e[e.VITALS=34]="VITALS",e[e.RESOURCE=35]="RESOURCE",e))(d||{}),f=(e=>(e[e.HASH=61]="HASH",e[e.HISTORY=62]="HISTORY",e))(f||{}),L=(e=>(e[e.CUSTOMER=111]="CUSTOMER",e))(L||{}),I=(e=>(e.LOCAL="local",e.SESSION="session",e.COOKIE="cookie",e.GLOBAL="global",e))(I||{}),x=(e=>(e[e.LOAD=11]="LOAD",e[e.UNLOAD=12]="UNLOAD",e))(x||{}),A=(e=>(e[e.MOBILE=1]="MOBILE",e[e.PC=2]="PC",e))(A||{}),U=(e=>(e[e.BROWSER=1]="BROWSER",e[e.WECHAT=2]="WECHAT",e[e.NODE=3]="NODE",e))(U||{}),D=(e=>(e[e.ROUTE=11]="ROUTE",e[e.CLICK=12]="CLICK",e[e.CONSOLE=13]="CONSOLE",e[e.XHR=14]="XHR",e[e.FETCH=15]="FETCH",e[e.UNHANDLEDREJECTION=16]="UNHANDLEDREJECTION",e[e.RESOURCE=17]="RESOURCE",e[e.CODE_ERROR=18]="CODE_ERROR",e[e.CUSTOMER=19]="CUSTOMER",e[e.FRAMEWORK=20]="FRAMEWORK",e[e.LIFECYCLE=21]="LIFECYCLE",e[e.CRASH=22]="CRASH",e))(D||{}),N=(e=>(e[e.API=21]="API",e[e.ROUTE=22]="ROUTE",e[e.CLICK=23]="CLICK",e[e.ERROR=24]="ERROR",e[e.LIFECYCLE=25]="LIFECYCLE",e[e.CUSTOMER=26]="CUSTOMER",e))(N||{});const y=e=>{let t=null;switch(e){case I.LOCAL:t=localStorage;break;case I.SESSION:t=sessionStorage}return t},g=e=>{if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""},m=(e,t,r)=>new Promise(((n,o)=>{const s=new XMLHttpRequest;if(e===O.GET&&r){const e=new URLSearchParams(r),n=t.includes("?")?"&":"?";t+=`${n}${e.toString()}`}s.open(e,t,!0),e!==O.GET&&("string"==typeof r||r instanceof URLSearchParams?s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):s.setRequestHeader("Content-Type","application/json;charset=UTF-8")),s.onreadystatechange=()=>{if(s.readyState===XMLHttpRequest.DONE){const e=(e=>{const t={};return e.trim().split(/[\r\n]+/).forEach((e=>{const[r,n]=e.split(": ");t[r]=n})),t})(s.getAllResponseHeaders());if(s.status>=200&&s.status<300){try{const t=s.responseText?JSON.parse(s.responseText):null;n({status:s.status,statusText:s.statusText,headers:e,data:t})}catch(e){o(new Error(`Failed to parse response: ${s.responseText}`))}return}o({status:s.status,statusText:s.statusText,headers:e,data:s.responseText})}},s.onerror=()=>{o(new Error("Network error"))};try{if(e!==O.GET)return"string"==typeof r||r instanceof URLSearchParams?void s.send(r):void s.send(JSON.stringify(r));s.send()}catch(e){o(e)}}));e.beacon=(e,t)=>{if(!e||"string"!=typeof e)return console.error("Invalid URL"),!1;if(!t||"object"!=typeof t)return console.error("Invalid data"),!1;const r=new FormData;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];"string"==typeof n||n instanceof Blob||(n=JSON.stringify(n)),r.append(e,n)}return navigator.sendBeacon(e,r)},e.countBytes=e=>(new TextEncoder).encode(e).length,e.delCookie=e=>{if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const r=g(e);null!=r&&(document.cookie=`${e}=${r};expires=${t.toUTCString()}`)},e.formatDecimal=(e,t)=>!isFinite(e)||isNaN(e)||!Number.isInteger(t)||t<0?e:parseFloat(e.toFixed(t)),e.formateUrlPath=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,e.generateUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),e.get=(e,t)=>m(O.GET,e,t),e.getCookie=g,e.getDeepPropByDot=(e,t)=>{if(!e||!t)return null;const E=((e,t)=>{for(var E in t||(t={}))n.call(t,E)&&s(e,E,t[E]);if(r)for(var E of r(t))o.call(t,E)&&s(e,E,t[E]);return e})({},t),R=e.split(".");let a=E;for(const e of R){const t=a[e];if(!t)return null;a=t}return a},e.getStore=(e,t,r=!0)=>{if(!e||!t)return"";const n=y(e);if(!n)return"";let o="";try{const e=t.split("."),[s]=e;o=n.getItem(s),r&&(o=JSON.parse(o),e.length>1&&(o=e.slice(1).reduce(((e,t)=>e[t]),o)))}catch(e){console.error("[@heimdallr-sdk]:",e)}return o},e.getUrlPath=e=>{const t=/^[a-zA-Z]+:\/\//.test(e);try{const{pathname:r}=new URL(e,t?void 0:"http://temporaryurl.com");return r.endsWith("/")&&r.length>1?r.slice(0,-1):r}catch(e){return""}},e.imgRequest=(e,t)=>{const r=E(t),n=e.includes("?")?"&":"?",o=`${e}${n}${r}`,s=new Image;s.src=o,setTimeout((()=>{s.src=""}),0)},e.obj2query=E,e.post=(e,t)=>m(O.POST,e,t),e.replaceOld=(e,t,r,n)=>{if(void 0!==e&&(t in e||n)){const n=r(e[t]);"function"==typeof n&&(e[t]=n)}},e.setCookie=(e,t,r)=>{if(!e||!t||!r)return;const n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${n.toUTCString()}`},e.setStore=(e,t,r)=>{if(!t)return;const n=y(e);n&&n.setItem(t,JSON.stringify(r))},e.setUrlQuery=(e,t={})=>{const r=[];return Object.keys(t).forEach((e=>{r.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${r.join("&")}`},e.splitStringByBytes=(e,t)=>{const r=(new TextEncoder).encode(e),n=new TextDecoder,o=[];let s=0;for(;s<r.length;){let e=s+t;for(;e>s&&128==(192&r[e]);)e--;o.push(n.decode(r.subarray(s,e))),s=e}return o},e.throttle=(e,t)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}},e.xhr=m,Object.defineProperty(e,"__esModule",{value:!0})})); |
@@ -1,4 +0,36 @@ | ||
export * from './base'; | ||
export * from './helper'; | ||
export * from './browser'; | ||
export * from './request'; | ||
import { IAnyObject, StoreTypes, StoreType, XhrResponse, HttpCommonRes, MethodTypes } from '@heimdallr-sdk/types'; | ||
declare const formateUrlPath: (host: string, path: string) => string; | ||
declare const getUrlPath: (url: string) => string; | ||
declare const setUrlQuery: (url: string, query?: {}) => string; | ||
declare const getDeepPropByDot: (keyPath: string, obj: Object) => { | ||
constructor: Function; | ||
toString(): string; | ||
toLocaleString(): string; | ||
valueOf(): Object; | ||
hasOwnProperty(v: PropertyKey): boolean; | ||
isPrototypeOf(v: Object): boolean; | ||
propertyIsEnumerable(v: PropertyKey): boolean; | ||
}; | ||
declare const obj2query: (params: IAnyObject) => string; | ||
declare const generateUUID: () => string; | ||
declare const throttle: <T extends (...args: any[]) => void>(fn: T, delay: number) => (...args: Parameters<T>) => void; | ||
declare const replaceOld: (source: IAnyObject, name: string, replacement: (...args: any[]) => any, isForced?: boolean) => void; | ||
declare const formatDecimal: (num: number, decimal: number) => number; | ||
declare const countBytes: (str: string) => number; | ||
declare const splitStringByBytes: (str: string, maxBytes: number) => Array<string>; | ||
declare const getStore: <T>(type: StoreTypes, keyPath: string, needParse?: boolean) => "" | T; | ||
declare const setStore: (type: StoreType, key: string, data: any) => void; | ||
declare const setCookie: (key: string, value: any, days: number) => void; | ||
declare const getCookie: (key: string) => string; | ||
declare const delCookie: (key: string) => void; | ||
declare const beacon: (url: string, data: Record<string, any>) => boolean; | ||
declare const get: (url: string, data: Record<string, any>) => Promise<XhrResponse<HttpCommonRes<any>>>; | ||
declare const post: (url: string, data: Record<string, any>) => Promise<XhrResponse<HttpCommonRes<any>>>; | ||
declare const xhr: (method: MethodTypes, url: string, data: any) => Promise<XhrResponse<HttpCommonRes>>; | ||
declare const imgRequest: (url: string, data: Record<string, any>) => void; | ||
export { beacon, countBytes, delCookie, formatDecimal, formateUrlPath, generateUUID, get, getCookie, getDeepPropByDot, getStore, getUrlPath, imgRequest, obj2query, post, replaceOld, setCookie, setStore, setUrlQuery, splitStringByBytes, throttle, xhr }; |
@@ -1,4 +0,1 @@ | ||
export * from './base'; | ||
export * from './helper'; | ||
export * from './browser'; | ||
export * from './request'; | ||
import{StoreType as e,TAG as t,MethodTypes as r}from"@heimdallr-sdk/types";var n=Object.defineProperty,o=Object.getOwnPropertySymbols,s=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,c=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;const i=(e,t)=>`${/^http(s|):\/\//.test(e||"")?e:`//${(e||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(t||"")[0]?t.substring(1):t}`,p=e=>{const t=/^[a-zA-Z]+:\/\//.test(e);try{const{pathname:r}=new URL(e,t?void 0:"http://temporaryurl.com");return r.endsWith("/")&&r.length>1?r.slice(0,-1):r}catch(e){return""}},u=(e,t={})=>{const r=[];return Object.keys(t).forEach((e=>{r.push(`${e}=${t[e]}`)})),`${e}${-1!==e.indexOf("?")?"&":"?"}${r.join("&")}`},l=(e,t)=>{if(!e||!t)return null;const r=((e,t)=>{for(var r in t||(t={}))s.call(t,r)&&c(e,r,t[r]);if(o)for(var r of o(t))a.call(t,r)&&c(e,r,t[r]);return e})({},t),n=e.split(".");let i=r;for(const e of n){const t=i[e];if(!t)return null;i=t}return i},x=e=>Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&"),d=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),f=(e,t)=>{let r=0;return function(...n){const o=Date.now();o-r>=t&&(r=o,e.apply(this,n))}},m=(e,t,r,n)=>{if(void 0!==e&&(t in e||n)){const n=r(e[t]);"function"==typeof n&&(e[t]=n)}},y=(e,t)=>!isFinite(e)||isNaN(e)||!Number.isInteger(t)||t<0?e:parseFloat(e.toFixed(t)),h=e=>(new TextEncoder).encode(e).length,g=(e,t)=>{const r=(new TextEncoder).encode(e),n=new TextDecoder,o=[];let s=0;for(;s<r.length;){let e=s+t;for(;e>s&&128==(192&r[e]);)e--;o.push(n.decode(r.subarray(s,e))),s=e}return o},T=t=>{let r=null;switch(t){case e.LOCAL:r=localStorage;break;case e.SESSION:r=sessionStorage}return r},w=(e,r,n=!0)=>{if(!e||!r)return"";const o=T(e);if(!o)return"";let s="";try{const e=r.split("."),[t]=e;s=o.getItem(t),n&&(s=JSON.parse(s),e.length>1&&(s=e.slice(1).reduce(((e,t)=>e[t]),s)))}catch(e){console.error(t,e)}return s},$=(e,t,r)=>{if(!t)return;const n=T(e);n&&n.setItem(t,JSON.stringify(r))},O=(e,t,r)=>{if(!e||!t||!r)return;const n=new Date;n.setTime(n.getTime()+24*r*60*60*1e3),document.cookie=`${e}=${encodeURIComponent(t)};expires=${n.toUTCString()}`},S=e=>{if(!e)return"";const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]*)(;|$)`));return null!=t?decodeURIComponent(t[2]):""},b=e=>{if(!e)return;const t=new Date;t.setTime(t.getTime()-1);const r=S(e);null!=r&&(document.cookie=`${e}=${r};expires=${t.toUTCString()}`)},R=(e,t)=>{if(!e||"string"!=typeof e)return console.error("Invalid URL"),!1;if(!t||"object"!=typeof t)return console.error("Invalid data"),!1;const r=new FormData;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];"string"==typeof n||n instanceof Blob||(n=JSON.stringify(n)),r.append(e,n)}return navigator.sendBeacon(e,r)},E=(e,t)=>U(r.GET,e,t),I=(e,t)=>U(r.POST,e,t),U=(e,t,n)=>new Promise(((o,s)=>{const a=new XMLHttpRequest;if(e===r.GET&&n){const e=new URLSearchParams(n),r=t.includes("?")?"&":"?";t+=`${r}${e.toString()}`}a.open(e,t,!0),e!==r.GET&&("string"==typeof n||n instanceof URLSearchParams?a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):a.setRequestHeader("Content-Type","application/json;charset=UTF-8")),a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){const e=(e=>{const t={};return e.trim().split(/[\r\n]+/).forEach((e=>{const[r,n]=e.split(": ");t[r]=n})),t})(a.getAllResponseHeaders());if(a.status>=200&&a.status<300){try{const t=a.responseText?JSON.parse(a.responseText):null;o({status:a.status,statusText:a.statusText,headers:e,data:t})}catch(e){s(new Error(`Failed to parse response: ${a.responseText}`))}return}s({status:a.status,statusText:a.statusText,headers:e,data:a.responseText})}},a.onerror=()=>{s(new Error("Network error"))};try{if(e!==r.GET)return"string"==typeof n||n instanceof URLSearchParams?void a.send(n):void a.send(JSON.stringify(n));a.send()}catch(e){s(e)}})),j=(e,t)=>{const r=x(t),n=e.includes("?")?"&":"?",o=`${e}${n}${r}`,s=new Image;s.src=o,setTimeout((()=>{s.src=""}),0)};export{R as beacon,h as countBytes,b as delCookie,y as formatDecimal,i as formateUrlPath,d as generateUUID,E as get,S as getCookie,l as getDeepPropByDot,w as getStore,p as getUrlPath,j as imgRequest,x as obj2query,I as post,m as replaceOld,O as setCookie,$ as setStore,u as setUrlQuery,g as splitStringByBytes,f as throttle,U as xhr}; |
{ | ||
"name": "@heimdallr-sdk/utils", | ||
"version": "0.0.20", | ||
"version": "0.0.21", | ||
"description": "@heimdallr-sdk/utils", | ||
@@ -25,12 +25,9 @@ "license": "MIT", | ||
}, | ||
"scripts": { | ||
"dev": "rimraf dist && rollup --config rollup.config.dev.js -w", | ||
"build": "run-p build:bundle build:esm", | ||
"build:bundle": "rimraf dist && rollup --config", | ||
"build:esm": "rimraf esm && tsc -p tsconfig.json" | ||
}, | ||
"dependencies": { | ||
"@heimdallr-sdk/types": "^0.0.16" | ||
"@heimdallr-sdk/types": "^0.0.17" | ||
}, | ||
"gitHead": "cd187687df2e4fe32756115e220be5d72c4152b0" | ||
} | ||
"scripts": { | ||
"dev": "rimraf esm && rollup -c rollup.config.dev.js -w", | ||
"build": "rimraf dist esm && rollup -c" | ||
} | ||
} |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
21925
7
100
+ Added@heimdallr-sdk/types@0.0.17(transitive)
- Removed@heimdallr-sdk/types@0.0.16(transitive)
Updated@heimdallr-sdk/types@^0.0.17