@huolala-tech/page-spy-alipay
Advanced tools
Comparing version 2.0.0-beta.0 to 2.0.0-beta.1
@@ -1,2 +0,50 @@ | ||
function e(){return Math.random().toString(36).slice(2)}function t(e){return Object.prototype.toString.call(e)}function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function s(e){return"[object BigInt]"===t(e)}function o(e){return e instanceof Array}function r(e){return"object"==typeof e&&null!==e}function i(e){return!(!r(e)||"[object Object]"!==t(e))}const a=e=>"".concat(e),c=e=>({ok:!0,value:e});function l(e){return void 0===e?c(a(e)):null===e?c(e):function(e){return"number"==typeof e}(e)&&(e===-1/0||e===1/0||Number.isNaN(e))?c(a(e)):s(e)?c("".concat(e,"n")):"symbol"==typeof e||"function"==typeof e?c(a(e.toString())):e instanceof Error?c(a(e.stack)):e===Object.prototype?{value:null,ok:!1}:e instanceof Object||"object"==typeof e?{value:e,ok:!1}:c(e)}function u(e){return void 0===e?"undefined":null===e?"null":s(e)?"bigint":e instanceof Object?e instanceof Error?"error":"function"==typeof e?"function":"object":typeof e}const h={...console},d=["log","info","error","warn","debug"].reduce(((e,t)=>(e[t]=function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];console[t]("[PageSpy] [".concat(t.toLocaleUpperCase(),"] "),...n)},e.unproxy[t]=function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];h[t]("[PageSpy] [".concat(t.toLocaleUpperCase(),"] "),...n)},e)),{unproxy:{}});const g="message",p="broadcast",f="ping",m="updateRoomInfo";var y,S=Object.freeze({__proto__:null,BROADCAST:p,CLOSE:"close",CONNECT:"connect",ERROR:"error",JOIN:"join",LEAVE:"leave",MESSAGE:g,PING:f,PONG:"pong",UPDATE_ROOM_INFO:m});function v(t,n){return{role:"client",type:t,data:{...(!(arguments.length>2&&void 0!==arguments[2])||arguments[2])&&{id:e()},...n}}}function b(e){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},b(e)}function I(e){var t=function(e,t){if("object"!=b(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var s=n.call(e,t||"default");if("object"!=b(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==b(t)?t:t+""}function O(e,t,n){return(t=I(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class C{constructor(e){O(this,"id",""),O(this,"method",""),O(this,"url",""),O(this,"requestType","xhr"),O(this,"requestHeader",null),O(this,"status",0),O(this,"statusText",""),O(this,"readyState",0),O(this,"responseReason",null),O(this,"responseType",""),O(this,"responseHeader",null),O(this,"startTime",0),O(this,"endTime",0),O(this,"costTime",0),O(this,"postData",null),O(this,"requestPayload",null),O(this,"withCredentials",!1),O(this,"lastEventId",""),this.id=e}}!function(e){e[e.UNSENT=0]="UNSENT",e[e.OPENED=1]="OPENED",e[e.HEADERS_RECEIVED=2]="HEADERS_RECEIVED",e[e.LOADING=3]="LOADING",e[e.DONE=4]="DONE"}(y||(y={}));class k{constructor(e){O(this,"reqMap",Object.create(null)),this.socketStore=e}getRequestMap(){return this.reqMap}getRequest(e){return this.reqMap[e]}removeRequest(e){delete this.reqMap[e]}createRequest(e){return e?this.reqMap[e]?(d.warn("The request object has been in store, disallow duplicate create"),!1):(this.reqMap[e]=new C(e),!0):(d.warn('The "id" is required when init request object'),!1)}setRequest(e,t){return!(!e||!t)&&(this.reqMap[e]=t,!0)}sendRequestItem(e,t){var n;if(!1!==(null===(n=k.dataProcessor)||void 0===n?void 0:n.call(k,t)))try{this.reqMap[e]||(this.reqMap[e]=t);const n=v("network",{...t},!1);this.socketStore.dispatchEvent("public-data",n),this.socketStore.broadcastMessage(n,t.readyState!==y.DONE),this.deferDeleteRequest(e)}catch(e){d.error(e.message)}}deferDeleteRequest(e){const t=this.getRequest(e);t&&t.readyState===y.DONE&&setTimeout((()=>{delete this.reqMap[e]}),3e3)}}class E{constructor(){O(this,"store",{}),O(this,"instanceStore",{})}getStore(){return this.store}resetStore(){this.store={}}getInstanceStore(){return this.instanceStore}resetInstanceStore(){this.instanceStore={}}transformToAtom(t){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const{value:s,ok:o}=l(t),r=e();if(o)return{id:r,type:u(t),value:s};if(n)try{return{id:r,type:"json",value:JSON.stringify(t)}}catch(e){return{id:r,type:"json",value:null}}return this.add(t)}get(t){const s=this.store[t],o=this.instanceStore[t];if(!s)return null;const r={},i=Object.getOwnPropertyDescriptors(s);Object.keys(i).forEach((t=>{const s=i[t];n(s,"value")&&(s.value=this.transformToAtom(s.value)),r[t]=E.getAtomOverview({atomId:e(),instanceId:o,value:s})}));const a=this.addExtraProperty(t);return{...r,...a}}getOrigin(e){const t=this.store[e];return t||null}add(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const o=e();let i=o;var a;r(a=t)&&n(a,"constructor")&&"function"==typeof a.constructor&&(i=s),this.store[o]=t,this.instanceStore[o]=i;const c=E.getSemanticValue(t);return E.getAtomOverview({atomId:o,value:c,instanceId:i})}static getAtomOverview(t){let{instanceId:n="",atomId:s,value:o}=t;return{id:e(),type:"atom",__atomId:s,instanceId:n,value:o}}static getSemanticValue(e){if(i(e))return"Object {...}";if(o(e))return"Array (".concat(e.length,")");return e.constructor.name}addExtraProperty(e){const t=this.store[e],n=this.instanceStore[e],s={};if((t instanceof String||t instanceof Number||t instanceof Boolean)&&(s["[[PrimitiveValue]]"]=this.transformToAtom(t.valueOf())),t instanceof Set){const e={};let n=0;for(const s of t)e[n++]=s;e.size=t.size,s["[[Entries]]"]=this.transformToAtom(e)}if(t instanceof Map){const e={};let n=0;for(const[s,o]of t.entries())e[n++]={key:s,value:o};e.size=t.size,s["[[Entries]]"]=this.transformToAtom(e)}var r;return(o(t)||(r=t,"function"==typeof NodeList&&"NodeList"===NodeList.name&&r instanceof NodeList||"function"==typeof HTMLCollection&&"HTMLCollection"===HTMLCollection.name&&r instanceof HTMLCollection))&&(s.length=this.transformToAtom(t.length)),null!==Object.getPrototypeOf(t)?s["[[Prototype]]"]=this.add(Object.getPrototypeOf(t),n):s.___proto___=this.transformToAtom(null),s}}const T=new E;class w{defaultConfig(){return{}}constructor(){O(this,"mergeConfig",(e=>{const t=Object.entries(e).reduce(((e,t)=>{let[n,s]=t;return this.privateKeys.includes(n)||(e[n]=s),e}),{});return this.value={...this.defaultConfig(),...t},this.value})),this.value=this.defaultConfig()}get(){return this.value}set(e,t){this.value[e]=t}}const P="page-spy-room";var j;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSING=2]="CLOSING",e[e.CLOSED=3]="CLOSED"}(j||(j={}));const R=2e3,N=Math.pow(1.5,4)*R;class q{constructor(){O(this,"events",{open:[],close:[],error:[],message:[]})}emit(e,t){this.events[e].forEach((e=>{e(t)})),"close"!==e&&"error"!==e||this.clearListeners()}onOpen(e){this.events.open.push(e)}onClose(e){this.events.close.push(e)}onError(e){this.events.error.push(e)}onMessage(e){this.events.message.push(e)}clearListeners(){Object.entries(this.events).forEach((e=>{let[,t]=e;t.splice(0)}))}}class D{getSocket(){return this.socketWrapper}updateRoomInfo(){if(this.getPageSpyConfig){var e;const{project:t,title:n}=this.getPageSpyConfig(),s=null===(e=this.getClient)||void 0===e?void 0:e.call(this).getName();this.send({type:m,content:{info:{name:s,group:t,tags:{title:n,name:s,group:t}}}},!0)}}constructor(){O(this,"socketUrl",""),O(this,"socketConnection",null),O(this,"debuggerConnection",null),O(this,"pingTimer",null),O(this,"pongTimer",null),O(this,"retryTimer",null),O(this,"isOffline",!1),O(this,"messageCapacity",0),O(this,"messages",[]),O(this,"events",{debug:[],refresh:[],"atom-detail":[],"atom-getter":[],"debugger-online":[],"database-pagination":[],"public-data":[],"harbor-clear":[]}),O(this,"retryInterval",R),O(this,"connectable",!0),O(this,"getPageSpyConfig",null),O(this,"getClient",null),this.addListener("atom-detail",D.handleResolveAtom),this.addListener("atom-getter",D.handleAtomPropertyGetter),this.addListener("debugger-online",this.handleFlushBuffer)}async init(e){try{var t,n,s,o,r;if(!e)throw Error("WebSocket url cannot be empty");this.socketWrapper.clearListeners(),this.socketWrapper.getState()===j.OPEN&&await new Promise((e=>{this.socketWrapper.onClose((()=>{this.socketWrapper.clearListeners(),e()})),this.socketWrapper.close()})),null===(t=this.socketWrapper)||void 0===t||t.onOpen((()=>{this.connectOnline()})),null===(n=this.socketWrapper)||void 0===n||n.onMessage((e=>{this.handleMessage(e)})),null===(s=this.socketWrapper)||void 0===s||s.onClose((()=>{this.connectOffline()})),null===(o=this.socketWrapper)||void 0===o||o.onError((()=>{this.connectOffline()})),this.socketUrl=e,null===(r=this.socketWrapper)||void 0===r||r.init(e)}catch(e){d.error(e.message)}}addListener(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}removeListener(e,t){const n=this.events[e]||[],s=n.indexOf(t);s>-1&&n.splice(s,1)}broadcastMessage(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=function(e){return{type:p,content:{data:e}}}(e);this.send(n,t)}close(){var e;this.connectable=!1,this.clearPing(),null===(e=this.socketWrapper)||void 0===e||e.close(),this.messages=[],Object.entries(this.events).forEach((e=>{let[t,n]=e;["atom-detail","atom-getter","debugger-online"].includes(t)||n.splice(0)}))}connectOnline(){this.retryInterval=R,this.updateRoomInfo(),this.ping()}connectOffline(){this.socketConnection=null,this.debuggerConnection=null,this.clearPing(),this.retryTimer&&clearTimeout(this.retryTimer),this.connectable&&(this.retryTimer=setTimeout((()=>{this.retryInterval<N&&(this.retryInterval*=1.5),this.retryTimer=null,this.tryReconnect()}),this.retryInterval))}tryReconnect(){this.init(this.socketUrl)}ping(){this.pingTimer&&clearTimeout(this.pingTimer),this.pongTimer&&clearTimeout(this.pongTimer),this.pingTimer=setTimeout((()=>{this.send({type:"ping",content:null}),this.pingTimer=null,this.pongTimer=setTimeout((()=>{this.connectOffline(),this.pongTimer=null}),5e3)}),5e3)}clearPing(){this.pingTimer&&(clearTimeout(this.pingTimer),this.pingTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}handlePong(){clearTimeout(this.pongTimer),this.pongTimer=null,this.ping()}handleMessage(e){var t;D.messageFilters.length&&D.messageFilters.forEach((t=>{e=t(e)}));const{CONNECT:n,MESSAGE:s,ERROR:o,JOIN:r,PING:i,PONG:a,LEAVE:c,CLOSE:l,BROADCAST:u}=S,h=JSON.parse(e.data),{type:d}=h;switch(d){case n:const{selfConnection:e,roomConnections:i}=h.content;this.socketConnection=e,this.debuggerConnection=i.find((e=>"Debugger"===e.userId))||null;break;case r:case c:const{connection:a}=h.content;"Debugger"===a.userId&&(d===r?(this.debuggerConnection=a,this.sendClientInfo()):this.debuggerConnection=null);break;case s:const{data:u,from:g,to:p}=h.content;p.address===(null===(t=this.socketConnection)||void 0===t?void 0:t.address)&&this.dispatchEvent(u.type,{source:u,from:g,to:p});break;case l:case o:this.connectOffline()}this.handlePong()}dispatchEvent(e,t){var n;["public-data"].includes(e)?this.events["public-data"].forEach((e=>{e(t)})):null===(n=this.events[e])||void 0===n||n.forEach((e=>{e.call(this,t,(e=>{this.unicastMessage(e,t.from)}))}))}unicastMessage(e,t){const n=function(e,t,n){return{type:g,content:{data:e,from:t,to:n}}}(e,this.socketConnection,t);this.send(n)}handleFlushBuffer(e){const{latestId:t}=e.source.data,n=this.messages.findIndex((e=>e.content.data.data.id===t));this.messages.slice(n+1).forEach((t=>{const n={type:g,content:{data:t.content.data,from:this.socketConnection,to:e.from}};this.send(n,!0)}))}static handleResolveAtom(e,t){let{source:n}=e;const{type:s,data:o}=n;if("atom-detail"===s){const e=T.get(o)||{};t(v("atom-detail-".concat(o),e,!1))}}static handleAtomPropertyGetter(e,t){let{source:n}=e;const{type:s,data:o}=n;if("atom-getter"===s){const{id:e,parentId:n,key:s,instanceId:i}=o,a=T.getOrigin(i),c=T.getOrigin(n);let l={};var r;if(a&&c)l=null===(r=Object.getOwnPropertyDescriptor(c,s))||void 0===r||null===(r=r.get)||void 0===r?void 0:r.call(a);else l=new Error("Getter computed failed");t(v("atom-getter-".concat(e),T.transformToAtom(l)))}}send(t){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.checkIfSend(t))try{var s;const n=t;n.createdAt=Date.now(),n.requestId=e();const o=function(e){const{ok:t,value:n}=l(e);return t?n:JSON.stringify(e,((e,t)=>l(t).value),2)}(n);null===(s=this.socketWrapper)||void 0===s||s.send(o)}catch(e){d.error("Incompatible: ".concat(e.message)),this.connectOffline()}this.checkIfCache(t,n)&&(0!==this.messageCapacity&&this.messages.length>=this.messageCapacity&&this.messages.shift(),this.messages.push(t))}checkIfSend(e){return this.socketWrapper.getState()===j.OPEN&&(!![m,f].includes(e.type)||!!this.debuggerConnection)}checkIfCache(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!this.isOffline&&!t&&![g,f].includes(e.type)}sendClientInfo(){var e;const t=null===(e=this.getClient)||void 0===e?void 0:e.call(this).makeClientInfoMsg();this.broadcastMessage({role:"client",type:"client-info",data:t},!0)}}O(D,"messageFilters",[]);const A=e=>{const t=[];return Object.entries(e).forEach((e=>{let[n,s]=e;t.push("".concat(n,"=").concat(s))})),t.join("&")};let L;const M=()=>{if(!L)throw Error("the mp sdk is not set");return L},U={setStorage:(e,t)=>null==L?void 0:L.setStorageSync(e,t),getStorage:e=>null==L?void 0:L.getStorageSync(e),removeStorage:e=>null==L?void 0:L.getStorageSync(e)};class x extends q{constructor(){super(...arguments),this.socketInstance=null,this.state=0}async init(e){this.state=j.CONNECTING;const t=M(),n=e=>{this.state=j.CLOSED,this.emit("close",e)},s=e=>{this.state=j.OPEN,this.emit("open",e)},o=e=>{this.state=j.CLOSED,this.emit("error",e)},r=e=>{this.emit("message",e)};if(x.isSingleSocket)t.connectSocket({url:e}),t.onSocketClose(n),t.onSocketError(o),t.onSocketMessage(r),t.onSocketOpen(s);else{let i=t.connectSocket({url:e,multiple:!0,complete(){}});i instanceof Promise&&(i=await i),i.onClose(n),i.onError(o),i.onOpen(s),i.onMessage(r),this.socketInstance=i}}send(e){var t;x.isSingleSocket?M().sendSocketMessage({data:e}):null===(t=this.socketInstance)||void 0===t||t.send({data:e})}close(){var e;x.isSingleSocket?M().closeSocket({}):null===(e=this.socketInstance)||void 0===e||e.close({}),this.state=j.CLOSED}getState(){return this.state}}x.isSingleSocket=!1;var H=new class extends D{constructor(){super(...arguments),this.socketWrapper=new x}onOffline(){U.removeStorage(P)}};class F{constructor(){this.name="ConsolePlugin",this.console={},this.proxyTypes=["log","info","error","warn","debug"],this.$pageSpyConfig=null}async onInit(e){let{config:t}=e;F.hasInitd||(F.hasInitd=!0,this.$pageSpyConfig=t,this.init())}init(){const e=this;this.proxyTypes.forEach((t=>{this.console[t]=console[t]||console.log||(()=>{}),Object.defineProperty(console,t,{value(){const n=getCurrentPages().pop();let s="/";n&&(s=n.route,n.options&&Object.keys(n.options).length>0&&(s+="?"+A(n.options)));for(var o=arguments.length,r=new Array(o),i=0;i<o;i++)r[i]=arguments[i];e.printLog({logType:t,logs:r,url:s})},configurable:!0,enumerable:!0,writable:!0})}))}reset(){this.proxyTypes.forEach((e=>{const t=this.console[e];t&&(console[e]=t)}))}onReset(){this.reset(),F.hasInitd=!1}printLog(e){var t,n,s;if(e.logs&&e.logs.length){const o=null===(n=null===(t=this.$pageSpyConfig)||void 0===t?void 0:t.dataProcessor)||void 0===n?void 0:n.console;if(o){this.reset();const t=o(e);if(this.init(),!1===t)return}this.console[e.logType](...e.logs);const r=v("console",{...e,time:Date.now(),logs:e.logs.map((e=>T.transformToAtom(e,!1)))});if(H.broadcastMessage(r),null===(s=this.$pageSpyConfig)||void 0===s?void 0:s.serializeData){const t={...r,data:{...r.data,logs:e.logs.map((e=>T.transformToAtom(e,!0)))}};H.dispatchEvent("public-data",t)}else H.dispatchEvent("public-data",r)}}}F.hasInitd=!1;class W{constructor(){this.name="ErrorPlugin",this.$pageSpyConfig=null,this.errorHandler=this.errorHandler.bind(this),this.unhandledRejectionHandler=this.unhandledRejectionHandler.bind(this)}onInit(e){let{config:t}=e;W.hasInitd||(W.hasInitd=!0,this.$pageSpyConfig=t,this.onUncaughtError(),this.onUnhandledRejectionError())}onReset(){const e=M();e.canIUse("offError")&&e.offError(this.errorHandler),e.canIUse("offUnhandledRejection")&&e.offUnhandledRejection(this.unhandledRejectionHandler),W.hasInitd=!1}errorHandler(e){if(W.hasInitd)if(e.stack||e.message){const{message:t,stack:n}=e;this.sendMessage(n||t,(e=>{if("object"!=typeof e)return null;const{name:t,message:n,stack:s}=Object(e);return!1===[t,n,s].every(Boolean)?null:{name:t,message:n,stack:s}})(e))}else{const e="[PageSpy] An unknown error occurred and no message or stack trace available";this.sendMessage(e,null)}}unhandledRejectionHandler(e){W.hasInitd&&this.sendMessage("UnHandled Rejection",{name:"unhandledrejection",message:e.reason})}onUncaughtError(){const e=M();e.canIUse("onError")&&e.onError(this.errorHandler)}onUnhandledRejectionError(){const e=M();e.canIUse("onUnhandledRejection")&&e.onUnhandledRejection(this.unhandledRejectionHandler)}sendMessage(e,t){var n,s,o;const r={logType:"error",logs:[e],time:Date.now(),url:"wx:light-app",errorDetail:t};if(!1===(null===(o=null===(s=null===(n=this.$pageSpyConfig)||void 0===n?void 0:n.dataProcessor)||void 0===s?void 0:s.console)||void 0===o?void 0:o.call(s,r)))return;r.logs=r.logs.map((e=>T.transformToAtom(e)));const i=v("console",r);H.dispatchEvent("public-data",i),H.broadcastMessage(i)}}W.hasInitd=!1;class _ extends k{constructor(){super(H)}}class G extends _{constructor(){super(),this.request=null,this.initProxyHandler()}reset(){if(this.request){const e=M();Object.defineProperty(e,"request",{value:this.request})}}initProxyHandler(){const n=this,s=M(),o=s.request;o&&(this.request=o,Object.defineProperty(s,"request",{value(s){const r=e();n.createRequest(r);const a=n.getRequest(r);if(a){const e=s.method||"GET",{url:c}=s;a.requestHeader=[],a.url=c,a.method=e.toUpperCase(),a.requestType="mp-request",a.status=0,a.statusText="Pending",a.startTime=Date.now(),a.readyState=y.UNSENT,i(s.header)&&(a.requestHeader=Object.entries(s.header).map((e=>{let[t,n]=e;return[String(t),String(n)]}))),a.requestHeader.push(["Content-Type","application/json"]);const{data:l}=s;if(l)if("string"==typeof l)a.requestPayload=l;else if(l instanceof ArrayBuffer)a.requestPayload="[object ArrayBuffer]";else try{a.requestPayload=JSON.stringify(l)}catch(e){a.requestPayload=t(l)}n.sendRequestItem(r,a);const u=s.success,h=s.fail,d=s.complete,g=()=>{a.endTime=Date.now(),a.costTime=a.endTime-(a.startTime||a.endTime)};return s.success=function(e){g(),a.status=(null==e?void 0:e.statusCode)||200,a.statusText="Done",a.responseHeader=[...Object.entries((null==e?void 0:e.header)||{})],a.readyState=y.HEADERS_RECEIVED,n.sendRequestItem(r,a);const t=function(e){const t=Object.keys(e),n={};for(let s=0;s<t.length;s++){const o=t[s];n[o.toLowerCase()]=e[o]}return n}((null==e?void 0:e.header)||{})["content-type"];switch(t&&(t.includes("application/json")&&(a.responseType="json"),(t.includes("text/html")||t.includes("text/plain"))&&(a.responseType="text")),a.responseType||(a.responseType="arraybuffer"),a.responseType){case"json":case"text":if("string"==typeof(null==e?void 0:e.data))try{a.response=JSON.parse(e.data)}catch(t){a.response=e.data,a.responseType="text"}else a.response=null==e?void 0:e.data;break;case"arraybuffer":a.response="[object ArrayBuffer]"}null==u||u(e)},s.fail=function(e){g(),null==h||h(e)},s.complete=function(e){a.readyState=y.DONE,n.sendRequestItem(r,a),null==d||d(e)},o(s)}return d.warn("The request object is not found on request event"),null}}))}}class V{constructor(){this.name="NetworkPlugin",this.requestProxy=null}onInit(e){let{config:t}=e;V.hasInitd||(V.hasInitd=!0,k.dataProcessor=t.dataProcessor.network,this.requestProxy=new G)}onReset(){var e;null===(e=this.requestProxy)||void 0===e||e.reset(),V.hasInitd=!1}}V.hasInitd=!1;class ${constructor(){this.name="SystemPlugin",this.$pageSpyConfig=null,this.client=null}onInit(e){let{config:t,client:n}=e;$.hasInitd||($.hasInitd=!0,this.$pageSpyConfig=t,this.client=n,this.onceInitPublicData(),H.addListener("refresh",((e,t)=>{let{source:n}=e;const{data:s}=n;if("system"===s){const e=this.getSystemInfo();if(null===e)return;t(e)}})))}onceInitPublicData(){const e=this.getSystemInfo();null!==e&&H.dispatchEvent("public-data",e)}onReset(){$.hasInitd=!1}getSystemInfo(){var e,t,n,s;const o={system:{ua:null===(e=this.client)||void 0===e?void 0:e.getName()},features:{}};return!1===(null===(s=null===(n=null===(t=this.$pageSpyConfig)||void 0===t?void 0:t.dataProcessor)||void 0===n?void 0:n.system)||void 0===s?void 0:s.call(n,o))?null:v("system",o)}}function B(e){const t=typeof e;let n=e;return"string"===t||"boolean"===t||"number"===t?n=String(e):"object"===t&&(n=e instanceof Date?e.toDateString():JSON.stringify(e)),n}$.hasInitd=!1;class J{constructor(){this.name="StoragePlugin",this.$pageSpyConfig=null,this.client=null}onInit(e){let{config:t,client:n}=e;J.hasInitd||(J.hasInitd=!0,this.$pageSpyConfig=t,this.client=n,this.initStorageProxy(),this.listenRefreshEvent())}onReset(){const e=M();Object.entries(J.originFunctions).forEach((t=>{let[n,s]=t;Object.defineProperty(e,n,{value:s})})),J.hasInitd=!1}sendRefresh(){const e=M();try{const t={type:"mpStorage",action:"get",data:e.getStorageInfoSync().keys.map((e=>({name:e,value:B(U.getStorage(e))})))};this.sendStorageItem(t)}catch(e){}}listenRefreshEvent(){H.addListener("refresh",(async e=>{let{source:t}=e;const{data:n}=t;"mpStorage"===n&&this.sendRefresh()}))}initStorageProxy(){const e=M();["setStorage","setStorageSync","removeStorage","removeStorageSync","clearStorage","clearStorageSync","batchSetStorageSync","batchSetStorage"].forEach((t=>{e[t]&&(J.originFunctions[t]=e[t])}));const t=this;Object.defineProperties(e,{setStorage:{value:e=>J.originFunctions.setStorage({...e,success(n){var s;t.sendSetItem(e.key,e.data),null===(s=e.success)||void 0===s||s.call(e,n)}})},setStorageSync:{value(e,n){var s;try{let o;if("mp-alipay"!==(null===(s=t.client)||void 0===s?void 0:s.info.browserType)||t.client.info.framework&&"unknown"!==t.client.info.framework){const s=e;o=J.originFunctions.setStorageSync(s,n),t.sendSetItem(s,n)}else{const n=e;o=J.originFunctions.setStorageSync(n),t.sendSetItem(n.key,n.data)}return o}catch(t){throw d.error("Failed to set storage synchronously: ".concat(e)),t}}},removeStorage:{value:e=>J.originFunctions.removeStorage({...e,success(n){var s;t.sendRemoveItem(e.key),null===(s=e.success)||void 0===s||s.call(e,n)}})},removeStorageSync:{value(e){try{const n=J.originFunctions.removeStorageSync(e);return t.sendRemoveItem(e),n}catch(t){throw d.error("Failed to remove storage synchronously: ".concat(e)),t}}},clearStorage:{value:e=>J.originFunctions.clearStorage({...e,success(n){var s;t.sendClearItem(),null===(s=e.success)||void 0===s||s.call(e,n)}})},clearStorageSync:{value(){try{const e=J.originFunctions.clearStorageSync();return t.sendClearItem(),e}catch(e){throw d.error("Failed to clear storage synchronously"),e}}}}),e.canIUse("batchSetStorageSync")&&Object.defineProperty(e,"batchSetStorageSync",{value(e){try{const n=J.originFunctions.batchSetStorageSync(e);return e.forEach((e=>{t.sendSetItem(e.key,e.value)})),n}catch(t){throw d.error("Failed to batch set storage synchronously: ".concat(JSON.stringify(e.map((e=>e.key))))),t}}}),e.canIUse("batchSetStorage")&&Object.defineProperty(e,"batchSetStorage",{value:e=>J.originFunctions.batchSetStorage({...e,success(n){var s;e.kvList.forEach((e=>{t.sendSetItem(e.key,e.value)})),null===(s=e.success)||void 0===s||s.call(e,n)}})})}sendSetItem(e,t){this.sendStorageItem({type:"mpStorage",action:"set",name:e,value:B(t)})}sendRemoveItem(e){this.sendStorageItem({type:"mpStorage",action:"remove",name:e})}sendClearItem(){this.sendStorageItem({type:"mpStorage",action:"clear"})}sendStorageItem(e){var t,n,s;if(!1===(null===(s=null===(n=null===(t=this.$pageSpyConfig)||void 0===t?void 0:t.dataProcessor)||void 0===n?void 0:n.storage)||void 0===s?void 0:s.call(n,e)))return;const o=v("storage",e);H.dispatchEvent("public-data",o),H.broadcastMessage(o,!0)}}J.hasInitd=!1,J.originFunctions={};const z=e=>!1===e?["http://","ws://"]:["https://","wss://"];class K{constructor(e,t){if(this.config=e,this.client=t,!e.get().api)throw Error("The api base url cannot be empty")}get base(){return this.config.get().api}createRoom(){const{enableSSL:e,project:t,title:n,useSecret:s,secret:o}=this.config.get(),r=z(e),i=this.client.getName(),a=A({group:t,title:n,name:encodeURIComponent(i)});return(e=>t=>new Promise(((n,s)=>{e({...t,success(e){n(e)},fail(e){s(e)}})})))(M().request)({url:"".concat(r[0]).concat(this.base,"/api/v1/room/create?").concat(a),method:"POST",data:JSON.stringify({useSecret:s,secret:o})}).then((e=>{var t;const{name:n,address:s}=(null===(t=e.data)||void 0===t?void 0:t.data)||{};return{roomUrl:this.getRoomUrl(s),address:s,name:n}}),(e=>{throw Error("Request create room failed: ".concat(e.message))}))}getRoomUrl(t){const n=this.config.get(),s=z(n.enableSSL);return"".concat(s[1]).concat(this.base,"/api/v1/ws/room/join?").concat(A({address:t,name:"client:".concat(e()),userId:"Client",forceCreate:!0,useSecret:n.useSecret,secret:n.secret}))}}class Q extends w{constructor(){super(...arguments),this.privateKeys=["secret"]}defaultConfig(){return{api:"",project:"default",title:"",enableSSL:null,disabledOnProd:!0,disabledPlugins:[],singletonSocket:!1,messageCapacity:1e3,useSecret:!1,secret:"",serializeData:!1,dataProcessor:{}}}}class X{constructor(e){if(this.root=null,this.request=null,this.name="",this.address="",this.roomUrl="",this.socketStore=H,this.config=new Q,this.cacheTimer=null,X.instance)return d.warn("Cannot initialize PageSpy multiple times"),X.instance;const t=this.config.mergeConfig(e);t.singletonSocket&&(x.isSingleSocket=!0);const n=M();n.canIUse("getAccountInfoSync")&&n.getAccountInfoSync&&"release"===n.getAccountInfoSync().miniProgram.envVersion&&!1!==t.disabledOnProd?d.warn("PageSpy is not allowed on release env of mini program"):(X.instance=this,this.request=new K(this.config,X.client),this.updateConfiguration(),X.client.plugins=X.pluginsWithOrder.map((e=>e.name)),this.triggerPlugins("onInit",{socketStore:H,config:t,atom:T,client:X.client}),this.init())}updateConfiguration(){const{messageCapacity:e,useSecret:t}=this.config.get();if(!0===t){const e=U.getStorage(P),t=(null==e?void 0:e.secret)||function(){const e=Math.floor(1e6*Math.random());return String(e).padStart(6,"0")}();this.config.set("secret",t),d.log("Room Secret: ".concat(t))}H.connectable=!0,H.getPageSpyConfig=()=>this.config.get(),H.getClient=()=>X.client,H.messageCapacity=e}async init(){const e=M(),t=this.config.get(),n=U.getStorage(P);if(n&&"object"==typeof n){const{name:e,address:s,roomUrl:o,project:r}=n;t.project!==r?await this.createNewConnection():(this.name=e,this.address=s,this.roomUrl=o,this.useOldConnection())}else await this.createNewConnection();e.canIUse("onAppShow")&&e.onAppShow((()=>{const e=H.getSocket().getState();e!==j.CLOSED&&e!==j.CLOSING||this.useOldConnection()})),d.log("Plugins inited")}async createNewConnection(){if(!this.request)return void d.error("Cannot get the Request");const e=await this.request.createRoom();this.name=e.name,this.address=e.address,this.roomUrl=e.roomUrl,this.refreshRoomInfo(),H.init(e.roomUrl)}useOldConnection(){this.refreshRoomInfo(),H.init(this.roomUrl)}refreshRoomInfo(){this.saveSession(),this.cacheTimer=setInterval((()=>{H.getSocket().getState()===j.OPEN&&this.saveSession()}),15e3),d.log("Room ID: ".concat(this.address.slice(0,4)))}saveSession(){const{name:e,address:t,roomUrl:n,config:s}=this,{useSecret:o,secret:r,project:i}=s.get(),a={name:e,address:t,roomUrl:n,project:i,useSecret:o,secret:r};U.setStorage(P,a)}triggerPlugins(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];const{disabledPlugins:r}=this.config.get();X.pluginsWithOrder.forEach((t=>{var s;o(r)&&r.length&&r.includes(t.name)||null===(s=t[e])||void 0===s||s.apply(t,n)}))}abort(){this.triggerPlugins("onReset"),H.close(),X.instance=null}updateRoomInfo(e){if(!e)return;const{project:t,title:n}=e;t&&this.config.set("project",String(t)),n&&this.config.set("title",String(n)),H.updateRoomInfo()}getDebugLink(){const e=this.config.get();let t="".concat(!1===e.enableSSL?"http://":"https://").concat(e.api,"/#/devtools?address=").concat(encodeURIComponent(this.address));return e.useSecret&&(t+="&secret=".concat(e.secret)),t}async showPanel(){const e=M(),t=this,n=[{text:"PageSpy 房间号:"+this.address.slice(0,4),action(){e.setClipboardData({data:t.getDebugLink(),success(){e.showToast({title:"复制成功",icon:"success"})}})}}];X.pluginsWithOrder.forEach((e=>{if(e.onActionSheet){const t=e.onActionSheet();(null==t?void 0:t.length)&&n.push(...t)}})),e.showActionSheet({title:"PageSpy Device ID:"+(this.address.slice(0,4)||"--"),itemColor:"#b67cff",itemList:n.map((e=>e.text)),success(e){const t=n[e.tapIndex];t.action&&t.action()}})}static get pluginsWithOrder(){return[...X.plugins.pre,...X.plugins.normal,...X.plugins.post]}static registerPlugin(e){var t;e&&("function"!=typeof(t=e)||void 0===t.prototype?e.name?X.pluginsWithOrder.some((t=>t.name===e.name))?d.info("The ".concat(e.name,' has registered. Consider the following reasons:\n - Duplicate register one same plugin;\n - Plugin\'s "name" conflict with others, you can print all registered plugins by "PageSpy.plugins";')):X.plugins[e.enforce||"normal"].push(e):d.error("The ".concat(e.constructor.name,' plugin should provide a "name" property')):d.error("PageSpy.registerPlugin() expect to pass an instance, not a class"))}}var Y;X.instance=null,X.plugins={pre:[],normal:[],post:[]},[new F,new W,new V,new J,new $].forEach((e=>{X.registerPlugin(e)})),Y=my,L=Y,U.getStorage=e=>{const t=my.getStorageSync({key:e});if(t.success)return t.data},U.setStorage=(e,t)=>my.setStorageSync({key:e,data:t}),U.removeStorage=e=>my.removeStorageSync({key:e});const Z=my.getSystemInfoSync();X.client=new class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{osType:"unknown",osVersion:"unknown",browserType:"unknown",browserVersion:"unknown",framework:"unknown",isDevTools:!1,sdk:"unknown",sdkVersion:"0.0.0"};O(this,"plugins",[]),O(this,"_name",""),this.info=e}makeClientInfoMsg(){return{sdk:this.info.sdk,isDevTools:this.info.isDevTools,ua:this.getName(),plugins:this.plugins}}getName(){if(!this._name){const{ua:e,osType:t,osVersion:n,browserType:s,browserVersion:o}=this.info;this._name=e||"".concat(t,"/").concat(n," ").concat(s,"/").concat(o)}return this._name}}({sdk:"mp-alipay",osType:Z.platform.toLowerCase(),browserType:"mp-alipay",osVersion:Z.system,browserVersion:Z.version,sdkVersion:"2.0.0-beta.0"}),D.messageFilters.push((e=>e.data));export{X as default}; | ||
import PageSpy, { setMPSDK, utilAPI, Client, SocketStoreBase } from '@huolala-tech/page-spy-mp-base'; | ||
export { default } from '@huolala-tech/page-spy-mp-base'; | ||
setMPSDK(my); | ||
// alipay toxic storage api... | ||
utilAPI.getStorage = key => { | ||
const res = my.getStorageSync({ | ||
key | ||
}); | ||
if (res.success) { | ||
return res.data; | ||
} | ||
return undefined; | ||
}; | ||
utilAPI.setStorage = (key, value) => { | ||
return my.setStorageSync({ | ||
key, | ||
data: value | ||
}); | ||
}; | ||
utilAPI.removeStorage = key => { | ||
return my.removeStorageSync({ | ||
key | ||
}); | ||
}; | ||
utilAPI.showActionSheet = params => { | ||
return my.showActionSheet({ | ||
...params, | ||
items: params.itemList, | ||
success: res => { | ||
var _params$success; | ||
(_params$success = params.success) === null || _params$success === void 0 || _params$success.call(params, { | ||
tapIndex: res.index | ||
}); | ||
} | ||
}); | ||
}; | ||
const info = my.getSystemInfoSync(); | ||
PageSpy.client = new Client({ | ||
sdk: 'mp-alipay', | ||
osType: info.platform.toLowerCase(), | ||
browserType: 'mp-alipay', | ||
osVersion: info.system, | ||
browserVersion: info.version, | ||
sdkVersion: "2.0.0-beta.1" | ||
}); | ||
SocketStoreBase.messageFilters.push(data => { | ||
return data.data; | ||
}); | ||
//# sourceMappingURL=index.min.js.map |
{ | ||
"name": "@huolala-tech/page-spy-alipay", | ||
"version": "2.0.0-beta.0", | ||
"version": "2.0.0-beta.1", | ||
"description": "A developer tool for debugging alipay miniprogram", | ||
@@ -31,5 +31,4 @@ "license": "MIT", | ||
"dependencies": { | ||
"@huolala-tech/page-spy-base": "^2.0.0-beta.0", | ||
"@huolala-tech/page-spy-mp-base": "^2.0.0-beta.0", | ||
"@huolala-tech/page-spy-types": "^2.0.0-beta.0" | ||
"@huolala-tech/page-spy-mp-base": "^2.0.0-beta.1", | ||
"@huolala-tech/page-spy-types": "^2.0.0-beta.1" | ||
}, | ||
@@ -68,3 +67,3 @@ "devDependencies": { | ||
}, | ||
"gitHead": "a5c943d5a756b54c897a33c405da2727c658e8ab" | ||
"gitHead": "61b2ee5634aa81a103aabe37386a94b3258a13f5" | ||
} |
@@ -15,57 +15,19 @@ [npm-image]: https://img.shields.io/npm/v/@huolala-tech/page-spy-alipay?logo=npm&label=version | ||
> [!CAUTION] | ||
> When submitting the mini program for review, be sure to delete the SDK in the code, otherwise the review will fail. | ||
## Usage | ||
```ts | ||
import PageSpy from '@huolala-tech/page-spy-alipay' | ||
import PageSpy from '@huolala-tech/page-spy-alipay'; | ||
const pageSpy = new PageSpy(config?: InitConfig) | ||
const pageSpy = new PageSpy({ | ||
api: 'example.com', | ||
}); | ||
``` | ||
## `InitConfig` definition | ||
Please refer to the official documentation for more details [PageSpy API](https://www.pagespy.org/#/docs/api)。 | ||
Except for the `api` parameter is required, all others parameters are optional: | ||
## Other SDKs | ||
```ts | ||
interface InitConfig { | ||
// Server domain, must be provided。 | ||
// Example:"example.com" | ||
api: string; | ||
If you are using UniAPP or Taro, we recommend using below SDKs respectively: | ||
// "project" is an aggregation of information that can be searched in the room list on the debug side. | ||
// default: 'default' | ||
project?: string; | ||
// "title" is a user-defined parameter that can be used to distinguish the current debugging client, | ||
// and the corresponding information is displayed under the "device id" in each debugging connection panel. | ||
// default: '--' | ||
title?: string; | ||
// Manually specify the scheme of the PageSpy service. | ||
// Note that except for development environment, mini-program requires the scheme to be set to "https", so: | ||
// - By default, pass the value undefined or null, the SDK will parse it to TRUE; | ||
// - true: the SDK will access the PageSpy service via ["https://", "wss://"]; | ||
// - false: the SDK will access the PageSpy service via ["http://", "wss://"]. | ||
enableSSL?: boolean | null; | ||
// Disable pagespy on release environment. | ||
// - true (Default): only allow pagespy init on develop and trail environment. | ||
// - false: allow using in release environment | ||
disabledOnProd?: boolean | null; | ||
// All internal plugins are carried with PageSpy by default out of the box. | ||
// You can disable some plugins as needed. | ||
disabledPlugins?: (InternalPlugins | string)[]; | ||
} | ||
type InternalPlugins = | ||
| 'ConsolePlugin' | ||
| 'ErrorPlugin' | ||
| 'NetworkPlugin' | ||
| 'StoragePlugin' | ||
| 'SystemPlugin'; | ||
``` | ||
For more details of mini-program usage, please refer to [Mini-Program Usage](https://github.com/HuolalaTech/page-spy/wiki/%E5%B0%8F%E7%A8%8B%E5%BA%8F%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E) | ||
- [@huolala-tech/page-spy-uniapp](https://www.npmjs.com/package/@huolala-tech/page-spy-uniapp) | ||
- [@huolala-tech/page-spy-taro](https://www.npmjs.com/package/@huolala-tech/page-spy-taro) |
Sorry, the diff of this file is not supported yet
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
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
2
0
5276
51
33