UNPKG

@zeppos/zml

Version:

A Mini Library of ZeppOS MiniApp

2 lines (1 loc) 21.3 kB
const e=Object.prototype.hasOwnProperty,t={init(){this.plugins=[],this.settings={},this.mixins=[]},set(e,t){if(1===arguments.length)return this.settings[e];this.settings[e]=t},use(e,...t){return"function"==typeof e?this.plugins.push({handler:e,args:t}):"object"==typeof e&&this.mixins.push({handler:e,args:t}),this},handle(e){this.plugins.forEach((t=>{if(t&&"function"==typeof t.handler)try{const s=t.handler.call(this,e,...t.args);"object"==typeof s&&this.mixins.push({handler:s,args:[]})}catch(e){}})),this.mixins.forEach((({handler:{onInit:t,onPause:s,build:n,onResume:i,onDestroy:r,onCreate:a,...o},args:h})=>{Object.assign(e,o)}))}},s={onChange(e){return e?(settings.settingsStorage.addListener("change",e),this):this},offChange(){return settings.settingsStorage.removeListener("change"),this},getItem:e=>settings.settingsStorage.getItem(e),setItem:(e,t)=>settings.settingsStorage.setItem(e,t),clear:()=>settings.settingsStorage.clear(),removeItem(e){settings.settingsStorage.removeItem(e)},getAll:()=>settings.settingsStorage.toObject()},n=setTimeout,i=clearTimeout,r=Promise;function a(){const e={canceled:!1};return e.promise=new r((function(t,s){e.resolve=t,e.reject=s})),e.cancel=()=>{e.canceled=!0,e.reject(new Error("Task canceled"))},e}function o({state:e={},onInit:t,onRun:s,onDestroy:n,...i}={}){const r={state:e,...i,onInit(e){for(let t=0;t<=o.mixins.length-1;t++){const s=o.mixins[t];s&&s.handler.onInit?.apply(this,e)}t?.apply(this,e)},onRun(e){for(let t=0;t<=o.mixins.length-1;t++){const s=o.mixins[t];s&&s.handler.onRun?.apply(this,e)}s?.apply(this,e)},onDestroy(e){n?.apply(this,e);for(let t=o.mixins.length-1;t>=0;t--){const s=o.mixins[t];s&&s.handler.onDestroy?.apply(this,e)}}};return o.handle(r),r}var h,d;function l(){return f()&&u()}function c(){return f()&&p()}function u(){return"undefined"!=typeof hmApp}function p(){return"undefined"!=typeof __$$R$$__}function f(){return u()||p()}function g(){return"undefined"!=typeof messaging}h=o,d=t,Object.getOwnPropertyNames(d).forEach((function(t){if(!e.call(h,t)){var s=Object.getOwnPropertyDescriptor(d,t);Object.defineProperty(h,t,s)}})),o.init(),o.use((function(){return{onInit(){this.logger=Logger.getLogger(sideService.appInfo.app.appName),this.logger.scope=sideService.appInfo.app.appName,this.logger.name="side-service",this.log=(...e)=>{this.logger.log(...e)},this.error=(...e)=>{e[0]instanceof Error?this.logger.error(...e):this.logger.error({},...e)},this.debug=(...e)=>{this.logger.debug(...e)}}}})),o.use((function(){return{onInit(){this.settings=s,this._onSettingsChange=this.onSettingsChange?.bind(this),s.onChange(this._onSettingsChange),"undefined"!=typeof sideService&&sideService.launchReasons.settingsChanged&&function(){const e=a();return n(e.resolve,1),e.promise}().then((()=>{this._onSettingsChange?.(sideService.launchArgs)}))},onDestroy(){this._onSettingsChange&&s.offChange(this._onSettingsChange)}}}));let y=null;y="undefined"!=typeof __$$R$$__?__$$R$$__:()=>({});let m=null;l()?m=DeviceRuntimeCore.HmLogger:c()?m=y("@zos/utils").log:g()&&"undefined"!=typeof Logger&&(m=Logger);class I{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}off(e,t){if(e)if(t){const s=this.listeners.get(e);if(!s)return;const n=s.findIndex((e=>e===t));n>=0&&s.splice(n,1)}else this.listeners.delete(e)}emit(e,...t){for(let s of this.listeners.get(e)??[])s&&s(...t)}clear(){this.listeners.clear()}once(e,t){const s=(...n)=>{this.off(e,s),t(...n)};this.on(e,s)}count(e){return(this.listeners.get(e)??[]).length}}let T=null;l()?T=hmBle:c()&&(T=y("@zos/ble"));const b=Buffer;function S(e){return w(function(e){return JSON.stringify(e)}(e))}function k(e){return t=L(e),JSON.parse(t);var t}function w(e){return b.from(e,"utf-8")}function L(e){return e.toString("utf-8")}function v(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}function C(e){return t=function(e){return b.from(e)}(e),t.toString("hex");var t}function q(e){return"object"==typeof e&&!b.isBuffer(e)&&!Array.isArray(e)&&null!==e}const U=f()?m.getLogger("device-message"):m.getLogger("side-message"),B=void 0,E="json",x="text",R="bin";function P(e){switch(e.toLowerCase()){case E:return 2;case x:return 1;case R:return 3;case"empty":return 0;default:return 3}}let D=1e4;function j(){return D++}let F=1e3;function O(){return F++}class _ extends I{constructor(e,t,s,n){super(),this.id=e,this.type=t,this.ctx=n,this.chunks=[],this.count=-1,this.finishChunk=null,this.size=s,this.receivedSize=0}addChunk(e){this.receivedSize+=e.payloadLength,1===e.opCode&&(this.count=e.seqId+1,this.finishChunk=e),e.payloadLength===e.payload.byteLength?(this.chunks.push(e),this.checkIfReceiveAllChunks()):this.emit("error",Error(`receive chunk data length error, expect ${e.payloadLength} but ${e.payload.byteLength}`))}checkIfReceiveAllChunks(){if(this.count!==this.chunks.length)return;if(!this.finishChunk)return;if(this.size!==this.receivedSize)return;this.chunks.sort(((e,t)=>e.seqId-t.seqId));let e=[];for(let t=0;t<this.count;t++){const s=this.chunks[t];if(!s||s.seqId!==t)return e=null,this.releaseBuf(),void this.emit("error",Error("receive data error"));e.push(s.payload)}this.chunks=[],this.finishChunk.payload=b.concat(e),e=null,this.finishChunk.payloadLength=this.finishChunk.payload.byteLength,this.finishChunk.totalLength===this.finishChunk.payloadLength?this.emit("data",this.finishChunk):this.emit("error",Error(`receive full data length error, expect ${this.finishChunk.payloadLength} but ${this.finishChunk.payload.byteLength}`))}releaseBuf(){this.chunks=[],this.finishChunk=null,this.count=0,this.size=0,this.receivedSize=0}}class A{constructor(){this.sessions=new Map}key(e){return`${e.id}:${e.type}`}newSession(e,t,s,n){const i=new _(e,t,s,n);return this.sessions.set(this.key(i),i),i}destroy(e){e.releaseBuf(),this.sessions.delete(this.key(e))}has(e,t){return this.sessions.has(this.key({id:e,type:t}))}getById(e,t){return this.sessions.get(this.key({id:e,type:t}))}clear(){this.sessions.clear()}}class $ extends Error{constructor(e,t){super(t),this.code=e,this.reason=t}}class z{constructor(){this.set=new Set}add(e){this.set.add(e)}runAll(...e){this.set.forEach((t=>{t&&t(...e)}))}remove(e){e?this.set.delete(e):this.set.clear()}}m.getLogger("message-builder");const M="hmrpcv1",H=new z,N=new z,J=new z,W=new class extends I{constructor({appId:e=0,appDevicePort:t=20,appSidePort:s=0,ble:n=(f()?T:void 0)}={appId:0,appDevicePort:20,appSidePort:0,ble:f()?T:void 0}){super(),this.isDevice=f(),this.isSide=!this.isDevice,this.appId=e,this.appDevicePort=t,this.appSidePort=s,this.ble=n,this.sendMsg=this.getSafeSend(),this.chunkSize=3584,this.handlers=new Map,this.shakeTask=null,this.waitingShakePromise=null,this.shakeStatus=1,this.shakeTimer=0,this.sessionMgr=new A,this.on("response",(e=>{this.onResponse(e)})),n?.addListener((e=>{this.emit("bleStatusChanged",e)})),this.on("bleStatusChanged",(e=>{if(!e){U.error("ble disconnect"),this.shakeTask&&(this.shakeTask.reject(new $(2,"ble disconnect")),this.shakeStatus=4);for(const[e,t]of Object.entries(this.handlers))t.task.reject(new $(2,"ble disconnect"));this.handlers.clear()}}))}fork(e=5e3){if(2===this.shakeStatus)return this.waitingShakePromise;this.shakeTask=a(),this.waitingShakePromise=this.shakeTask.promise,this.shakeStatus=1,this.clearShakeTimer(),this.shakeTimer=n((()=>{this.shakeStatus=4,this.shakeTask.reject(new $(1,"shake timeout"))}),e);try{this.errorIfBleDisconnect()}catch(e){return U.error("error ble disconnect %j",e),this.shakeTask.reject(new $(2,"ble disconnect")),this.shakeStatus=4,this.waitingShakePromise}return this.shakeStatus=2,this.sendShake(),this.waitingShakePromise}clearShakeTimer(){this.shakeTimer&&i(this.shakeTimer),this.shakeTimer=0}getMessageSize(){return 3600}getMessagePayloadSize(){return 3584}getMessageHeaderSize(){return 16}buf2Json(e){return k(e)}json2Buf(e){return S(e)}now(e=Date.now()){return function(e=Date.now()){return e%1e7}(e)}connect(e){this.on("message",(e=>{this.onMessage(e)})),this.ble&&this.ble.createConnect(((e,t,s)=>{this.onFragmentData(t)})),e&&e(this)}disConnect(e){this.sendClose(),this.off("message"),this.handlers.clear(),this.ble&&this.ble.disConnect(),e&&e(this)}listen(e){this.appSidePort=globalThis.getApp().port2,messaging&&messaging.peerSocket.addListener("message",(e=>{this.onMessage(e)})),this.waitingShakePromise=r.resolve(),e&&e(this)}buildBin(e){if(e.payload.byteLength>this.chunkSize)throw new Error(`${e.payload.byteLength} greater than max size of ${this.chunkSize}`);const t=this.getMessageHeaderSize()+e.payload.byteLength;let s=b.alloc(t),n=0;return s.writeUInt8(e.flag,n),n+=1,s.writeUInt8(e.version,n),n+=1,s.writeUInt16LE(e.type,n),n+=2,s.writeUInt16LE(e.port1,n),n+=2,s.writeUInt16LE(e.port2,n),n+=2,s.writeUInt32LE(e.appId,n),n+=4,s.writeUInt32LE(e.extra,n),n+=4,s.fill(e.payload,n,e.payload.byteLength+n),s}buildShake(){return this.buildBin({flag:1,version:1,type:1,port1:this.appDevicePort,port2:this.appSidePort,appId:this.appId,extra:0,payload:b.from([this.appId])})}sendShake(){U.info("shake send");const e=this.buildShake();this.sendMsg(e)}buildClose(){return this.buildBin({flag:1,version:1,type:2,port1:this.appDevicePort,port2:this.appSidePort,appId:this.appId,extra:0,payload:b.from([this.appId])})}sendClose(){const e=this.buildClose();this.sendMsg(e)}readBin(e){const t=b.from(e);let s=0;const n=t.readUInt8(s);s+=1;const i=t.readUInt8(s);s+=1;const r=t.readUInt16LE(s);s+=2;const a=t.readUInt16LE(s);s+=2;const o=t.readUInt16LE(s);s+=2;const h=t.readUInt32LE(s);s+=4;const d=t.readUInt32LE(s);return s+=4,{flag:n,version:i,type:r,port1:a,port2:o,appId:h,extra:d,payload:t.subarray(s)}}buildData(e,t={}){return this.buildBin({flag:1,version:1,type:4,port1:this.appDevicePort,port2:this.appSidePort,appId:this.appId,extra:0,...t,payload:e})}sendBin(e,t=B){if(t&&U.warn("[RAW] [S] send size=%d bin=%s",e.byteLength,C(e.buffer)),!this.ble.send(e.buffer,e.byteLength))throw Error("send message error")}sendBinBySide(e,t=B){t&&U.warn("[RAW] [S] send size=%d bin=%s",e.byteLength,C(e.buffer)),messaging.peerSocket.send(e.buffer)}getSafeSend(){return this.isDevice?this.sendBin.bind(this):this.sendBinBySide.bind(this)}sendHmProtocol({requestId:e,dataBin:t,type:s,contentType:n,dataType:i},{messageType:r=4}={}){const a=3518,o=t.byteLength;let h=0;const d=b.alloc(a),l=e||j(),c=O();let u=0;const p=Math.ceil(o/a);function f(){return u++}for(let e=1;e<=p;e++){if(this.errorIfBleDisconnect(),e===p){const e=o-h,a=b.alloc(0+e);t.copy(a,0,h,h+e),h+=e,this.sendDataWithSession({traceId:l,spanId:c,seqId:f(),payload:a,type:s,opCode:1,totalLength:o,contentType:n,dataType:i},{messageType:r});break}t.copy(d,0,h,h+a),h+=a,this.sendDataWithSession({traceId:l,spanId:c,seqId:f(),payload:d,type:s,opCode:0,totalLength:o,contentType:n,dataType:i},{messageType:r})}}sendJson({requestId:e=0,json:t,type:s=1,contentType:n,dataType:i}){const r=S(t),a=e||j();this.sendHmProtocol({requestId:a,dataBin:r,type:s,contentType:n,dataType:i})}sendBuf({requestId:e=0,buf:t,type:s=1,contentType:n,dataType:i}){const r=e||j();return this.sendHmProtocol({requestId:r,dataBin:t,type:s,contentType:n,dataType:i})}sendText({requestId:e=0,text:t,type:s=1,contentType:n,dataType:i}){const r=w(t),a=e||j();return this.sendHmProtocol({requestId:a,dataBin:r,type:s,contentType:n,dataType:i})}sendDataWithSession({traceId:e,spanId:t,seqId:s,payload:n,type:i,opCode:r,totalLength:a,contentType:o,dataType:h},{messageType:d}){const l=this.buildPayload({traceId:e,spanId:t,seqId:s,totalLength:a,type:i,opCode:r,payload:n,contentType:o,dataType:h});let c=this.isDevice?this.buildData(l,{type:d}):l;this.sendMsg(c)}buildPayload(e){const t=66+e.payload.byteLength;let s=b.alloc(t),n=0;return s.writeUInt32LE(e.traceId,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(e.spanId,n),n+=4,s.writeUInt32LE(e.seqId,n),n+=4,s.writeUInt32LE(e.totalLength,n),n+=4,s.writeUInt32LE(e.payload.byteLength,n),n+=4,s.writeUInt8(e.type,n),n+=1,s.writeUInt8(e.opCode,n),n+=1,s.writeUInt32LE(this.now(),n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.writeUInt8(e.contentType,n),n+=1,s.writeUInt8(e.dataType,n),n+=1,s.writeUInt16LE(0,n),n+=2,s.writeUInt32LE(0,n),n+=4,s.writeUInt32LE(0,n),n+=4,s.fill(e.payload,n,e.payload.byteLength+n),s}readPayload(e){const t=b.from(e);let s=0;const n=t.readUInt32LE(s);s+=4;const i=t.readUInt32LE(s);s+=4;const r=t.readUInt32LE(s);s+=4;const a=t.readUInt32LE(s);s+=4;const o=t.readUInt32LE(s);s+=4;const h=t.readUInt32LE(s);s+=4;const d=t.readUInt8(s);s+=1;const l=t.readUInt8(s);s+=1;const c=t.readUInt32LE(s);s+=4;const u=t.readUInt32LE(s);s+=4;const p=t.readUInt32LE(s);s+=4;const f=t.readUInt32LE(s);s+=4;const g=t.readUInt32LE(s);s+=4;const y=t.readUInt32LE(s);s+=4;const m=t.readUInt32LE(s);s+=4;const I=t.readUInt8(s);s+=1;const T=t.readUInt8(s);s+=1;const S=t.readUInt16LE(s);s+=2;const k=t.readUInt32LE(s);s+=4;const w=t.readUInt32LE(s);return s+=4,{traceId:n,parentId:i,spanId:r,seqId:a,totalLength:o,payloadLength:h,payloadType:d,opCode:l,contentType:I,dataType:T,timestamp1:c,timestamp2:u,timestamp3:p,timestamp4:f,timestamp5:g,timestamp6:y,timestamp7:m,extra1:S,extra2:k,extra3:w,payload:t.subarray(s)}}onFragmentData(e){const t=this.readBin(e);this.emit("raw",e),1===t.flag&&1===t.type?(this.appSidePort=t.port2,U.info("shake success appSidePort=>",t.port2),this.emit("shake:response",t),this.clearShakeTimer(),this.shakeTask.resolve(),this.shakeStatus=3):1===t.flag&&4===t.type||1===t.flag&&5===t.type?(this.emit("message",t.payload),this.emit("read",t)):1===t.flag&&6===t.type?this.emit("log",t.payload):0===t.flag||1===t.flag&&2===t.type&&(this.appSidePort=0)}errorIfBleDisconnect(){if(f()&&!this.ble.connectStatus())throw new $(2,"ble disconnect")}errorIfSideServiceDisconnect(){if(f()&&!this.appSidePort)throw new $(3,"side service is not running")}getRequestCount(){return this.handlers.size}onResponse(e){const t=this.handlers.get(e.traceId).handler;t&&t(e)}onMessage(e){const t=this.readPayload(e);let s=this.sessionMgr.getById(t.traceId,t.payloadType);s||(s=this.sessionMgr.newSession(t.traceId,t.payloadType,t.totalLength,this),s.on("data",(e=>{1===e.opCode&&(1===e.payloadType?this.emit("request",{request:e,response:({data:t,dataType:s})=>{s=void 0!==s?P(s):e.dataType,this.response({requestId:e.traceId,contentType:e.contentType,dataType:s,data:t})}}):2===e.payloadType?this.emit("response",e):3===e.payloadType&&this.emit("call",e),this.emit("data",e),this.sessionMgr.destroy(s))})),s.on("error",(e=>{this.sessionMgr.destroy(s),this.emit("error",e)}))),s.addChunk(t)}request(e,t){try{this.errorIfBleDisconnect()}catch(e){return U.error("error ble disconnect %j",e),r.reject(e)}return this.waitingShakePromise.then((()=>{this.errorIfBleDisconnect(),this.errorIfSideServiceDisconnect();let s=R;"string"==typeof e?s=x:q(e)?s=E:(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||b.isBuffer(e))&&(s=R);const r={timeout:6e4,contentType:s,dataType:s},o=j(),h=a();t=Object.assign(r,t);let d=n((()=>{d=null,h.reject(new $(4,`request id=${o} timeout in ${t.timeout}ms`))}),t.timeout);return this.handlers.set(o,{handler:({traceId:e,payload:t,dataType:s})=>{let n;switch(this.errorIfBleDisconnect(),this.errorIfSideServiceDisconnect(),s){case 1:n=L(t);break;case 3:default:n=t;break;case 2:n=k(t)}U.info("response id=>%d",o),h.resolve(n)},task:h}),U.info("request id=%d",o),b.isBuffer(e)?this.sendBuf({requestId:o,buf:e,type:1,contentType:3,dataType:P(t.dataType)}):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?this.sendBuf({requestId:o,buf:b.from(e),type:1,contentType:3,dataType:P(t.dataType)}):2===P(t.contentType)?this.sendJson({requestId:o,json:e,type:1,contentType:2,dataType:P(t.dataType)}):1===P(t.contentType)?this.sendText({requestId:o,text:e,type:1,contentType:1,dataType:P(t.dataType)}):this.sendBuf({requestId:o,buf:b.from(e),type:1,contentType:3,dataType:P(t.dataType)}),h.promise.catch((e=>{throw U.error("request id=%d %d %j",o,e.code,e.reason),e})).finally((()=>{d&&(i(d),d=null),this.handlers.get(o)?this.handlers.delete(o):U.warn("release request id=>%d error",o)}))}))}response({requestId:e,contentType:t,dataType:s,data:n}){3===s?this.sendBuf({requestId:e,buf:n,type:2,contentType:t,dataType:s}):1===s?this.sendText({requestId:e,text:n,type:2,contentType:t,dataType:s}):2===s?this.sendJson({requestId:e,json:n,type:2,contentType:t,dataType:s}):this.sendBuf({requestId:e,buf:n,type:2,contentType:t,dataType:3})}call(e){let t=2;return"string"==typeof e?t=1:q(e)?t=2:(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||b.isBuffer(e))&&(t=3),this.waitingShakePromise.then((()=>b.isBuffer(e)?this.sendBuf({buf:e,type:3,contentType:3,dataType:0}):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?this.sendBuf({buf:b.from(e),type:3,contentType:3,dataType:0}):2===t?this.sendJson({json:e,type:3,contentType:2,dataType:0}):1===t?this.sendText({text:e,type:3,contentType:1,dataType:0}):this.sendBuf({buf:b.from(e),type:3,contentType:3,dataType:0})))}},V=function(e){return{shakeTimeout:5e3,requestTimeout:6e4,transport:e,onCall(e){return e?(H.add(e),this):this},offOnCall(e){return H.remove(e),this},call(t){return f()&&e.fork(this.shakeTimeout),t=q(t)?t.contentType?t:{jsonrpc:M,...t}:t,e.call(t)},onRequest(e){return e?(N.add(e),this):this},initOnCall(){e.on("call",(({contentType:e,payload:t})=>{switch(e){case 2:t=k(t);break;case 1:t=L(t);break;default:t=v(t)}H.runAll(t)}))},initOnRequest(){e.on("request",(e=>{let t=e.request.payload;switch(e.request.contentType){case 2:t=k(t);break;case 1:t=L(t);break;default:t=v(t)}N.runAll(t,((s,n,i={})=>2===e.request.contentType&&t?.jsonrpc===M?s?e.response({data:{jsonrpc:M,error:s}}):e.response({data:{jsonrpc:M,result:n}}):e.response({data:n,...i})))}))},cancelAllRequest(){return e.off("response"),this},offOnRequest(e){return N.remove(e),this},request(t,s={}){return f()&&e.fork(this.shakeTimeout),t=q(t)?s.contentType?t:{jsonrpc:M,...t}:t,e.request(t,{timeout:this.requestTimeout,...s}).then((e=>{if(!q(e)||e.jsonrpc!==M)return e;const{error:t,result:s}=e;if(t)throw t;return s}))},connect(){e.connect((()=>{this.initOnCall(),this.initOnRequest(),this.initOnBleChanged()}))},initOnBleChanged(){return e.on("bleStatusChanged",(e=>{J.runAll(e)})),this},onBleChanged(e){return e?(J.add(e),this):this},offOnBleChanged(e){return J.remove(e),this},disConnect(){return this.cancelAllRequest(),this.offOnRequest(),this.offOnCall(),this.offOnBleChanged(),e.disConnect((()=>{})),this},start(){return e.listen((()=>{this.initOnCall(),this.initOnRequest()})),this},stop(){return this.cancelAllRequest(),this.offOnRequest(),this.offOnCall(),e.disConnect((()=>{})),this}}}(W);function G(e){return e.toTimeString().split(" ")[0]}const K=function(e){let t=new z;return{canUseFileTransfer:()=>void 0!==e,init(){this.canUseFileTransfer()&&(g()?e.inbox.on("file",(function(){const s=e.inbox.getNextFile();t.runAll(s)})):e.inbox.on("newfile",(function(){const s=e.inbox.getNextFile();t.runAll(s)})))},onFile(e){return e&&this.canUseFileTransfer()?(t.add(e),this):this},onSideServiceFileFinished(e){return e&&this.canUseFileTransfer()?(t.add(e),this):this},emitFile(){return e.inbox.emit("file"),this},offFile(){return this.canUseFileTransfer()?(e.inbox.off("newfile"),e.inbox.off("file"),t.remove(),this):this},getFile(){return this.canUseFileTransfer()?e.inbox.getNextFile():null},sendFile(t,s){if(!this.canUseFileTransfer())throw new Error("fileTransfer is not available");return e.outbox.enqueueFile(t,s)}}}(transferFile),Q={convert:e=>image.convert(e)};o.use((function(){return{onInit(){this.messaging=V,this._onCall=this.onCall?.bind(this),this._onRequest=this.onRequest?.bind(this),this.messaging.onCall(this._onCall).onRequest(this.__onRequest.bind(this)),this.messaging.start()},onDestroy(){this._onCall&&this.messaging.offOnCall(this._onCall),this._onRequest&&this.messaging.offOnRequest(this._onRequest),this.messaging.stop()},request(e,t={}){return this.messaging.request(e,t)},call(e){return this.messaging.call(e)},__onRequest(e,t){return"http.request"===e.method?this.httpRequestHandler(e,t):this._onRequest(e,t)},fetch:e=>fetch(function(e){const t={timeout:1e4,...e};return t.baseURL&&(t.url=new URL(t.url,t.baseURL).toString()),t}(e)),httpRequestHandler(e,t){const s=new Date;return this.fetch(e.params).then((e=>{t(null,{status:e.status,statusText:e.statusText,headers:e.headers,body:e.body})})).catch((s=>(this.error("http error url=%s",e.params.url,s.message,s.data),t({code:s.code,message:s.message,data:s.data})))).finally((()=>{const t=new Date;this.log("http url=%s %s %s elapsed=%dms",e.params.url,G(s),G(t),t.getTime()-s.getTime())}))}}})).use((function(){return{onInit(){K.init(),this._onReceivedFile=this.onReceivedFile?.bind(this),K.onSideServiceFileFinished(this._onReceivedFile),"undefined"!=typeof sideService&&sideService.launchReasons.fileTransfer&&K.emitFile()},onDestroy(){this._onReceivedFile&&K.offFile(this._onReceivedFile)},sendFile:(e,t)=>K.sendFile(e,t)}})).use((function(e){e.download=function(e,t){return network.downloader.downloadFile({url:e,...t})}})).use((function(e){e.convert=function(e){return Q.convert(e)}}));export{o as BaseSideService,Q as convertLib,s as settingsLib};