@ray-js/wechat-mqtt-core 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.esm.js +1 -1
- package/index.js +1 -1
- package/lib/interface.d.ts +1 -1
- package/lib/publish.d.ts +1 -1
- package/lib/response.d.ts +1 -1
- package/package.json +3 -3
package/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stringToBytes as e,uintToBytes as o,uintToBytesBy128 as t,bytesToIntBy128 as r,bytesToUint as i,bytesToString as n,BaseApi as s}from"@ray-js/wechat-helper";import{createEmitter as c}from"@ray-js/wechat-event";function a(e,o,t,r){return new(t||(t=Promise))((function(i,n){function s(e){try{a(r.next(e))}catch(e){n(e)}}function c(e){try{a(r.throw(e))}catch(e){n(e)}}function a(e){var o;e.done?i(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(s,c)}a((r=r.apply(e,o||[])).next())}))}var l,d;!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(l||(l={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(d||(d={}));const p=(r,i=0)=>{const n=r<<4|i;let s=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0,d=new Uint8Array(100),p=0;const u=(r,i,n,s=!1,c=!1)=>{let a;a="string"==typeof n?e(n):"number"==typeof n?[n]:n;let l=new Uint8Array;s&&(l=c?t(a.length):o(a.length,2));return r=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(r,i+(a.length+l.length)),s&&r.set(l,i),i+=l.length,r.set(a,i),[r,i+=a.length]};function f(e,o=!1,t=!1){const[r,i]=u(s,c,e,o,t);s=r,c=i}function m(e,o=!0,t=!1){const[r,i]=u(a,l,e,o,t);a=r,l=i}return{header:f,payload:m,cleanCache(){d=new Uint8Array(100),p=0},cache:(e,o=!1,t=!1)=>{const[r,i]=u(d,p,e,o,t);d=r,p=i},putHeader(){f(d.slice(0,p),!0,!0)},putPayload(){m(d.slice(0,p),!0,!0)},getCache:()=>d.slice(0,p),getPacket:()=>{const e=c,o=l,r=e+o,i=t(r),d=new Uint8Array(r+i.length+1);d[0]=n;let p=1;return d.set(i,p),p+=i.length,d.set(s.slice(0,e),p),p+=e,d.set(a.slice(0,o),p),d}}},u=t=>(r,i)=>{const n=e(r),s=o(n.length,2);i(t),i(s),i(n)},f=e=>(o,t)=>{t(e),t(o?1:0)},m=e=>(t,r)=>{r(e),r(o(t))},v=e=>(t,r)=>{r(e),r(o(t,2))},g=e=>(t,r)=>{const i=o(t.length,2);r(e),r(i),r(t)},h={sessionExpiryInterval:m(d.sessionExpiryInterval),receiveMaximum:v(d.receiveMaximum),maximumPacketSize:m(d.maximumPacketSize),topicAliasMaximum:v(d.topicAliasMaximum),topicAlias:v(d.topicAlias),requestResponseInformation:f(d.requestProblemInformation),requestProblemInformation:f(d.requestProblemInformation),userProperties:(C=d.userProperties,(o,t)=>{Object.keys(o).forEach((r=>{const i=o[r],n=e(r);Array.isArray(i)?i.forEach((o=>{t(C),t(n),t(e(o))})):(t(C),t(n),t(e(i)))}))}),authenticationMethod:u(d.authenticationMethod),authenticationData:g(d.authenticationData),willDelayInterval:m(d.willDelayInterval),payloadFormatIndicator:f(d.payloadFormatIndicator),messageExpiryInterval:m(d.messageExpiryInterval),contentType:u(d.contentType),responseTopic:u(d.responseTopic),correlationData:g(d.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t(o))})(d.subscriptionIdentifier)};var C;const M=(e,o)=>{Object.keys(e||{}).map((t=>{h[t]&&h[t](e[t],o)}))},y=(e,o)=>{const{properties:t,reasonCode:r}=o,i=p(l.AUTH);if(i.header(r),!t)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return M(t,i.cache),i.putHeader(),e.send(i.getPacket())},P=[],b=(e,o,t)=>{t?P.splice(0,0,[e,o]):P.push([e,o])};const T=(e,o)=>[i(e.slice(o,o+=2)),o],I=(e,o)=>[i(e.slice(o,o+=4)),o],w=(e,o)=>[1===e[o++],o],E=(e,o)=>{const t=i(e.slice(o,o+=2));return[n(e.slice(o,o+=t)),o]},A=(e,o)=>{const t=i(e.slice(o,o+=2));return[e.slice(o,o+=t),o]},U={sessionExpiryInterval:I,receiveMaximum:T,maximumPacketSize:I,topicAliasMaximum:T,topicAlias:T,requestResponseInformation:w,requestProblemInformation:w,userProperties:(e,o)=>{const[t,r]=E(e,o),[i,n]=E(e,r);return[[t,i],n]},authenticationMethod:E,authenticationData:A,willDelayInterval:I,payloadFormatIndicator:w,messageExpiryInterval:I,contentType:E,responseTopic:E,correlationData:A,subscriptionIdentifier:(e,o)=>{const{num:t,end:i}=r(e,o);return[t,i]}},S=e=>{let o=e.length>0,t=0;const r={};for(;o;){const i=e[t++],n=Object.keys(d).find((e=>d[e]===i));if(!n)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const s=U[n](e,t);if(i===d.userProperties){const e=r[n],o=s[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else r[n]=s[0];t=s[1],o=t<e.length}}return r},B=(e,o)=>{const{end:t}=r(e,1),n=e.slice(t),s=i(n.slice(0,2));let c,a=0;if(5===o.protocolVersion){a=n[2];const{num:o,end:t}=r(n,3);c=S(e.slice(t,o))}return{id:s,reasonCode:a,properties:c}},q=(t,r)=>a(void 0,void 0,void 0,(function*(){const{dup:i,qos:n=0,topicName:s,id:c,properties:a,payload:d}=r;let u=0|(i?0===n?0:8:0);u|=n<<1;const f=p(l.PUBLISH,u);f.header(e(s),!0),n>0&&f.header(o(c,2)),5===t.protocolVersion&&(M(a,f.cache),f.putHeader()),f.payload(d,!1);try{yield t.send(f.getPacket())}catch(e){return void t.emitError(e)}if(0!==n)if(1===n)try{yield D(t,r)}catch(e){q(t,r)}else try{const e=yield H(t,c);t.options.onPubrel?k(t,t.options.onPubrel(e)):k(t,{id:c,reasonCode:0}),yield K(t,r)}catch(e){q(t,r)}})),x=(e,t,r,i=0)=>a(void 0,void 0,void 0,(function*(){const{id:n,properties:s,reasonCode:c}=t,a=p(r,i);a.header(o(n,2)),5===e.protocolVersion&&(a.header(c||0),M(s,a.cache),a.putHeader()),e.send(a.getPacket())})),N=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBACK)})),k=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREL,2)})),O=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREC,0)})),R=(e,o)=>a(void 0,void 0,void 0,(function*(){x(e,o,l.PUBCOMP,0)})),D=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=s=>{if(s[0]>>4===l.PUBACK){const c=B(s,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(n),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const n=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),H=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=s=>{if(s[0]>>4===l.PUBREC){const c=B(s,e);if(c.id===o)if(e.offMessage(i),clearTimeout(n),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const n=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),K=(e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=s=>{if(s[0]>>4===l.PUBCOMP){const c=B(s,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(n),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const n=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))}));b((()=>!(!window||!window.WebSocket)),((e,o)=>a(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const i=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(i),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",(o=>{o.data instanceof ArrayBuffer?e(o):o.data instanceof Blob&&o.data.arrayBuffer().then((o=>{e({data:o})}))}))},onError:e=>{t.addEventListener("error",e)}}}))));b((()=>!("undefined"==typeof wx||!s.hasBaseApi("connectSocket"))),((e,o)=>a(void 0,void 0,void 0,(function*(){const t=yield((e,o)=>a(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=s.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:r});i&&t(i)}))})))(e,o);return{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,r)=>{t.send({data:e,fail:r,success:o})})),close:()=>{t.close()},onClose:e=>{t.onClose(e)},onMessage:e=>{t.onMessage(e)},onError:e=>{t.onError(e)}}}))));const V=(e,o)=>{const t=(e=>{let o=0;const t=e[o++],{num:i,end:n}=r(e,1);return{reasonCode:t,properties:S(e.slice(n,n+i))}})(e);if(24===t.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};y(o,o.options.onAuth(t))}},L=(e,o)=>{const t=((e,o)=>{const t=e[0],n=(6&t)>>1,s=(8&t)>>3==1;let c=1;const{num:a,end:l}=r(e,c),d=l+a;c=l;const p=E(e,c),[u]=p;let f,m;if(c=p[1],n>0&&(f=i(e.slice(c,c+=2))),5===o.protocolVersion){const{num:o,end:t}=r(e,c);m=S(e.slice(t,o)),c=o+t}return{qos:n,dup:s,topicName:u,id:f,payload:e.slice(c,d),properties:m}})(e,o);let{topicName:n}=t;if(o.protocolVersion>=5&&t.properties){const{topicAlias:e}=t.properties;if(e)if(n)o.applyTopic(e,n);else if(n=o.getTopic(e),!n)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(n))switch(t.qos){case 0:o.emitMqttMessage({topic:n,payload:t.payload});break;case 1:o.options.onPuback?N(o,o.options.onPuback(t)):N(o,{id:t.id,reasonCode:0});break;case 2:o.options.onPubrec?O(o,o.options.onPubrec(t)):O(o,{id:t.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},j=(e,o)=>{const t=B(e,o);o.options.onPubcomp?R(o,o.options.onPubcomp(t)):R(o,{id:t.id,reasonCode:0})},Q=e=>{const o=1e3*(e.options.keepalive||60),t=()=>a(void 0,void 0,void 0,(function*(){try{!e.isClose()&&(yield(e=>(e.send(new Uint8Array([l.PINGREQ<<4,0])),new Promise(((o,t)=>{const r=t=>{t[0]>>4===l.PINGRESP&&(e.offMessage(r),clearTimeout(i),o(!0))};e.onMessage(r);const i=setTimeout((()=>{e.offMessage(r),e.close(),t({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(e)),setTimeout(t,o)}catch(o){console.warn("ping error",o),e.emitError(o),e.close(o)}}));setTimeout(t,o)},z=t=>a(void 0,void 0,void 0,(function*(){const n=yield(e=>a(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=P.find((e=>e[0]()));if(t){let r=0;const i=c();let n=null,s=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(c=!1)=>a(void 0,void 0,void 0,(function*(){if(c&&n)try{n.close()}catch(e){}const a=++s;return r=0,n=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{r=2,o(new Error("ws connect time out"))}),1e4);n&&n.onError((e=>{if(0===r)clearTimeout(t),o(e);else if(a===s){const o=r;r=2,i.emit("error",e),2==o&&i.emit("close",e)}})),n&&n.onOpen((()=>{clearTimeout(t),r=1,n&&n.onClose((e=>{if(a===s){const o=r;r=2,2==o&&i.emit("close",e)}})),n&&n.onMessage((e=>{a===s&&i.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===r,isOnline:()=>1===r,getStatus:()=>r,send:e=>{if(n&&1===r)return n.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{i.on("close",e)},offClose:e=>{i.off("close",e)},onError:e=>{i.on("error",e)},offError:e=>{i.off("error",e)},onMessage:e=>{i.on("message",e)},offMessage:e=>{i.off("message",e)},close:e=>{const o=r;r=2,2!==o&&i.emit("close",e),n&&n.close()},emitError:e=>{i.emit("error",e)},emitMqttMessage:e=>{i.emit("mqttMessage",e)},onMqttMessage:e=>{i.on("mqttMessage",e)},offMqttMessage:e=>{i.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(t);yield n.connect(),n.onMessage((e=>{((e,o)=>{const t=e[0]>>4,{end:i,num:n}=r(e,1);switch(t){case l.AUTH:return V(e.slice(i,i+n),o);case l.PUBLISH:return L(e,o);case l.PUBCOMP:return j(e,o);case l.DISCONNECT:o.close()}})(e,n)})),yield((e,t)=>a(void 0,void 0,void 0,(function*(){const{protocolVersion:i=4,connectTimeout:n=10,username:s,password:c,will:a,keepalive:d=60,clean:u,clientId:f}=t,m=p(l.CONNECT);m.header([0,4,77,81,84,84]),m.header(i);let v=0;if(v|=s?128:0,v|=c?64:0,v|=a&&a.retain?32:0,v|=a&&a.qos?a.qos<<3:0,v|=a?4:0,v|=u?2:0,m.header(v),m.header(o(d,2)),5===i&&(M(t.properties,m.cache),m.putHeader()),i<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===u)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(f),a){if(5===i){if(!a.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),M(a.properties,m.cache),m.putPayload()}if(!a.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(a.topic),!a.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(a.payload)}return s&&m.payload(s),c&&m.payload(c),e.send(m.getPacket()),new Promise(((o,t)=>{const i=n=>{if(n[0]>>4===l.CONNACK){e.offMessage(i),clearTimeout(s);const{end:c}=r(n,1),a=n.slice(c),l=1&a[0];e.sessionPresent=l;const d=a[1];return 0===d?void o(!0):void t({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close(),t({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*n)}))})))(n,t),Q(n);let s=0;const d=()=>(++s,16777215===s&&(s=1),s);return{getStatus:n.getStatus,onMessage:n.onMqttMessage,offMessage:n.offMqttMessage,subscribe:(e,t)=>a(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>!n.checkTopic(e.topic)))).length){const s=yield((e,t)=>a(void 0,void 0,void 0,(function*(){const{id:n,properties:s,payload:c}=t,a=p(l.SUBSCRIBE,2);if(a.header(o(n,2)),5===e.protocolVersion){if(!s)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};M(s,a.cache),a.putHeader()}return c.forEach((o=>{a.payload(o.topic);let t=o.qos||0;if(5===e.protocolVersion){const{nl:e=0,rap:r=0,rh:i=0}=o;t|=e<<2,t|=r<<3,t|=i<<4}a.payload(t,!1)})),e.send(a.getPacket()),new Promise(((o,t)=>{const s=t=>{if(t[0]>>4===l.SUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(i(d.slice(0,2))===n){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,i);i=e+o,t=S(d.slice(e,i))}const n=d.slice(i);e.offMessage(s),clearTimeout(c),o({reasonCode:n,properties:t})}}};e.onMessage(s);const c=setTimeout((()=>{e.offMessage(s),e.close(),t({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(n,{id:d(),properties:null==t?void 0:t.properties,payload:e}),c=e.reduce(((o,t,r)=>(s.reasonCode[r]>=128?o[t.topic]=s.reasonCode[r]:e.map((e=>n.addTopic(e.topic))),o)),{});return{properties:s.properties,err:Object.keys(c).length?c:void 0}}return{}})),unsubscribe:(e,t)=>a(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>n.checkTopic(e)))).length){const s=yield((e,t)=>{const{id:n,properties:s,topics:c}=t,a=p(l.UNSUBSCRIBE,2);return a.header(o(n,2)),5===e.protocolVersion&&(M(s,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),e.send(a.getPacket()),new Promise(((o,t)=>{const s=t=>{if(t[0]>>4===l.UNSUBACK){const l=r(t,1),d=l.end+l.num,p=t.slice(l.end,d);if(i(p.slice(0,2))===n){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(p,i);i=e+o,t=S(p.slice(e,i))}const n=p.slice(i);e.offMessage(s),clearTimeout(a),n.length?o({reasonCode:n,properties:t}):o({reasonCode:new Uint8Array(c.map((()=>0))),properties:t})}}};e.onMessage(s);const a=setTimeout((()=>{e.offMessage(s),e.close(),t({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(n,{id:d(),properties:null==t?void 0:t.properties,topics:e}),c=e.reduce(((o,t,r)=>(s.reasonCode[r]>=128?o[t]=s.reasonCode[r]:e.map((e=>n.removeTopic(e))),o)),{});return{err:Object.keys(c).length?c:void 0}}return{}})),publish:(o,t,r)=>{const i=d();return q(n,Object.assign({id:i,topicName:o,payload:"string"==typeof t?e(t):t},r))},reAuth:e=>{y(n,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:e=>{((e,o)=>{a(void 0,void 0,void 0,(function*(){const{reasonCode:t=0,properties:r}=o,i=p(l.DISCONNECT);5===e.protocolVersion&&(i.header(t),M(r,i.cache),i.putHeader()),yield e.send(i.getPacket()),e.close()}))})(n,e||{reasonCode:0})},onClose:n.onClose,onError:n.onError}}));export{z as createMQTT};
|
|
1
|
+
import{stringToBytes as e,uintToBytes as o,uintToBytesBy128 as t,bytesToIntBy128 as r,bytesToUint as i,bytesToString as s,BaseApi as n}from"@ray-js/wechat-helper";import{createEmitter as a}from"@ray-js/wechat-event";function c(e,o,t,r){return new(t||(t=Promise))((function(i,s){function n(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var o;e.done?i(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,a)}c((r=r.apply(e,o||[])).next())}))}var l,d;!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(l||(l={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(d||(d={}));const p=(r,i=0)=>{const s=r<<4|i;let n=new Uint8Array(100),a=0,c=new Uint8Array(100),l=0,d=new Uint8Array(100),p=0;const u=(r,i,s,n=!1,a=!1)=>{let c;c="string"==typeof s?e(s):"number"==typeof s?[s]:s;let l=new Uint8Array;n&&(l=a?t(c.length):o(c.length,2));return r=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(r,i+(c.length+l.length)),n&&r.set(l,i),i+=l.length,r.set(c,i),[r,i+=c.length]};function f(e,o=!1,t=!1){const[r,i]=u(n,a,e,o,t);n=r,a=i}function m(e,o=!0,t=!1){const[r,i]=u(c,l,e,o,t);c=r,l=i}return{header:f,payload:m,cleanCache(){d=new Uint8Array(100),p=0},cache:(e,o=!1,t=!1)=>{const[r,i]=u(d,p,e,o,t);d=r,p=i},putHeader(){f(d.slice(0,p),!0,!0)},putPayload(){m(d.slice(0,p),!0,!0)},getCache:()=>d.slice(0,p),getPacket:()=>{const e=a,o=l,r=e+o,i=t(r),d=new Uint8Array(r+i.length+1);d[0]=s;let p=1;return d.set(i,p),p+=i.length,d.set(n.slice(0,e),p),p+=e,d.set(c.slice(0,o),p),d}}},u=t=>(r,i)=>{const s=e(r),n=o(s.length,2);i(t),i(n),i(s)},f=e=>(o,t)=>{t(e),t(o?1:0)},m=e=>(t,r)=>{r(e),r(o(t))},v=e=>(t,r)=>{r(e),r(o(t,2))},g=e=>(t,r)=>{const i=o(t.length,2);r(e),r(i),r(t)},h={sessionExpiryInterval:m(d.sessionExpiryInterval),receiveMaximum:v(d.receiveMaximum),maximumPacketSize:m(d.maximumPacketSize),topicAliasMaximum:v(d.topicAliasMaximum),topicAlias:v(d.topicAlias),requestResponseInformation:f(d.requestProblemInformation),requestProblemInformation:f(d.requestProblemInformation),userProperties:(C=d.userProperties,(o,t)=>{Object.keys(o).forEach((r=>{const i=o[r],s=e(r);Array.isArray(i)?i.forEach((o=>{t(C),t(s),t(e(o))})):(t(C),t(s),t(e(i)))}))}),authenticationMethod:u(d.authenticationMethod),authenticationData:g(d.authenticationData),willDelayInterval:m(d.willDelayInterval),payloadFormatIndicator:f(d.payloadFormatIndicator),messageExpiryInterval:m(d.messageExpiryInterval),contentType:u(d.contentType),responseTopic:u(d.responseTopic),correlationData:g(d.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t(o))})(d.subscriptionIdentifier)};var C;const M=(e,o)=>{Object.keys(e||{}).map((t=>{h[t]&&h[t](e[t],o)}))},y=(e,o)=>{const{properties:t,reasonCode:r}=o,i=p(l.AUTH);if(i.header(r),!t)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return M(t,i.cache),i.putHeader(),e.send(i.getPacket())},P=[],b=(e,o,t)=>{t?P.splice(0,0,[e,o]):P.push([e,o])};const T=(e,o)=>[i(e.slice(o,o+=2)),o],I=(e,o)=>[i(e.slice(o,o+=4)),o],w=(e,o)=>[1===e[o++],o],E=(e,o)=>{const t=i(e.slice(o,o+=2));return[s(e.slice(o,o+=t)),o]},A=(e,o)=>{const t=i(e.slice(o,o+=2));return[e.slice(o,o+=t),o]},U={sessionExpiryInterval:I,receiveMaximum:T,maximumPacketSize:I,topicAliasMaximum:T,topicAlias:T,requestResponseInformation:w,requestProblemInformation:w,userProperties:(e,o)=>{const[t,r]=E(e,o),[i,s]=E(e,r);return[[t,i],s]},authenticationMethod:E,authenticationData:A,willDelayInterval:I,payloadFormatIndicator:w,messageExpiryInterval:I,contentType:E,responseTopic:E,correlationData:A,subscriptionIdentifier:(e,o)=>{const{num:t,end:i}=r(e,o);return[t,i]}},S=e=>{let o=e.length>0,t=0;const r={};for(;o;){const i=e[t++],s=Object.keys(d).find((e=>d[e]===i));if(!s)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const n=U[s](e,t);if(i===d.userProperties){const e=r[s],o=n[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else r[s]=n[0];t=n[1],o=t<e.length}}return r},B=(e,o)=>{const{end:t}=r(e,1),s=e.slice(t),n=i(s.slice(0,2));let a,c=0;if(5===o.protocolVersion){c=s[2];const{num:o,end:t}=r(s,3);a=S(e.slice(t,o))}return{id:n,reasonCode:c,properties:a}},q=(t,r)=>c(void 0,void 0,void 0,(function*(){const{dup:i,qos:s=0,topicName:n,id:a,properties:c,payload:d}=r;let u=0|(i?0===s?0:8:0);u|=s<<1;const f=p(l.PUBLISH,u);f.header(e(n),!0),s>0&&f.header(o(a,2)),5===t.protocolVersion&&(M(c,f.cache),f.putHeader()),f.payload(d,!1);try{yield t.send(f.getPacket())}catch(e){return void t.emitError(e)}if(0!==s)if(1===s)try{yield D(t,r)}catch(e){yield q(t,r)}else try{const e=yield H(t,a);t.options.onPubrel?k(t,t.options.onPubrel(e)):k(t,{id:a,reasonCode:0}),yield K(t,r)}catch(e){yield q(t,r)}})),x=(e,t,r,i=0)=>c(void 0,void 0,void 0,(function*(){const{id:s,properties:n,reasonCode:a}=t,c=p(r,i);c.header(o(s,2)),5===e.protocolVersion&&(c.header(a||0),M(n,c.cache),c.putHeader()),e.send(c.getPacket())})),N=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,l.PUBACK)})),k=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREL,2)})),O=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,l.PUBREC,0)})),R=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,l.PUBCOMP,0)})),D=(e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBACK){const a=B(n,e);if(a.id===o.id)if(e.offMessage(i),clearTimeout(s),0===a.reasonCode)t(a);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${a.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),H=(e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBREC){const a=B(n,e);if(a.id===o)if(e.offMessage(i),clearTimeout(s),0===a.reasonCode)t(a);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${a.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))})),K=(e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n=>{if(n[0]>>4===l.PUBCOMP){const a=B(n,e);if(a.id===o.id)if(e.offMessage(i),clearTimeout(s),0===a.reasonCode)t(a);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${a.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(i);const s=setTimeout((()=>{e.offMessage(i),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))}));b((()=>!(!window||!window.WebSocket)),((e,o)=>c(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const i=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(i),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",(o=>{o.data instanceof ArrayBuffer?e(o):o.data instanceof Blob&&o.data.arrayBuffer().then((o=>{e({data:o})}))}))},onError:e=>{t.addEventListener("error",e)}}}))));b((()=>!("undefined"==typeof wx||!n.hasBaseApi("connectSocket"))),((e,o)=>c(void 0,void 0,void 0,(function*(){const t=yield((e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const i=n.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:r});i&&t(i)}))})))(e,o);return{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,r)=>{t.send({data:e,fail:r,success:o})})),close:()=>{t.close()},onClose:e=>{t.onClose(e)},onMessage:e=>{t.onMessage(e)},onError:e=>{t.onError(e)}}}))));const V=(e,o)=>{const t=(e=>{let o=0;const t=e[o++],{num:i,end:s}=r(e,1);return{reasonCode:t,properties:S(e.slice(s,s+i))}})(e);if(24===t.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};y(o,o.options.onAuth(t))}},L=(e,o)=>{const t=((e,o)=>{const t=e[0],s=(6&t)>>1,n=(8&t)>>3==1;let a=1;const{num:c,end:l}=r(e,a),d=l+c;a=l;const p=E(e,a),[u]=p;let f,m;if(a=p[1],s>0&&(f=i(e.slice(a,a+=2))),5===o.protocolVersion){const{num:o,end:t}=r(e,a);m=S(e.slice(t,o)),a=o+t}return{qos:s,dup:n,topicName:u,id:f,payload:e.slice(a,d),properties:m}})(e,o);let{topicName:s}=t;if(o.protocolVersion>=5&&t.properties){const{topicAlias:e}=t.properties;if(e)if(s)o.applyTopic(e,s);else if(s=o.getTopic(e),!s)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(s))switch(t.qos){case 0:o.emitMqttMessage({topic:s,payload:t.payload});break;case 1:if(o.options.onPuback){const e=o.options.onPuback(t);N(o,e),0===e.reasonCode&&o.emitMqttMessage({topic:s,payload:t.payload})}else N(o,{id:t.id,reasonCode:0}),o.emitMqttMessage({topic:s,payload:t.payload});break;case 2:if(o.options.onPubrec){const e=o.options.onPubrec(t);O(o,e),0===e.reasonCode&&o.emitMqttMessage({topic:s,payload:t.payload})}else O(o,{id:t.id,reasonCode:0}),o.emitMqttMessage({topic:s,payload:t.payload})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},j=(e,o)=>{const t=B(e,o);o.options.onPubcomp?R(o,o.options.onPubcomp(t)):R(o,{id:t.id,reasonCode:0})},Q=e=>{const o=1e3*(e.options.keepalive||60),t=()=>c(void 0,void 0,void 0,(function*(){try{!e.isClose()&&(yield(e=>(e.send(new Uint8Array([l.PINGREQ<<4,0])),new Promise(((o,t)=>{const r=t=>{t[0]>>4===l.PINGRESP&&(e.offMessage(r),clearTimeout(i),o(!0))};e.onMessage(r);const i=setTimeout((()=>{e.offMessage(r),e.close(),t({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(e)),setTimeout(t,o)}catch(o){console.warn("ping error",o),e.emitError(o),e.close(o)}}));setTimeout(t,o)},z=t=>c(void 0,void 0,void 0,(function*(){const s=yield(e=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=P.find((e=>e[0]()));if(t){let r=0;const i=a();let s=null,n=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(a=!1)=>c(void 0,void 0,void 0,(function*(){if(a&&s)try{s.close()}catch(e){}const c=++n;return r=0,s=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{r=2,o(new Error("ws connect time out"))}),1e4);s&&s.onError((e=>{if(0===r)clearTimeout(t),o(e);else if(c===n){const o=r;r=2,i.emit("error",e),2==o&&i.emit("close",e)}})),s&&s.onOpen((()=>{clearTimeout(t),r=1,s&&s.onClose((e=>{if(c===n){const o=r;r=2,2==o&&i.emit("close",e)}})),s&&s.onMessage((e=>{c===n&&i.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===r,isOnline:()=>1===r,getStatus:()=>r,send:e=>{if(s&&1===r)return s.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{i.on("close",e)},offClose:e=>{i.off("close",e)},onError:e=>{i.on("error",e)},offError:e=>{i.off("error",e)},onMessage:e=>{i.on("message",e)},offMessage:e=>{i.off("message",e)},close:e=>{const o=r;r=2,2!==o&&i.emit("close",e),s&&s.close()},emitError:e=>{i.emit("error",e)},emitMqttMessage:e=>{i.emit("mqttMessage",e)},onMqttMessage:e=>{i.on("mqttMessage",e)},offMqttMessage:e=>{i.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(t);yield s.connect(),s.onMessage((e=>{((e,o)=>{const t=e[0]>>4,{end:i,num:s}=r(e,1);switch(t){case l.AUTH:return V(e.slice(i,i+s),o);case l.PUBLISH:return L(e,o);case l.PUBCOMP:return j(e,o);case l.DISCONNECT:o.close()}})(e,s)})),yield((e,t)=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:i=4,connectTimeout:s=10,username:n,password:a,will:c,keepalive:d=60,clean:u,clientId:f}=t,m=p(l.CONNECT);m.header([0,4,77,81,84,84]),m.header(i);let v=0;if(v|=n?128:0,v|=a?64:0,v|=c&&c.retain?32:0,v|=c&&c.qos?c.qos<<3:0,v|=c?4:0,v|=u?2:0,m.header(v),m.header(o(d,2)),5===i&&(M(t.properties,m.cache),m.putHeader()),i<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===u)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(f),c){if(5===i){if(!c.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),M(c.properties,m.cache),m.putPayload()}if(!c.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(c.topic),!c.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(c.payload)}return n&&m.payload(n),a&&m.payload(a),e.send(m.getPacket()),new Promise(((o,t)=>{const i=s=>{if(s[0]>>4===l.CONNACK){e.offMessage(i),clearTimeout(n);const{end:a}=r(s,1),c=s.slice(a),l=1&c[0];e.sessionPresent=l;const d=c[1];return 0===d?void o(!0):void t({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};e.onMessage(i);const n=setTimeout((()=>{e.offMessage(i),e.close(),t({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*s)}))})))(s,t),Q(s);let n=0;const d=()=>(++n,16777215===n&&(n=1),n);return{getStatus:s.getStatus,onMessage:s.onMqttMessage,offMessage:s.offMqttMessage,subscribe:(e,t)=>c(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>!s.checkTopic(e.topic)))).length){const n=yield((e,t)=>c(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:a}=t,c=p(l.SUBSCRIBE,2);if(c.header(o(s,2)),5===e.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};M(n,c.cache),c.putHeader()}return a.forEach((o=>{c.payload(o.topic);let t=o.qos||0;if(5===e.protocolVersion){const{nl:e=0,rap:r=0,rh:i=0}=o;t|=e<<2,t|=r<<3,t|=i<<4}c.payload(t,!1)})),e.send(c.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===l.SUBACK){const c=r(t,1),l=c.end+c.num,d=t.slice(c.end,l);if(i(d.slice(0,2))===s){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,i);i=e+o,t=S(d.slice(e,i))}const s=d.slice(i);e.offMessage(n),clearTimeout(a),o({reasonCode:s,properties:t})}}};e.onMessage(n);const a=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(s,{id:d(),properties:null==t?void 0:t.properties,payload:e}),a=e.reduce(((o,t,r)=>(n.reasonCode[r]>=128?o[t.topic]=n.reasonCode[r]:e.map((e=>s.addTopic(e.topic))),o)),{});return{properties:n.properties,err:Object.keys(a).length?a:void 0}}return{}})),unsubscribe:(e,t)=>c(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>s.checkTopic(e)))).length){const n=yield((e,t)=>{const{id:s,properties:n,topics:a}=t,c=p(l.UNSUBSCRIBE,2);return c.header(o(s,2)),5===e.protocolVersion&&(M(n,c.cache),c.putHeader()),a.forEach((e=>{c.payload(e)})),e.send(c.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===l.UNSUBACK){const l=r(t,1),d=l.end+l.num,p=t.slice(l.end,d);if(i(p.slice(0,2))===s){let t,i=2;if(5===e.protocolVersion){const{end:e,num:o}=r(p,i);i=e+o,t=S(p.slice(e,i))}const s=p.slice(i);e.offMessage(n),clearTimeout(c),s.length?o({reasonCode:s,properties:t}):o({reasonCode:new Uint8Array(a.map((()=>0))),properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(s,{id:d(),properties:null==t?void 0:t.properties,topics:e}),a=e.reduce(((o,t,r)=>(n.reasonCode[r]>=128?o[t]=n.reasonCode[r]:e.map((e=>s.removeTopic(e))),o)),{});return{err:Object.keys(a).length?a:void 0}}return{}})),publish:(o,t,r)=>{const i=d();return q(s,Object.assign({id:i,topicName:o,payload:"string"==typeof t?e(t):t},r))},reAuth:e=>{y(s,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:e=>{((e,o)=>{c(void 0,void 0,void 0,(function*(){const{reasonCode:t=0,properties:r}=o,i=p(l.DISCONNECT);5===e.protocolVersion&&(i.header(t),M(r,i.cache),i.putHeader()),yield e.send(i.getPacket()),e.close()}))})(s,e||{reasonCode:0})},onClose:s.onClose,onError:s.onError}}));export{z as createMQTT};
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,o,t=require("@ray-js/wechat-helper"),r=require("@ray-js/wechat-event");function s(e,o,t,r){return new(t||(t=Promise))((function(s,i){function n(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var o;e.done?s(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,c)}a((r=r.apply(e,o||[])).next())}))}!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(e||(e={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(o||(o={}));const i=(e,o=0)=>{const r=e<<4|o;let s=new Uint8Array(100),i=0,n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0;const d=(e,o,r,s=!1,i=!1)=>{let n;n="string"==typeof r?t.stringToBytes(r):"number"==typeof r?[r]:r;let c=new Uint8Array;s&&(c=i?t.uintToBytesBy128(n.length):t.uintToBytes(n.length,2));return e=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(e,o+(n.length+c.length)),s&&e.set(c,o),o+=c.length,e.set(n,o),[e,o+=n.length]};function u(e,o=!1,t=!1){const[r,n]=d(s,i,e,o,t);s=r,i=n}function p(e,o=!0,t=!1){const[r,s]=d(n,c,e,o,t);n=r,c=s}return{header:u,payload:p,cleanCache(){a=new Uint8Array(100),l=0},cache:(e,o=!1,t=!1)=>{const[r,s]=d(a,l,e,o,t);a=r,l=s},putHeader(){u(a.slice(0,l),!0,!0)},putPayload(){p(a.slice(0,l),!0,!0)},getCache:()=>a.slice(0,l),getPacket:()=>{const e=i,o=c,a=e+o,l=t.uintToBytesBy128(a),d=new Uint8Array(a+l.length+1);d[0]=r;let u=1;return d.set(l,u),u+=l.length,d.set(s.slice(0,e),u),u+=e,d.set(n.slice(0,o),u),d}}},n=e=>(o,r)=>{const s=t.stringToBytes(o),i=t.uintToBytes(s.length,2);r(e),r(i),r(s)},c=e=>(o,t)=>{t(e),t(o?1:0)},a=e=>(o,r)=>{r(e),r(t.uintToBytes(o))},l=e=>(o,r)=>{r(e),r(t.uintToBytes(o,2))},d=e=>(o,r)=>{const s=t.uintToBytes(o.length,2);r(e),r(s),r(o)},u={sessionExpiryInterval:a(o.sessionExpiryInterval),receiveMaximum:l(o.receiveMaximum),maximumPacketSize:a(o.maximumPacketSize),topicAliasMaximum:l(o.topicAliasMaximum),topicAlias:l(o.topicAlias),requestResponseInformation:c(o.requestProblemInformation),requestProblemInformation:c(o.requestProblemInformation),userProperties:(p=o.userProperties,(e,o)=>{Object.keys(e).forEach((r=>{const s=e[r],i=t.stringToBytes(r);Array.isArray(s)?s.forEach((e=>{o(p),o(i),o(t.stringToBytes(e))})):(o(p),o(i),o(t.stringToBytes(s)))}))}),authenticationMethod:n(o.authenticationMethod),authenticationData:d(o.authenticationData),willDelayInterval:a(o.willDelayInterval),payloadFormatIndicator:c(o.payloadFormatIndicator),messageExpiryInterval:a(o.messageExpiryInterval),contentType:n(o.contentType),responseTopic:n(o.responseTopic),correlationData:d(o.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t.uintToBytesBy128(o))})(o.subscriptionIdentifier)};var p;const f=(e,o)=>{Object.keys(e||{}).map((t=>{u[t]&&u[t](e[t],o)}))},m=(o,t)=>{const{properties:r,reasonCode:s}=t,n=i(e.AUTH);if(n.header(s),!r)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return f(r,n.cache),n.putHeader(),o.send(n.getPacket())},y=[],v=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};const g=(e,o)=>[t.bytesToUint(e.slice(o,o+=2)),o],h=(e,o)=>[t.bytesToUint(e.slice(o,o+=4)),o],C=(e,o)=>[1===e[o++],o],T=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[t.bytesToString(e.slice(o,o+=r)),o]},M=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[e.slice(o,o+=r),o]},b={sessionExpiryInterval:h,receiveMaximum:g,maximumPacketSize:h,topicAliasMaximum:g,topicAlias:g,requestResponseInformation:C,requestProblemInformation:C,userProperties:(e,o)=>{const[t,r]=T(e,o),[s,i]=T(e,r);return[[t,s],i]},authenticationMethod:T,authenticationData:M,willDelayInterval:h,payloadFormatIndicator:C,messageExpiryInterval:h,contentType:T,responseTopic:T,correlationData:M,subscriptionIdentifier:(e,o)=>{const{num:r,end:s}=t.bytesToIntBy128(e,o);return[r,s]}},P=e=>{let t=e.length>0,r=0;const s={};for(;t;){const i=e[r++],n=Object.keys(o).find((e=>o[e]===i));if(!n)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const c=b[n](e,r);if(i===o.userProperties){const e=s[n],o=c[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else s[n]=c[0];r=c[1],t=r<e.length}}return s},B=(e,o)=>{const{end:r}=t.bytesToIntBy128(e,1),s=e.slice(r),i=t.bytesToUint(s.slice(0,2));let n,c=0;if(5===o.protocolVersion){c=s[2];const{num:o,end:r}=t.bytesToIntBy128(s,3);n=P(e.slice(r,o))}return{id:i,reasonCode:c,properties:n}},I=(o,r)=>s(void 0,void 0,void 0,(function*(){const{dup:s,qos:n=0,topicName:c,id:a,properties:l,payload:d}=r;let u=0|(s?0===n?0:8:0);u|=n<<1;const p=i(e.PUBLISH,u);p.header(t.stringToBytes(c),!0),n>0&&p.header(t.uintToBytes(a,2)),5===o.protocolVersion&&(f(l,p.cache),p.putHeader()),p.payload(d,!1);try{yield o.send(p.getPacket())}catch(e){return void o.emitError(e)}if(0!==n)if(1===n)try{yield q(o,r)}catch(e){I(o,r)}else try{const e=yield x(o,a);o.options.onPubrel?A(o,o.options.onPubrel(e)):A(o,{id:a,reasonCode:0}),yield N(o,r)}catch(e){I(o,r)}})),E=(e,o,r,n=0)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:c,reasonCode:a}=o,l=i(r,n);l.header(t.uintToBytes(s,2)),5===e.protocolVersion&&(l.header(a||0),f(c,l.cache),l.putHeader()),e.send(l.getPacket())})),w=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBACK)})),A=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),U=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREC,0)})),S=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBCOMP,0)})),q=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBACK){const e=B(c,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),x=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBREC){const e=B(c,o);if(e.id===t)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),N=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=c=>{if(c[0]>>4===e.PUBCOMP){const e=B(c,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))}));v((()=>!(!window||!window.WebSocket)),((e,o)=>s(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const s=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(s),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",(o=>{o.data instanceof ArrayBuffer?e(o):o.data instanceof Blob&&o.data.arrayBuffer().then((o=>{e({data:o})}))}))},onError:e=>{t.addEventListener("error",e)}}}))));v((()=>!("undefined"==typeof wx||!t.BaseApi.hasBaseApi("connectSocket"))),((e,o)=>s(void 0,void 0,void 0,(function*(){const r=yield((e,o)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=t.BaseApi.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:s});i&&r(i)}))})))(e,o);return{onOpen:e=>{r.onOpen(e)},send:e=>new Promise(((o,t)=>{r.send({data:e,fail:t,success:o})})),close:()=>{r.close()},onClose:e=>{r.onClose(e)},onMessage:e=>{r.onMessage(e)},onError:e=>{r.onError(e)}}}))));const k=(e,o)=>{const r=(e=>{let o=0;const r=e[o++],{num:s,end:i}=t.bytesToIntBy128(e,1);return{reasonCode:r,properties:P(e.slice(i,i+s))}})(e);if(24===r.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};m(o,o.options.onAuth(r))}},O=(e,o)=>{const r=((e,o)=>{const r=e[0],s=(6&r)>>1,i=(8&r)>>3==1;let n=1;const{num:c,end:a}=t.bytesToIntBy128(e,n),l=a+c;n=a;const d=T(e,n),[u]=d;let p,f;if(n=d[1],s>0&&(p=t.bytesToUint(e.slice(n,n+=2))),5===o.protocolVersion){const{num:o,end:r}=t.bytesToIntBy128(e,n);f=P(e.slice(r,o)),n=o+r}return{qos:s,dup:i,topicName:u,id:p,payload:e.slice(n,l),properties:f}})(e,o);let{topicName:s}=r;if(o.protocolVersion>=5&&r.properties){const{topicAlias:e}=r.properties;if(e)if(s)o.applyTopic(e,s);else if(s=o.getTopic(e),!s)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(s))switch(r.qos){case 0:o.emitMqttMessage({topic:s,payload:r.payload});break;case 1:o.options.onPuback?w(o,o.options.onPuback(r)):w(o,{id:r.id,reasonCode:0});break;case 2:o.options.onPubrec?U(o,o.options.onPubrec(r)):U(o,{id:r.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},R=(e,o)=>{const t=B(e,o);o.options.onPubcomp?S(o,o.options.onPubcomp(t)):S(o,{id:t.id,reasonCode:0})},D=o=>{const t=1e3*(o.options.keepalive||60),r=()=>s(void 0,void 0,void 0,(function*(){try{!o.isClose()&&(yield(o=>(o.send(new Uint8Array([e.PINGREQ<<4,0])),new Promise(((t,r)=>{const s=r=>{r[0]>>4===e.PINGRESP&&(o.offMessage(s),clearTimeout(i),t(!0))};o.onMessage(s);const i=setTimeout((()=>{o.offMessage(s),o.close(),r({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(o)),setTimeout(r,t)}catch(e){console.warn("ping error",e),o.emitError(e),o.close(e)}}));setTimeout(r,t)};exports.createMQTT=o=>s(void 0,void 0,void 0,(function*(){const n=yield(e=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let i=0;const n=r.createEmitter();let c=null,a=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(r=!1)=>s(void 0,void 0,void 0,(function*(){if(r&&c)try{c.close()}catch(e){}const s=++a;return i=0,c=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{i=2,o(new Error("ws connect time out"))}),1e4);c&&c.onError((e=>{if(0===i)clearTimeout(t),o(e);else if(s===a){const o=i;i=2,n.emit("error",e),2==o&&n.emit("close",e)}})),c&&c.onOpen((()=>{clearTimeout(t),i=1,c&&c.onClose((e=>{if(s===a){const o=i;i=2,2==o&&n.emit("close",e)}})),c&&c.onMessage((e=>{s===a&&n.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===i,isOnline:()=>1===i,getStatus:()=>i,send:e=>{if(c&&1===i)return c.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{n.on("close",e)},offClose:e=>{n.off("close",e)},onError:e=>{n.on("error",e)},offError:e=>{n.off("error",e)},onMessage:e=>{n.on("message",e)},offMessage:e=>{n.off("message",e)},close:e=>{const o=i;i=2,2!==o&&n.emit("close",e),c&&c.close()},emitError:e=>{n.emit("error",e)},emitMqttMessage:e=>{n.emit("mqttMessage",e)},onMqttMessage:e=>{n.on("mqttMessage",e)},offMqttMessage:e=>{n.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(o);yield n.connect(),n.onMessage((o=>{((o,r)=>{const s=o[0]>>4,{end:i,num:n}=t.bytesToIntBy128(o,1);switch(s){case e.AUTH:return k(o.slice(i,i+n),r);case e.PUBLISH:return O(o,r);case e.PUBCOMP:return R(o,r);case e.DISCONNECT:r.close()}})(o,n)})),yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:s=4,connectTimeout:n=10,username:c,password:a,will:l,keepalive:d=60,clean:u,clientId:p}=r,m=i(e.CONNECT);m.header([0,4,77,81,84,84]),m.header(s);let y=0;if(y|=c?128:0,y|=a?64:0,y|=l&&l.retain?32:0,y|=l&&l.qos?l.qos<<3:0,y|=l?4:0,y|=u?2:0,m.header(y),m.header(t.uintToBytes(d,2)),5===s&&(f(r.properties,m.cache),m.putHeader()),s<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===u)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(p),l){if(5===s){if(!l.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),f(l.properties,m.cache),m.putPayload()}if(!l.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(l.topic),!l.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(l.payload)}return c&&m.payload(c),a&&m.payload(a),o.send(m.getPacket()),new Promise(((r,s)=>{const i=n=>{if(n[0]>>4===e.CONNACK){o.offMessage(i),clearTimeout(c);const{end:e}=t.bytesToIntBy128(n,1),a=n.slice(e),l=1&a[0];o.sessionPresent=l;const d=a[1];return 0===d?void r(!0):void s({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};o.onMessage(i);const c=setTimeout((()=>{o.offMessage(i),o.close(),s({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*n)}))})))(n,o),D(n);let c=0;const a=()=>(++c,16777215===c&&(c=1),c);return{getStatus:n.getStatus,onMessage:n.onMqttMessage,offMessage:n.offMqttMessage,subscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>!n.checkTopic(e.topic)))).length){const c=yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:c}=r,a=i(e.SUBSCRIBE,2);if(a.header(t.uintToBytes(s,2)),5===o.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};f(n,a.cache),a.putHeader()}return c.forEach((e=>{a.payload(e.topic);let t=e.qos||0;if(5===o.protocolVersion){const{nl:o=0,rap:r=0,rh:s=0}=e;t|=o<<2,t|=r<<3,t|=s<<4}a.payload(t,!1)})),o.send(a.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.SUBACK){const e=t.bytesToIntBy128(i,1),a=e.end+e.num,l=i.slice(e.end,a);if(t.bytesToUint(l.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(l,s);s=o+r,e=P(l.slice(o,s))}const i=l.slice(s);o.offMessage(n),clearTimeout(c),r({reasonCode:i,properties:e})}}};o.onMessage(n);const c=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(n,{id:a(),properties:null==r?void 0:r.properties,payload:o}),l=o.reduce(((e,t,r)=>(c.reasonCode[r]>=128?e[t.topic]=c.reasonCode[r]:o.map((e=>n.addTopic(e.topic))),e)),{});return{properties:c.properties,err:Object.keys(l).length?l:void 0}}return{}})),unsubscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>n.checkTopic(e)))).length){const s=yield((o,r)=>{const{id:s,properties:n,topics:c}=r,a=i(e.UNSUBSCRIBE,2);return a.header(t.uintToBytes(s,2)),5===o.protocolVersion&&(f(n,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),o.send(a.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.UNSUBACK){const e=t.bytesToIntBy128(i,1),l=e.end+e.num,d=i.slice(e.end,l);if(t.bytesToUint(d.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(d,s);s=o+r,e=P(d.slice(o,s))}const i=d.slice(s);o.offMessage(n),clearTimeout(a),i.length?r({reasonCode:i,properties:e}):r({reasonCode:new Uint8Array(c.map((()=>0))),properties:e})}}};o.onMessage(n);const a=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(n,{id:a(),properties:null==r?void 0:r.properties,topics:o}),c=o.reduce(((e,t,r)=>(s.reasonCode[r]>=128?e[t]=s.reasonCode[r]:o.map((e=>n.removeTopic(e))),e)),{});return{err:Object.keys(c).length?c:void 0}}return{}})),publish:(e,o,r)=>{const s=a();return I(n,Object.assign({id:s,topicName:e,payload:"string"==typeof o?t.stringToBytes(o):o},r))},reAuth:e=>{m(n,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:o=>{((o,t)=>{s(void 0,void 0,void 0,(function*(){const{reasonCode:r=0,properties:s}=t,n=i(e.DISCONNECT);5===o.protocolVersion&&(n.header(r),f(s,n.cache),n.putHeader()),yield o.send(n.getPacket()),o.close()}))})(n,o||{reasonCode:0})},onClose:n.onClose,onError:n.onError}}));
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,o,t=require("@ray-js/wechat-helper"),r=require("@ray-js/wechat-event");function s(e,o,t,r){return new(t||(t=Promise))((function(s,i){function n(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var o;e.done?s(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,a)}c((r=r.apply(e,o||[])).next())}))}!function(e){e[e.Reserved=0]="Reserved",e[e.CONNECT=1]="CONNECT",e[e.CONNACK=2]="CONNACK",e[e.PUBLISH=3]="PUBLISH",e[e.PUBACK=4]="PUBACK",e[e.PUBREC=5]="PUBREC",e[e.PUBREL=6]="PUBREL",e[e.PUBCOMP=7]="PUBCOMP",e[e.SUBSCRIBE=8]="SUBSCRIBE",e[e.SUBACK=9]="SUBACK",e[e.UNSUBSCRIBE=10]="UNSUBSCRIBE",e[e.UNSUBACK=11]="UNSUBACK",e[e.PINGREQ=12]="PINGREQ",e[e.PINGRESP=13]="PINGRESP",e[e.DISCONNECT=14]="DISCONNECT",e[e.AUTH=15]="AUTH"}(e||(e={})),function(e){e[e.sessionExpiryInterval=17]="sessionExpiryInterval",e[e.receiveMaximum=33]="receiveMaximum",e[e.maximumQoS=36]="maximumQoS",e[e.retainAvailable=37]="retainAvailable",e[e.maximumPacketSize=39]="maximumPacketSize",e[e.topicAliasMaximum=34]="topicAliasMaximum",e[e.topicAlias=35]="topicAlias",e[e.requestResponseInformation=25]="requestResponseInformation",e[e.requestProblemInformation=23]="requestProblemInformation",e[e.userProperties=38]="userProperties",e[e.authenticationMethod=21]="authenticationMethod",e[e.authenticationData=22]="authenticationData",e[e.willDelayInterval=24]="willDelayInterval",e[e.payloadFormatIndicator=1]="payloadFormatIndicator",e[e.messageExpiryInterval=2]="messageExpiryInterval",e[e.contentType=3]="contentType",e[e.responseTopic=8]="responseTopic",e[e.correlationData=9]="correlationData",e[e.subscriptionIdentifier=11]="subscriptionIdentifier",e[e.reasonString=31]="reasonString",e[e.assignedClientIdentifier=18]="assignedClientIdentifier",e[e.wildcardSubscriptionAvailable=40]="wildcardSubscriptionAvailable",e[e.subscriptionIdentifiersAvailable=41]="subscriptionIdentifiersAvailable",e[e.sharedSubscriptionAvailable=42]="sharedSubscriptionAvailable",e[e.serverKeepAlive=19]="serverKeepAlive",e[e.responseInformation=26]="responseInformation",e[e.serverReference=28]="serverReference"}(o||(o={}));const i=(e,o=0)=>{const r=e<<4|o;let s=new Uint8Array(100),i=0,n=new Uint8Array(100),a=0,c=new Uint8Array(100),l=0;const d=(e,o,r,s=!1,i=!1)=>{let n;n="string"==typeof r?t.stringToBytes(r):"number"==typeof r?[r]:r;let a=new Uint8Array;s&&(a=i?t.uintToBytesBy128(n.length):t.uintToBytes(n.length,2));return e=((e,o)=>{if(o>=e.length){const t=new Uint8Array(o+1);return t.set(e,0),t}return e})(e,o+(n.length+a.length)),s&&e.set(a,o),o+=a.length,e.set(n,o),[e,o+=n.length]};function p(e,o=!1,t=!1){const[r,n]=d(s,i,e,o,t);s=r,i=n}function u(e,o=!0,t=!1){const[r,s]=d(n,a,e,o,t);n=r,a=s}return{header:p,payload:u,cleanCache(){c=new Uint8Array(100),l=0},cache:(e,o=!1,t=!1)=>{const[r,s]=d(c,l,e,o,t);c=r,l=s},putHeader(){p(c.slice(0,l),!0,!0)},putPayload(){u(c.slice(0,l),!0,!0)},getCache:()=>c.slice(0,l),getPacket:()=>{const e=i,o=a,c=e+o,l=t.uintToBytesBy128(c),d=new Uint8Array(c+l.length+1);d[0]=r;let p=1;return d.set(l,p),p+=l.length,d.set(s.slice(0,e),p),p+=e,d.set(n.slice(0,o),p),d}}},n=e=>(o,r)=>{const s=t.stringToBytes(o),i=t.uintToBytes(s.length,2);r(e),r(i),r(s)},a=e=>(o,t)=>{t(e),t(o?1:0)},c=e=>(o,r)=>{r(e),r(t.uintToBytes(o))},l=e=>(o,r)=>{r(e),r(t.uintToBytes(o,2))},d=e=>(o,r)=>{const s=t.uintToBytes(o.length,2);r(e),r(s),r(o)},p={sessionExpiryInterval:c(o.sessionExpiryInterval),receiveMaximum:l(o.receiveMaximum),maximumPacketSize:c(o.maximumPacketSize),topicAliasMaximum:l(o.topicAliasMaximum),topicAlias:l(o.topicAlias),requestResponseInformation:a(o.requestProblemInformation),requestProblemInformation:a(o.requestProblemInformation),userProperties:(u=o.userProperties,(e,o)=>{Object.keys(e).forEach((r=>{const s=e[r],i=t.stringToBytes(r);Array.isArray(s)?s.forEach((e=>{o(u),o(i),o(t.stringToBytes(e))})):(o(u),o(i),o(t.stringToBytes(s)))}))}),authenticationMethod:n(o.authenticationMethod),authenticationData:d(o.authenticationData),willDelayInterval:c(o.willDelayInterval),payloadFormatIndicator:a(o.payloadFormatIndicator),messageExpiryInterval:c(o.messageExpiryInterval),contentType:n(o.contentType),responseTopic:n(o.responseTopic),correlationData:d(o.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t.uintToBytesBy128(o))})(o.subscriptionIdentifier)};var u;const f=(e,o)=>{Object.keys(e||{}).map((t=>{p[t]&&p[t](e[t],o)}))},m=(o,t)=>{const{properties:r,reasonCode:s}=t,n=i(e.AUTH);if(n.header(s),!r)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return f(r,n.cache),n.putHeader(),o.send(n.getPacket())},y=[],v=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};const g=(e,o)=>[t.bytesToUint(e.slice(o,o+=2)),o],h=(e,o)=>[t.bytesToUint(e.slice(o,o+=4)),o],C=(e,o)=>[1===e[o++],o],M=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[t.bytesToString(e.slice(o,o+=r)),o]},T=(e,o)=>{const r=t.bytesToUint(e.slice(o,o+=2));return[e.slice(o,o+=r),o]},b={sessionExpiryInterval:h,receiveMaximum:g,maximumPacketSize:h,topicAliasMaximum:g,topicAlias:g,requestResponseInformation:C,requestProblemInformation:C,userProperties:(e,o)=>{const[t,r]=M(e,o),[s,i]=M(e,r);return[[t,s],i]},authenticationMethod:M,authenticationData:T,willDelayInterval:h,payloadFormatIndicator:C,messageExpiryInterval:h,contentType:M,responseTopic:M,correlationData:T,subscriptionIdentifier:(e,o)=>{const{num:r,end:s}=t.bytesToIntBy128(e,o);return[r,s]}},P=e=>{let t=e.length>0,r=0;const s={};for(;t;){const i=e[r++],n=Object.keys(o).find((e=>o[e]===i));if(!n)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const a=b[n](e,r);if(i===o.userProperties){const e=s[n],o=a[0];void 0!==e[o[0]]?"string"==typeof e[o[0]]?e[o[0]]=[e[o[0]]]:e[o[0]].push(o[1]):e[o[0]]=o[1]}else s[n]=a[0];r=a[1],t=r<e.length}}return s},B=(e,o)=>{const{end:r}=t.bytesToIntBy128(e,1),s=e.slice(r),i=t.bytesToUint(s.slice(0,2));let n,a=0;if(5===o.protocolVersion){a=s[2];const{num:o,end:r}=t.bytesToIntBy128(s,3);n=P(e.slice(r,o))}return{id:i,reasonCode:a,properties:n}},I=(o,r)=>s(void 0,void 0,void 0,(function*(){const{dup:s,qos:n=0,topicName:a,id:c,properties:l,payload:d}=r;let p=0|(s?0===n?0:8:0);p|=n<<1;const u=i(e.PUBLISH,p);u.header(t.stringToBytes(a),!0),n>0&&u.header(t.uintToBytes(c,2)),5===o.protocolVersion&&(f(l,u.cache),u.putHeader()),u.payload(d,!1);try{yield o.send(u.getPacket())}catch(e){return void o.emitError(e)}if(0!==n)if(1===n)try{yield q(o,r)}catch(e){yield I(o,r)}else try{const e=yield x(o,c);o.options.onPubrel?A(o,o.options.onPubrel(e)):A(o,{id:c,reasonCode:0}),yield N(o,r)}catch(e){yield I(o,r)}})),E=(e,o,r,n=0)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:a,reasonCode:c}=o,l=i(r,n);l.header(t.uintToBytes(s,2)),5===e.protocolVersion&&(l.header(c||0),f(a,l.cache),l.putHeader()),e.send(l.getPacket())})),w=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBACK)})),A=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),U=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREC,0)})),S=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBCOMP,0)})),q=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=a=>{if(a[0]>>4===e.PUBACK){const e=B(a,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),x=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=a=>{if(a[0]>>4===e.PUBREC){const e=B(a,o);if(e.id===t)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))})),N=(o,t)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=a=>{if(a[0]>>4===e.PUBCOMP){const e=B(a,o);if(e.id===t.id)if(o.offMessage(i),clearTimeout(n),0===e.reasonCode)r(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};s(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};s(e),o.emitError(e)}),1e4)}))}));v((()=>!(!window||!window.WebSocket)),((e,o)=>s(void 0,void 0,void 0,(function*(){const t=new WebSocket(e,4===o?["mqttv3.1"]:["mqtt"]);return{onOpen:e=>{t.addEventListener("open",e)},send:e=>{t.send(e)},close:()=>0===t.bufferedAmount?t.close():new Promise(((e,o)=>{let r=0;const s=setInterval((()=>{r++,200===r&&o(),0===t.bufferedAmount&&(clearInterval(s),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",(o=>{o.data instanceof ArrayBuffer?e(o):o.data instanceof Blob&&o.data.arrayBuffer().then((o=>{e({data:o})}))}))},onError:e=>{t.addEventListener("error",e)}}}))));v((()=>!("undefined"==typeof wx||!t.BaseApi.hasBaseApi("connectSocket"))),((e,o)=>s(void 0,void 0,void 0,(function*(){const r=yield((e,o)=>s(void 0,void 0,void 0,(function*(){return new Promise(((r,s)=>{const i=t.BaseApi.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:s});i&&r(i)}))})))(e,o);return{onOpen:e=>{r.onOpen(e)},send:e=>new Promise(((o,t)=>{r.send({data:e,fail:t,success:o})})),close:()=>{r.close()},onClose:e=>{r.onClose(e)},onMessage:e=>{r.onMessage(e)},onError:e=>{r.onError(e)}}}))));const k=(e,o)=>{const r=(e=>{let o=0;const r=e[o++],{num:s,end:i}=t.bytesToIntBy128(e,1);return{reasonCode:r,properties:P(e.slice(i,i+s))}})(e);if(24===r.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};m(o,o.options.onAuth(r))}},O=(e,o)=>{const r=((e,o)=>{const r=e[0],s=(6&r)>>1,i=(8&r)>>3==1;let n=1;const{num:a,end:c}=t.bytesToIntBy128(e,n),l=c+a;n=c;const d=M(e,n),[p]=d;let u,f;if(n=d[1],s>0&&(u=t.bytesToUint(e.slice(n,n+=2))),5===o.protocolVersion){const{num:o,end:r}=t.bytesToIntBy128(e,n);f=P(e.slice(r,o)),n=o+r}return{qos:s,dup:i,topicName:p,id:u,payload:e.slice(n,l),properties:f}})(e,o);let{topicName:s}=r;if(o.protocolVersion>=5&&r.properties){const{topicAlias:e}=r.properties;if(e)if(s)o.applyTopic(e,s);else if(s=o.getTopic(e),!s)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(s))switch(r.qos){case 0:o.emitMqttMessage({topic:s,payload:r.payload});break;case 1:if(o.options.onPuback){const e=o.options.onPuback(r);w(o,e),0===e.reasonCode&&o.emitMqttMessage({topic:s,payload:r.payload})}else w(o,{id:r.id,reasonCode:0}),o.emitMqttMessage({topic:s,payload:r.payload});break;case 2:if(o.options.onPubrec){const e=o.options.onPubrec(r);U(o,e),0===e.reasonCode&&o.emitMqttMessage({topic:s,payload:r.payload})}else U(o,{id:r.id,reasonCode:0}),o.emitMqttMessage({topic:s,payload:r.payload})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},R=(e,o)=>{const t=B(e,o);o.options.onPubcomp?S(o,o.options.onPubcomp(t)):S(o,{id:t.id,reasonCode:0})},D=o=>{const t=1e3*(o.options.keepalive||60),r=()=>s(void 0,void 0,void 0,(function*(){try{!o.isClose()&&(yield(o=>(o.send(new Uint8Array([e.PINGREQ<<4,0])),new Promise(((t,r)=>{const s=r=>{r[0]>>4===e.PINGRESP&&(o.offMessage(s),clearTimeout(i),t(!0))};o.onMessage(s);const i=setTimeout((()=>{o.offMessage(s),o.close(),r({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(o)),setTimeout(r,t)}catch(e){console.warn("ping error",e),o.emitError(e),o.close(e)}}));setTimeout(r,t)};exports.createMQTT=o=>s(void 0,void 0,void 0,(function*(){const n=yield(e=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let i=0;const n=r.createEmitter();let a=null,c=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(r=!1)=>s(void 0,void 0,void 0,(function*(){if(r&&a)try{a.close()}catch(e){}const s=++c;return i=0,a=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{i=2,o(new Error("ws connect time out"))}),1e4);a&&a.onError((e=>{if(0===i)clearTimeout(t),o(e);else if(s===c){const o=i;i=2,n.emit("error",e),2==o&&n.emit("close",e)}})),a&&a.onOpen((()=>{clearTimeout(t),i=1,a&&a.onClose((e=>{if(s===c){const o=i;i=2,2==o&&n.emit("close",e)}})),a&&a.onMessage((e=>{s===c&&n.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===i,isOnline:()=>1===i,getStatus:()=>i,send:e=>{if(a&&1===i)return a.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{n.on("close",e)},offClose:e=>{n.off("close",e)},onError:e=>{n.on("error",e)},offError:e=>{n.off("error",e)},onMessage:e=>{n.on("message",e)},offMessage:e=>{n.off("message",e)},close:e=>{const o=i;i=2,2!==o&&n.emit("close",e),a&&a.close()},emitError:e=>{n.emit("error",e)},emitMqttMessage:e=>{n.emit("mqttMessage",e)},onMqttMessage:e=>{n.on("mqttMessage",e)},offMqttMessage:e=>{n.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],addTopic:e=>{-1===d.indexOf(e)&&d.push(e)},removeTopic:e=>{const o=d.indexOf(e);o>=0&&d.splice(o,1)},clearTopic:()=>{d.length=0},checkTopic:e=>d.some((o=>function(e,o){const t=e.split("/"),r=e.split("/");if(e===o)return!0;for(let e=0;e<r.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==r[e])return!1}}return!1}(o,e)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(o);yield n.connect(),n.onMessage((o=>{((o,r)=>{const s=o[0]>>4,{end:i,num:n}=t.bytesToIntBy128(o,1);switch(s){case e.AUTH:return k(o.slice(i,i+n),r);case e.PUBLISH:return O(o,r);case e.PUBCOMP:return R(o,r);case e.DISCONNECT:r.close()}})(o,n)})),yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{protocolVersion:s=4,connectTimeout:n=10,username:a,password:c,will:l,keepalive:d=60,clean:p,clientId:u}=r,m=i(e.CONNECT);m.header([0,4,77,81,84,84]),m.header(s);let y=0;if(y|=a?128:0,y|=c?64:0,y|=l&&l.retain?32:0,y|=l&&l.qos?l.qos<<3:0,y|=l?4:0,y|=p?2:0,m.header(y),m.header(t.uintToBytes(d,2)),5===s&&(f(r.properties,m.cache),m.putHeader()),s<4)throw{errCode:63001,errMsg:"ClientId must be supplied before 3.1.1"};if(!1===p)throw{errCode:63002,errMsg:"ClientId must be given if clean set to 0"};if(m.payload(u),l){if(5===s){if(!l.properties)throw{errCode:63006,errMsg:"Will properties must be given if will has seted, when protocol version is 5.x "};m.cleanCache(),f(l.properties,m.cache),m.putPayload()}if(!l.topic)throw{errCode:63003,errMsg:"Will topic must be given if will has seted"};if(m.payload(l.topic),!l.payload)throw{errCode:63004,errMsg:"Will payload must be given if will has seted"};m.payload(l.payload)}return a&&m.payload(a),c&&m.payload(c),o.send(m.getPacket()),new Promise(((r,s)=>{const i=n=>{if(n[0]>>4===e.CONNACK){o.offMessage(i),clearTimeout(a);const{end:e}=t.bytesToIntBy128(n,1),c=n.slice(e),l=1&c[0];o.sessionPresent=l;const d=c[1];return 0===d?void r(!0):void s({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};o.onMessage(i);const a=setTimeout((()=>{o.offMessage(i),o.close(),s({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*n)}))})))(n,o),D(n);let a=0;const c=()=>(++a,16777215===a&&(a=1),a);return{getStatus:n.getStatus,onMessage:n.onMqttMessage,offMessage:n.offMqttMessage,subscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>!n.checkTopic(e.topic)))).length){const a=yield((o,r)=>s(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:a}=r,c=i(e.SUBSCRIBE,2);if(c.header(t.uintToBytes(s,2)),5===o.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};f(n,c.cache),c.putHeader()}return a.forEach((e=>{c.payload(e.topic);let t=e.qos||0;if(5===o.protocolVersion){const{nl:o=0,rap:r=0,rh:s=0}=e;t|=o<<2,t|=r<<3,t|=s<<4}c.payload(t,!1)})),o.send(c.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.SUBACK){const e=t.bytesToIntBy128(i,1),c=e.end+e.num,l=i.slice(e.end,c);if(t.bytesToUint(l.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(l,s);s=o+r,e=P(l.slice(o,s))}const i=l.slice(s);o.offMessage(n),clearTimeout(a),r({reasonCode:i,properties:e})}}};o.onMessage(n);const a=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(n,{id:c(),properties:null==r?void 0:r.properties,payload:o}),l=o.reduce(((e,t,r)=>(a.reasonCode[r]>=128?e[t.topic]=a.reasonCode[r]:o.map((e=>n.addTopic(e.topic))),e)),{});return{properties:a.properties,err:Object.keys(l).length?l:void 0}}return{}})),unsubscribe:(o,r)=>s(void 0,void 0,void 0,(function*(){if((o=o.filter((e=>n.checkTopic(e)))).length){const s=yield((o,r)=>{const{id:s,properties:n,topics:a}=r,c=i(e.UNSUBSCRIBE,2);return c.header(t.uintToBytes(s,2)),5===o.protocolVersion&&(f(n,c.cache),c.putHeader()),a.forEach((e=>{c.payload(e)})),o.send(c.getPacket()),new Promise(((r,i)=>{const n=i=>{if(i[0]>>4===e.UNSUBACK){const e=t.bytesToIntBy128(i,1),l=e.end+e.num,d=i.slice(e.end,l);if(t.bytesToUint(d.slice(0,2))===s){let e,s=2;if(5===o.protocolVersion){const{end:o,num:r}=t.bytesToIntBy128(d,s);s=o+r,e=P(d.slice(o,s))}const i=d.slice(s);o.offMessage(n),clearTimeout(c),i.length?r({reasonCode:i,properties:e}):r({reasonCode:new Uint8Array(a.map((()=>0))),properties:e})}}};o.onMessage(n);const c=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(n,{id:c(),properties:null==r?void 0:r.properties,topics:o}),a=o.reduce(((e,t,r)=>(s.reasonCode[r]>=128?e[t]=s.reasonCode[r]:o.map((e=>n.removeTopic(e))),e)),{});return{err:Object.keys(a).length?a:void 0}}return{}})),publish:(e,o,r)=>{const s=c();return I(n,Object.assign({id:s,topicName:e,payload:"string"==typeof o?t.stringToBytes(o):o},r))},reAuth:e=>{m(n,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:o=>{((o,t)=>{s(void 0,void 0,void 0,(function*(){const{reasonCode:r=0,properties:s}=t,n=i(e.DISCONNECT);5===o.protocolVersion&&(n.header(r),f(s,n.cache),n.putHeader()),yield o.send(n.getPacket()),o.close()}))})(n,o||{reasonCode:0})},onClose:n.onClose,onError:n.onError}}));
|
package/lib/interface.d.ts
CHANGED
|
@@ -144,7 +144,7 @@ export interface Client {
|
|
|
144
144
|
getStatus(): 0 | 1 | 2;
|
|
145
145
|
onMessage(cb: (data: MQTTMessage) => void): void;
|
|
146
146
|
offMessage(cb: (data: MQTTMessage) => void): void;
|
|
147
|
-
publish(topic: string, message: string | Uint8Array, option?: MessageOption): void
|
|
147
|
+
publish(topic: string, message: string | Uint8Array, option?: MessageOption): Promise<void>;
|
|
148
148
|
reAuth(option: AuthOptions): void;
|
|
149
149
|
disconnect(option?: DisconnectOptions): void;
|
|
150
150
|
onClose(cb: () => void): void;
|
package/lib/publish.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ClientConntroller, Message, PuplishResponse } from
|
|
1
|
+
import { ClientConntroller, Message, PuplishResponse } from './interface';
|
|
2
2
|
export declare const publish: (client: ClientConntroller, message: Message) => Promise<void>;
|
|
3
3
|
export declare const puback: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
4
4
|
export declare const pubrel: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
package/lib/response.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { ClientConntroller } from
|
|
1
|
+
import { ClientConntroller } from './interface';
|
|
2
2
|
export declare const handleResponse: (data: Uint8Array, client: ClientConntroller) => void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ray-js/wechat-mqtt-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.7",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@ray-js/wechat-helper": "^0.3.
|
|
27
|
-
"@ray-js/wechat-event": "^0.3.
|
|
26
|
+
"@ray-js/wechat-helper": "^0.3.7",
|
|
27
|
+
"@ray-js/wechat-event": "^0.3.7"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {}
|
|
30
30
|
}
|