@heimdallr-sdk/wx
Version:
A SDK For Monitoring wechat applet
2 lines (1 loc) • 9.4 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).HEIMDALLR_WX={})}(this,(function(t){"use strict";var e,s=((e=s||{}).NAME="@heimdallr-sdk",e);const n="[@heimdallr-sdk]:";var i=(t=>(t[t.FATAL=1]="FATAL",t[t.ERROR=2]="ERROR",t[t.WARN=3]="WARN",t[t.INFO=4]="INFO",t[t.DEBUG=5]="DEBUG",t))(i||{}),o=(t=>(t.SESSION_ID="HEIMDALLR_SDK_SESSION_ID",t.USER_ID="HEIMDALLR_SDK_USER_ID",t.APP="HEIMDALLR_SDK_APP_ID",t))(o||{}),r=(t=>(t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t))(r||{}),a=(t=>(t[t.LIFECYCLE=1]="LIFECYCLE",t[t.ERROR=2]="ERROR",t[t.PERFORMANCE=3]="PERFORMANCE",t[t.API=4]="API",t[t.DOM=5]="DOM",t[t.ROUTE=6]="ROUTE",t[t.CONSOLE=7]="CONSOLE",t[t.RECORD=8]="RECORD",t[t.VUE=9]="VUE",t[t.CUSTOMER=10]="CUSTOMER",t[t.EXTEND=11]="EXTEND",t))(a||{}),c=(t=>(t[t.BEACON=1]="BEACON",t[t.IMG=2]="IMG",t[t.GET=3]="GET",t[t.POST=4]="POST",t))(c||{}),h=(t=>(t.LOG="log",t.INFO="info",t.WARN="warn",t.ERROR="error",t.ASSERT="assert",t))(h||{}),l=(t=>(t[t.XHR=41]="XHR",t[t.FETCH=42]="FETCH",t))(l||{}),u=(t=>(t[t.HASH=61]="HASH",t[t.HISTORY=62]="HISTORY",t))(u||{}),d=(t=>(t.LOCAL="local",t.SESSION="session",t.COOKIE="cookie",t.GLOBAL="global",t))(d||{}),p=(t=>(t[t.LOAD=11]="LOAD",t[t.UNLOAD=12]="UNLOAD",t))(p||{}),E=(t=>(t[t.MOBILE=1]="MOBILE",t[t.PC=2]="PC",t))(E||{}),O=(t=>(t[t.BROWSER=1]="BROWSER",t[t.WECHAT=2]="WECHAT",t[t.NODE=3]="NODE",t))(O||{}),f=(t=>(t[t.ROUTE=11]="ROUTE",t[t.CLICK=12]="CLICK",t[t.CONSOLE=13]="CONSOLE",t[t.XHR=14]="XHR",t[t.FETCH=15]="FETCH",t[t.UNHANDLEDREJECTION=16]="UNHANDLEDREJECTION",t[t.RESOURCE=17]="RESOURCE",t[t.CODE_ERROR=18]="CODE_ERROR",t[t.CUSTOMER=19]="CUSTOMER",t[t.FRAMEWORK=20]="FRAMEWORK",t[t.LIFECYCLE=21]="LIFECYCLE",t[t.CRASH=22]="CRASH",t))(f||{}),R=(t=>(t[t.API=21]="API",t[t.ROUTE=22]="ROUTE",t[t.CLICK=23]="CLICK",t[t.ERROR=24]="ERROR",t[t.LIFECYCLE=25]="LIFECYCLE",t[t.CUSTOMER=26]="CUSTOMER",t))(R||{});const x=(t,e)=>`${/^http(s|):\/\//.test(t||"")?t:`//${(t||"").replace(/^http(s|):\/\//,"")}`}/${"/"===(e||"")[0]?e.substring(1):e}`,C=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),g=(t,e,s,n)=>{if(void 0!==t&&(e in t||n)){const n=s(t[e]);"function"==typeof n&&(t[e]=n)}};class T{constructor(){this.dep=new Map}watch(t,e){const s=this.dep.get(t);s?this.dep.set(t,s.concat(e)):this.dep.set(t,[e])}notify(t,e){const s=this.dep.get(t);t&&s&&s.forEach((t=>{try{t(e)}catch(t){console.error(t)}}))}}var S=Object.defineProperty,m=Object.getOwnPropertySymbols,y=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable,b=(t,e,s)=>e in t?S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,w=(t,e)=>{for(var s in e||(e={}))y.call(e,s)&&b(t,s,e[s]);if(m)for(var s of m(e))A.call(e,s)&&b(t,s,e[s]);return t};class L{constructor(t){this.options=t,this.initConsole(),this.isRightEnv()?(this.bindOptions(),this.isReady=!1,this.taskQueue=[],this.initAPP().then((t=>{t&&this.appID!==t&&(this.appID=t),this.isReady=!0,this.executeTaskQueue()}))):console.warn(n,"Client does not match the environment")}initConsole(){const{debug:t}=this.options;t&&"undefined"!=typeof console||Object.keys(h).forEach((t=>{console[t]=()=>null}))}bindOptions(){const{dsn:t,app:e,debug:s=!1,enabled:i=!0}=this.options;if(!e||!t)return void console.warn(n,"Missing app or dsn in options");const{host:o,init:r,report:a=""}=t,c=x(o,r),h=x(o,a);this.context={app:e,uploadUrl:h,initUrl:c,debug:s,enabled:i}}use(t){const{uploadUrl:e,enabled:s}=this.context,n=new T,i=new Map;for(const o of t){const{name:t,monitor:r,transform:a}=o||{};if(!t||!r){console.warn("The plugin missing name or monitor.");continue}if(i.has(t)){console.warn(`The plugin name [${t}] is duplicate, please modify it.`);continue}i.set(t,1);try{r.call(this,n.notify.bind(n,t))}catch(t){console.error(t)}const c=(...t)=>{const n="function"==typeof a?a.apply(this,t):t;if(!n)return;const i=this.transform(n);i&&s&&(this.isReady?this.nextTick(this.report,this,e,w({aid:this.appID},i)):this.taskQueue.push(i))};n.watch(t,c)}}executeTaskQueue(){const{uploadUrl:t}=this.context;for(;this.taskQueue.length;){const e=this.taskQueue.shift();this.nextTick(this.report,this,t,w({aid:this.appID},e))}}getClientOptions(){return w({},this.options)}getContext(){return w({},this.context)}}class I{constructor(t={}){this.maxBreadcrumbs=t.maxBreadcrumbs||80,this.stack=[]}unshift(t){return t.l||(t.l=i.INFO),this.stack.length>=this.maxBreadcrumbs&&this.pop(),this.stack.unshift(t),this.stack.sort(((t,e)=>e.t-t.t)),this.stack}pop(){return void 0!==this.stack.pop()}clear(){this.stack=[]}getStack(){return this.stack.slice(0)}}var D=(t=>(t.UNCAUGHTEXCEPTION="uncaughtException",t))(D||{});var P=Object.defineProperty,U=Object.defineProperties,k=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,M=(t,e,s)=>e in t?P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,F=(t,e)=>{for(var s in e||(e={}))H.call(e,s)&&M(t,s,e[s]);if(N)for(var s of N(e))v.call(e,s)&&M(t,s,e[s]);return t},W=(t,e)=>U(t,k(e)),_=(t,e,s)=>new Promise(((n,i)=>{var o=t=>{try{a(s.next(t))}catch(t){i(t)}},r=t=>{try{a(s.throw(t))}catch(t){i(t)}},a=t=>t.done?n(t.value):Promise.resolve(t.value).then(o,r);a((s=s.apply(t,e)).next())}));const j="heimdallr-event-log";class B extends L{constructor(t){super(t),this.diff=0,this.wxContext={},this.requestTasks=new Map,this.breadcrumb=new I(t)}setWxContext(t){this.wxContext=F(F({},this.wxContext),t)}clearWxContext(){this.wxContext={}}getWxContext(){return F({},this.wxContext)}initAPP(){return _(this,null,(function*(){yield this.getWxSettings();const{initUrl:t,app:e}=this.getContext(),s=this.getTime(),n=W(F({},e),{ctime:s}),i=yield this.report(t,n),{header:o,data:{data:r={}}={}}=i;this.setDiff(o.Date);const{id:a=""}=r||{};return a}))}getWxSettings(){return _(this,null,(function*(){const{bluetoothEnabled:t,locationEnabled:e}=wx.getSystemSetting(),{brand:s,model:n,system:i}=wx.getDeviceInfo(),{windowWidth:o,windowHeight:r}=wx.getWindowInfo(),{SDKVersion:a,language:c,version:h}=wx.getAppBaseInfo(),{cameraAuthorized:l,locationAuthorized:u,microphoneAuthorized:d,notificationAuthorized:p,phoneCalendarAuthorized:E}=wx.getAppAuthorizeSetting(),O=yield wx.getRendererUserAgent();this.wxSettings={btEn:t,locEn:e,brand:s,model:n,system:i,width:o,height:r,sdk:a,lan:c,version:h,ua:O,camAuth:l,locAuth:u,micAuth:d,notifyAuth:p,calAuth:E}}))}isRightEnv(){return"undefined"!=typeof wx&&"undefined"!=typeof App}report(t,e){const{reqOption:s}=this.getClientOptions();return new Promise(((n,i)=>{const o="function"==typeof s?s(n,i):{},r=wx.request(W(F({success:t=>{n(t)},fail:t=>i(t),url:t,method:"POST"},o),{data:e,dataType:"json",complete:()=>{this.requestTasks.delete(r)}}));this.requestTasks.set(r,e)}))}transform(t){if(!t)return null;const{dat:e}=t,s=this.getWxContext();let n=W(F(F({t:this.getTime(),p:O.WECHAT},s),t),{dat:JSON.stringify(e)});const{st:i}=e;return i===p.LOAD&&(n=F(F({},n),this.wxSettings)),n}nextTick(t,e,...s){wx.nextTick((()=>{t.call(e,...s)}))}setDiff(t){const e=new Date(t),s=Date.now()-e.getTime();(!this.diff||this.diff>s)&&(this.diff=s)}getTime(){return Date.now()-(this.diff||0)}lifecycleReport(t){const{uploadUrl:e,enabled:s}=this.getContext();t&&s&&(this.appID?this.nextTick(this.report,this,e,F({aid:this.appID},t)):this.taskQueue.push(t))}handleOnShow(t){const e=wx.getStorageSync(j);Array.isArray(e)&&(e.forEach((t=>{this.lifecycleReport(t)})),wx.removeStorageSync(j));const s={sid:C(),url:t},{userStoreKey:i}=this.getClientOptions();if("string"==typeof i){const t=function(t){if(!t)return null;try{return wx.getStorageSync(t)}catch(e){return console.error(n,`Get ${t} faild`,e),null}}(i);s.ui=t}this.setWxContext(s);const o=C();this.breadcrumb.unshift({lid:o,bt:R.LIFECYCLE,msg:`Enter "${t}"`,t:this.getTime()}),this.lifecycleReport(this.transform({lid:o,e:a.LIFECYCLE,dat:{st:p.LOAD,href:t}}))}handleOnHide(t){this.requestTasks.size&&(wx.setStorage({key:j,data:[...this.requestTasks.values()]}),this.requestTasks.forEach(((t,e)=>{e.abort()})));const e=C();this.breadcrumb.unshift({lid:e,bt:R.LIFECYCLE,msg:`Leave "${t}"`,t:this.getTime()}),this.lifecycleReport(this.transform({lid:e,e:a.LIFECYCLE,dat:{st:p.UNLOAD,href:t}})),this.clearWxContext()}cusOnShow(){const t=this;return e=>function(s){e&&e.apply(this,s),t.handleOnShow(this.route)}}cusOnHide(){const t=this;return e=>function(){e&&e.apply(this),t.handleOnHide(this.route)}}}t.WxClient=B,t.default=t=>{const e=new B(t),{plugins:s=[]}=t;return e.use([{name:"errorPlugin",monitor(t){const e=App;App=function(s){return g(s,"onError",(function(e){return function(...s){e&&e.apply(this,s);const[i]=s;console.error(n,i),t({err:i})}}),!0),e(s)}},transform(t){const{err:e}=t,s=C();this.breadcrumb.unshift({lid:s,bt:R.ERROR,l:i.ERROR,msg:e,t:this.getTime()});const n=this.breadcrumb.getStack();return{lid:s,t:this.getTime(),e:a.ERROR,b:n,dat:{st:D.UNCAUGHTEXCEPTION,err:e}}}},...s]),{heimdallrPage:t=>{g(t,"onShow",e.cusOnShow(),!0),g(t,"onHide",e.cusOnHide(),!0),Page(t)},track:(t,s)=>{switch(t){case"show":e.handleOnShow(s);break;case"hide":e.handleOnHide(s);break;default:console.warn(n,"Unknown type")}}}},Object.defineProperty(t,"__esModule",{value:!0})}));