@ray-js/wechat-mqtt-core 0.3.6-beta-1
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.d.ts +4 -0
- package/index.esm.js +1 -0
- package/index.js +1 -0
- package/lib/adapter/blowser.d.ts +1 -0
- package/lib/adapter/index.d.ts +2 -0
- package/lib/adapter/wechat.d.ts +1 -0
- package/lib/auth.d.ts +2 -0
- package/lib/connect.d.ts +2 -0
- package/lib/constant.d.ts +47 -0
- package/lib/disconnect.d.ts +2 -0
- package/lib/factory.d.ts +6 -0
- package/lib/interface.d.ts +178 -0
- package/lib/packet.d.ts +35 -0
- package/lib/parse.d.ts +24 -0
- package/lib/ping.d.ts +2 -0
- package/lib/publish.d.ts +6 -0
- package/lib/response.d.ts +2 -0
- package/lib/subscribe.d.ts +31 -0
- package/package.json +32 -0
package/index.d.ts
ADDED
package/index.esm.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
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 c}from"@ray-js/wechat-event";function a(e,o,t,r){return new(t||(t=Promise))((function(i,s){function n(e){try{a(r.next(e))}catch(e){s(e)}}function c(e){try{a(r.throw(e))}catch(e){s(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(n,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 s=r<<4|i;let n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0,d=new Uint8Array(100),p=0;const u=(r,i,s,n=!1,c=!1)=>{let a;a="string"==typeof s?e(s):"number"==typeof s?[s]:s;let l=new Uint8Array;n&&(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)),n&&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(n,c,e,o,t);n=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]=s;let p=1;return d.set(i,p),p+=i.length,d.set(n.slice(0,e),p),p+=e,d.set(a.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 c,a=0;if(5===o.protocolVersion){a=s[2];const{num:o,end:t}=r(s,3);c=S(e.slice(t,o))}return{id:n,reasonCode:a,properties:c}},q=(t,r)=>a(void 0,void 0,void 0,(function*(){const{dup:i,qos:s=0,topicName:n,id:c,properties:a,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(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!==s)if(1===s)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:s,properties:n,reasonCode:c}=t,a=p(r,i);a.header(o(s,2)),5===e.protocolVersion&&(a.header(c||0),M(n,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=n=>{if(n[0]>>4===l.PUBACK){const c=B(n,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(s),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 s=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=n=>{if(n[0]>>4===l.PUBREC){const c=B(n,e);if(c.id===o)if(e.offMessage(i),clearTimeout(s),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 s=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=n=>{if(n[0]>>4===l.PUBCOMP){const c=B(n,e);if(c.id===o.id)if(e.offMessage(i),clearTimeout(s),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 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)=>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",e)},onError:e=>{t.addEventListener("error",e)}}}))));b((()=>!("undefined"==typeof wx||!n.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=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 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],s>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:s,dup:n,topicName:u,id:f,payload:e.slice(c,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: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 s=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 s=null,n=0;const l={},d=[];return{options:e,protocolVersion:o,sessionPresent:0,connect:(c=!1)=>a(void 0,void 0,void 0,(function*(){if(c&&s)try{s.close()}catch(e){}const a=++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(a===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(a===n){const o=r;r=2,2==o&&i.emit("close",e)}})),s&&s.onMessage((e=>{a===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)=>a(void 0,void 0,void 0,(function*(){const{protocolVersion:i=4,connectTimeout:s=10,username:n,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|=n?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 n&&m.payload(n),c&&m.payload(c),e.send(m.getPacket()),new Promise(((o,t)=>{const i=s=>{if(s[0]>>4===l.CONNACK){e.offMessage(i),clearTimeout(n);const{end:c}=r(s,1),a=s.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 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)=>a(void 0,void 0,void 0,(function*(){if((e=e.filter((e=>!s.checkTopic(e.topic)))).length){const n=yield((e,t)=>a(void 0,void 0,void 0,(function*(){const{id:s,properties:n,payload:c}=t,a=p(l.SUBSCRIBE,2);if(a.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,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 n=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))===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(c),o({reasonCode:s,properties:t})}}};e.onMessage(n);const c=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}),c=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(c).length?c:void 0}}return{}})),unsubscribe:(e,t)=>a(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:c}=t,a=p(l.UNSUBSCRIBE,2);return a.header(o(s,2)),5===e.protocolVersion&&(M(n,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),e.send(a.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(a),s.length?o({reasonCode:s,properties:t}):o({reasonCode:new Uint8Array(c.map((()=>0))),properties:t})}}};e.onMessage(n);const a=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}),c=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(c).length?c: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)=>{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()}))})(s,e||{reasonCode:0})},onClose:s.onClose,onError:s.onError}}));export{z as createMQTT};
|
package/index.js
ADDED
|
@@ -0,0 +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},I=(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}},B=(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){B(o,r)}else try{const e=yield x(o,a);o.options.onPubrel?U(o,o.options.onPubrel(e)):U(o,{id:a,reasonCode:0}),yield N(o,r)}catch(e){B(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)})),U=(o,t)=>s(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),A=(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=I(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=I(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=I(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",e)},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?A(o,o.options.onPubrec(r)):A(o,{id:r.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},R=(e,o)=>{const t=I(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 B(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}}));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/lib/auth.d.ts
ADDED
package/lib/connect.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export declare enum PacketType {
|
|
2
|
+
Reserved = 0,
|
|
3
|
+
CONNECT = 1,
|
|
4
|
+
CONNACK = 2,
|
|
5
|
+
PUBLISH = 3,
|
|
6
|
+
PUBACK = 4,
|
|
7
|
+
PUBREC = 5,
|
|
8
|
+
PUBREL = 6,
|
|
9
|
+
PUBCOMP = 7,
|
|
10
|
+
SUBSCRIBE = 8,
|
|
11
|
+
SUBACK = 9,
|
|
12
|
+
UNSUBSCRIBE = 10,
|
|
13
|
+
UNSUBACK = 11,
|
|
14
|
+
PINGREQ = 12,
|
|
15
|
+
PINGRESP = 13,
|
|
16
|
+
DISCONNECT = 14,
|
|
17
|
+
AUTH = 15
|
|
18
|
+
}
|
|
19
|
+
export declare enum PropertySign {
|
|
20
|
+
sessionExpiryInterval = 17,
|
|
21
|
+
receiveMaximum = 33,
|
|
22
|
+
maximumQoS = 36,
|
|
23
|
+
retainAvailable = 37,
|
|
24
|
+
maximumPacketSize = 39,
|
|
25
|
+
topicAliasMaximum = 34,
|
|
26
|
+
topicAlias = 35,
|
|
27
|
+
requestResponseInformation = 25,
|
|
28
|
+
requestProblemInformation = 23,
|
|
29
|
+
userProperties = 38,
|
|
30
|
+
authenticationMethod = 21,
|
|
31
|
+
authenticationData = 22,
|
|
32
|
+
willDelayInterval = 24,
|
|
33
|
+
payloadFormatIndicator = 1,
|
|
34
|
+
messageExpiryInterval = 2,
|
|
35
|
+
contentType = 3,
|
|
36
|
+
responseTopic = 8,
|
|
37
|
+
correlationData = 9,
|
|
38
|
+
subscriptionIdentifier = 11,
|
|
39
|
+
reasonString = 31,
|
|
40
|
+
assignedClientIdentifier = 18,
|
|
41
|
+
wildcardSubscriptionAvailable = 40,
|
|
42
|
+
subscriptionIdentifiersAvailable = 41,
|
|
43
|
+
sharedSubscriptionAvailable = 42,
|
|
44
|
+
serverKeepAlive = 19,
|
|
45
|
+
responseInformation = 26,
|
|
46
|
+
serverReference = 28
|
|
47
|
+
}
|
package/lib/factory.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { Adapter, ClientConntroller, Options } from './interface';
|
|
2
|
+
declare type Judge = () => boolean;
|
|
3
|
+
declare type Connect = (url: string, version?: number) => Promise<Adapter>;
|
|
4
|
+
export declare const addAdapter: (judge: Judge, creater: Connect, priority?: boolean) => void;
|
|
5
|
+
export declare const createClient: (options: Options) => Promise<ClientConntroller>;
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
export interface Adapter {
|
|
2
|
+
close: () => void;
|
|
3
|
+
onClose(cb: (ev: any) => void): void;
|
|
4
|
+
send(data: ArrayBuffer | ArrayBufferView): void;
|
|
5
|
+
onMessage(cb: (res: {
|
|
6
|
+
data: ArrayBuffer;
|
|
7
|
+
}) => void): void;
|
|
8
|
+
onOpen(cb: (data: any) => void): void;
|
|
9
|
+
onError(cb: (ev: any) => void): void;
|
|
10
|
+
}
|
|
11
|
+
export interface MQTTMessage {
|
|
12
|
+
topic: string;
|
|
13
|
+
payload: Uint8Array;
|
|
14
|
+
}
|
|
15
|
+
export interface ClientConntroller {
|
|
16
|
+
options: Options;
|
|
17
|
+
protocolVersion: number;
|
|
18
|
+
sessionPresent: number;
|
|
19
|
+
connect(isReconnect?: boolean): Promise<any>;
|
|
20
|
+
isClose(): boolean;
|
|
21
|
+
isOnline(): boolean;
|
|
22
|
+
getStatus(): 0 | 1 | 2;
|
|
23
|
+
close: (err?: any) => void;
|
|
24
|
+
onClose(cb: (ev: any) => void): void;
|
|
25
|
+
send(data: ArrayBuffer | ArrayBufferView): void;
|
|
26
|
+
onError(cb: (ev: any) => void): void;
|
|
27
|
+
onMessage(cb: (data: Uint8Array) => void): void;
|
|
28
|
+
offMessage(cb: (data: Uint8Array) => void): void;
|
|
29
|
+
offClose(cb: (ev: any) => void): void;
|
|
30
|
+
offError(cb: (ev: any) => void): void;
|
|
31
|
+
emitError(data: any): void;
|
|
32
|
+
emitMqttMessage(data: MQTTMessage): void;
|
|
33
|
+
onMqttMessage(cb: (data: MQTTMessage) => void): void;
|
|
34
|
+
offMqttMessage(cb: (data: MQTTMessage) => void): void;
|
|
35
|
+
applyTopic: (topicAlias: number, topicName: string) => void;
|
|
36
|
+
getTopic: (topicAlias: number) => string;
|
|
37
|
+
checkTopic: (topicName: string) => boolean;
|
|
38
|
+
addTopic: (topic: string) => void;
|
|
39
|
+
removeTopic: (topic: string) => void;
|
|
40
|
+
clearTopic: () => void;
|
|
41
|
+
}
|
|
42
|
+
export declare type QoS = 0 | 1 | 2;
|
|
43
|
+
export declare type UserProperties = Record<string, string | string[]>;
|
|
44
|
+
export interface Options {
|
|
45
|
+
url: string;
|
|
46
|
+
username?: string;
|
|
47
|
+
password?: string;
|
|
48
|
+
clientId: string;
|
|
49
|
+
protocolVersion?: number;
|
|
50
|
+
keepalive?: number;
|
|
51
|
+
clean?: boolean;
|
|
52
|
+
will?: {
|
|
53
|
+
topic: string;
|
|
54
|
+
payload: Uint8Array | string;
|
|
55
|
+
qos: QoS;
|
|
56
|
+
retain: boolean;
|
|
57
|
+
properties?: {
|
|
58
|
+
willDelayInterval?: number;
|
|
59
|
+
payloadFormatIndicator?: boolean;
|
|
60
|
+
sessionExpiryInterval?: number;
|
|
61
|
+
contentType?: string;
|
|
62
|
+
responseTopic?: string;
|
|
63
|
+
correlationData?: Uint8Array;
|
|
64
|
+
userProperties?: UserProperties;
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
properties?: {
|
|
68
|
+
sessionExpiryInterval?: number;
|
|
69
|
+
receiveMaximum?: number;
|
|
70
|
+
maximumPacketSize?: number;
|
|
71
|
+
topicAliasMaximum?: number;
|
|
72
|
+
requestResponseInformation?: boolean;
|
|
73
|
+
requestProblemInformation?: boolean;
|
|
74
|
+
userProperties?: UserProperties;
|
|
75
|
+
authenticationMethod?: string;
|
|
76
|
+
authenticationData?: Uint8Array;
|
|
77
|
+
};
|
|
78
|
+
connectTimeout?: number;
|
|
79
|
+
onAuth?: (options: AuthOptions) => AuthOptions;
|
|
80
|
+
onPuback?: (options: Message) => PuplishResponse;
|
|
81
|
+
onPubrel?: (options: PuplishResponse) => PuplishResponse;
|
|
82
|
+
onPubrec?: (options: Message) => PuplishResponse;
|
|
83
|
+
onPubcomp?: (options: PuplishResponse) => PuplishResponse;
|
|
84
|
+
}
|
|
85
|
+
export declare type QOS = 0 | 1 | 2;
|
|
86
|
+
export interface Message {
|
|
87
|
+
id?: number;
|
|
88
|
+
dup?: boolean;
|
|
89
|
+
qos?: QOS;
|
|
90
|
+
topicName: string;
|
|
91
|
+
properties?: {
|
|
92
|
+
payloadFormatIndicator?: boolean;
|
|
93
|
+
messageExpiryInterval?: number;
|
|
94
|
+
topicAlias?: number;
|
|
95
|
+
responseTopic?: string;
|
|
96
|
+
correlationData?: string;
|
|
97
|
+
userProperties?: UserProperties;
|
|
98
|
+
subscriptionIdentifier?: number;
|
|
99
|
+
contentType?: string;
|
|
100
|
+
};
|
|
101
|
+
payload: Uint8Array;
|
|
102
|
+
}
|
|
103
|
+
export interface MessageOption {
|
|
104
|
+
dup?: boolean;
|
|
105
|
+
qos?: QOS;
|
|
106
|
+
properties?: {
|
|
107
|
+
payloadFormatIndicator?: boolean;
|
|
108
|
+
messageExpiryInterval?: number;
|
|
109
|
+
topicAlias?: number;
|
|
110
|
+
responseTopic?: string;
|
|
111
|
+
correlationData?: string;
|
|
112
|
+
userProperties?: UserProperties;
|
|
113
|
+
subscriptionIdentifier?: number;
|
|
114
|
+
contentType?: string;
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
export interface DisconnectOptions {
|
|
118
|
+
reasonCode?: number;
|
|
119
|
+
properties?: {
|
|
120
|
+
sessionExpiryInterval?: number;
|
|
121
|
+
reasonString?: string;
|
|
122
|
+
userProperties?: UserProperties;
|
|
123
|
+
serverReference?: string;
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
export interface AuthOptions {
|
|
127
|
+
reasonCode: number;
|
|
128
|
+
properties?: {
|
|
129
|
+
authenticationMethod: string;
|
|
130
|
+
authenticationData: string;
|
|
131
|
+
reasonString?: string;
|
|
132
|
+
userProperties?: UserProperties;
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
export interface PuplishResponse {
|
|
136
|
+
id: number;
|
|
137
|
+
reasonCode?: number;
|
|
138
|
+
properties?: {
|
|
139
|
+
reasonString?: string;
|
|
140
|
+
userProperties?: UserProperties;
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
export interface Client {
|
|
144
|
+
getStatus(): 0 | 1 | 2;
|
|
145
|
+
onMessage(cb: (data: MQTTMessage) => void): void;
|
|
146
|
+
offMessage(cb: (data: MQTTMessage) => void): void;
|
|
147
|
+
publish(topic: string, message: string | Uint8Array, option?: MessageOption): void;
|
|
148
|
+
reAuth(option: AuthOptions): void;
|
|
149
|
+
disconnect(option?: DisconnectOptions): void;
|
|
150
|
+
onClose(cb: () => void): void;
|
|
151
|
+
onError(cb: (e: any) => void): void;
|
|
152
|
+
subscribe: (topics: Topic[], options?: SubscribeOption) => Promise<{
|
|
153
|
+
err?: Record<string, number>;
|
|
154
|
+
properties?: any;
|
|
155
|
+
}>;
|
|
156
|
+
unsubscribe: (topic: string[], options?: UnsubscribeOption) => Promise<{
|
|
157
|
+
err?: Record<string, number>;
|
|
158
|
+
properties?: any;
|
|
159
|
+
}>;
|
|
160
|
+
}
|
|
161
|
+
export interface Topic {
|
|
162
|
+
topic: string;
|
|
163
|
+
qos?: number;
|
|
164
|
+
nl?: 0 | 1;
|
|
165
|
+
rap?: 0 | 1;
|
|
166
|
+
rh?: number;
|
|
167
|
+
}
|
|
168
|
+
export interface SubscribeOption {
|
|
169
|
+
properties?: {
|
|
170
|
+
subscriptionIdentifier: number;
|
|
171
|
+
userProperties?: UserProperties;
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
export interface UnsubscribeOption {
|
|
175
|
+
properties?: {
|
|
176
|
+
userProperties?: UserProperties;
|
|
177
|
+
};
|
|
178
|
+
}
|
package/lib/packet.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { PropertySign } from "./constant";
|
|
2
|
+
declare type WriteData = (data: string | number | number[] | Uint8Array) => void;
|
|
3
|
+
export declare const createPacket: (cmd: number, fixHeader?: number) => {
|
|
4
|
+
header: (data: number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
5
|
+
payload: (data: string | number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
6
|
+
cleanCache(): void;
|
|
7
|
+
cache: (data: string | number | number[] | Uint8Array, needLen?: boolean, isVariable?: boolean) => void;
|
|
8
|
+
putHeader(): void;
|
|
9
|
+
putPayload(): void;
|
|
10
|
+
getCache(): Uint8Array;
|
|
11
|
+
getPacket: () => Uint8Array;
|
|
12
|
+
};
|
|
13
|
+
export declare const writeString: (sign: PropertySign) => (v: string, write: WriteData) => void;
|
|
14
|
+
export declare const writePair: (sign: PropertySign) => (properies: Record<string, string | string[]>, write: WriteData) => void;
|
|
15
|
+
export declare const writeProperty: {
|
|
16
|
+
sessionExpiryInterval: (value: number, write: WriteData) => void;
|
|
17
|
+
receiveMaximum: (value: number, write: WriteData) => void;
|
|
18
|
+
maximumPacketSize: (value: number, write: WriteData) => void;
|
|
19
|
+
topicAliasMaximum: (value: number, write: WriteData) => void;
|
|
20
|
+
topicAlias: (value: number, write: WriteData) => void;
|
|
21
|
+
requestResponseInformation: (value: boolean, write: WriteData) => void;
|
|
22
|
+
requestProblemInformation: (value: boolean, write: WriteData) => void;
|
|
23
|
+
userProperties: (properies: Record<string, string | string[]>, write: WriteData) => void;
|
|
24
|
+
authenticationMethod: (v: string, write: WriteData) => void;
|
|
25
|
+
authenticationData: (value: Uint8Array, write: WriteData) => void;
|
|
26
|
+
willDelayInterval: (value: number, write: WriteData) => void;
|
|
27
|
+
payloadFormatIndicator: (value: boolean, write: WriteData) => void;
|
|
28
|
+
messageExpiryInterval: (value: number, write: WriteData) => void;
|
|
29
|
+
contentType: (v: string, write: WriteData) => void;
|
|
30
|
+
responseTopic: (v: string, write: WriteData) => void;
|
|
31
|
+
correlationData: (value: Uint8Array, write: WriteData) => void;
|
|
32
|
+
subscriptionIdentifier: (value: number, write: WriteData) => void;
|
|
33
|
+
};
|
|
34
|
+
export declare const packetProperties: (properies: any, write: WriteData) => void;
|
|
35
|
+
export {};
|
package/lib/parse.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AuthOptions, ClientConntroller, Message, PuplishResponse } from "./interface";
|
|
2
|
+
export declare const parseProperty: {
|
|
3
|
+
sessionExpiryInterval: (data: Uint8Array, offset: number) => number[];
|
|
4
|
+
receiveMaximum: (data: Uint8Array, offset: number) => number[];
|
|
5
|
+
maximumPacketSize: (data: Uint8Array, offset: number) => number[];
|
|
6
|
+
topicAliasMaximum: (data: Uint8Array, offset: number) => number[];
|
|
7
|
+
topicAlias: (data: Uint8Array, offset: number) => number[];
|
|
8
|
+
requestResponseInformation: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
9
|
+
requestProblemInformation: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
10
|
+
userProperties: (data: Uint8Array, offset: number) => [Array<string>, number];
|
|
11
|
+
authenticationMethod: (data: Uint8Array, offset: number) => [string, number];
|
|
12
|
+
authenticationData: (data: Uint8Array, offset: number) => [Uint8Array, number];
|
|
13
|
+
willDelayInterval: (data: Uint8Array, offset: number) => number[];
|
|
14
|
+
payloadFormatIndicator: (data: Uint8Array, offset: number) => (number | boolean)[];
|
|
15
|
+
messageExpiryInterval: (data: Uint8Array, offset: number) => number[];
|
|
16
|
+
contentType: (data: Uint8Array, offset: number) => [string, number];
|
|
17
|
+
responseTopic: (data: Uint8Array, offset: number) => [string, number];
|
|
18
|
+
correlationData: (data: Uint8Array, offset: number) => [Uint8Array, number];
|
|
19
|
+
subscriptionIdentifier: (data: Uint8Array, offset: number) => number[];
|
|
20
|
+
};
|
|
21
|
+
export declare const parseProperties: (data: Uint8Array) => Record<string, any>;
|
|
22
|
+
export declare const parseAuth: (data: Uint8Array) => AuthOptions;
|
|
23
|
+
export declare const parsePublish: (data: Uint8Array, client: ClientConntroller) => Message;
|
|
24
|
+
export declare const parsePublishResponse: (data: Uint8Array, client: ClientConntroller) => PuplishResponse;
|
package/lib/ping.d.ts
ADDED
package/lib/publish.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { ClientConntroller, Message, PuplishResponse } from "./interface";
|
|
2
|
+
export declare const publish: (client: ClientConntroller, message: Message) => Promise<void>;
|
|
3
|
+
export declare const puback: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
4
|
+
export declare const pubrel: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
5
|
+
export declare const pubrec: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
6
|
+
export declare const pubcomp: (client: ClientConntroller, message: PuplishResponse) => Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ClientConntroller, UserProperties } from "./interface";
|
|
2
|
+
interface SubscribeOptions {
|
|
3
|
+
id: number;
|
|
4
|
+
properties?: {
|
|
5
|
+
subscriptionIdentifier: number;
|
|
6
|
+
userProperties?: UserProperties;
|
|
7
|
+
};
|
|
8
|
+
payload: {
|
|
9
|
+
topic: string;
|
|
10
|
+
qos?: number;
|
|
11
|
+
nl?: 0 | 1;
|
|
12
|
+
rap?: 0 | 1;
|
|
13
|
+
rh?: number;
|
|
14
|
+
}[];
|
|
15
|
+
}
|
|
16
|
+
interface UnSubscribeOptions {
|
|
17
|
+
id: number;
|
|
18
|
+
properties?: {
|
|
19
|
+
userProperties?: UserProperties;
|
|
20
|
+
};
|
|
21
|
+
topics: string[];
|
|
22
|
+
}
|
|
23
|
+
export declare const subscribe: (client: ClientConntroller, options: SubscribeOptions) => Promise<{
|
|
24
|
+
reasonCode: Uint8Array;
|
|
25
|
+
properties?: any;
|
|
26
|
+
}>;
|
|
27
|
+
export declare const unsubscribe: (client: ClientConntroller, subscribe: UnSubscribeOptions) => Promise<{
|
|
28
|
+
reasonCode: Uint8Array;
|
|
29
|
+
properties?: any;
|
|
30
|
+
}>;
|
|
31
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ray-js/wechat-mqtt-core",
|
|
3
|
+
"version": "0.3.6-beta-1",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public",
|
|
6
|
+
"registry": "https://registry.npmjs.org"
|
|
7
|
+
},
|
|
8
|
+
"maintainers": [
|
|
9
|
+
"tuya_npm",
|
|
10
|
+
{
|
|
11
|
+
"name": "tuyafe",
|
|
12
|
+
"email": "tuyafe@tuya.com"
|
|
13
|
+
}
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"module": "./index.esm.js",
|
|
17
|
+
"main": "./index.js",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"types": "./index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./index.d.ts",
|
|
23
|
+
"import": "./index.esm.js",
|
|
24
|
+
"require": "./index.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@ray-js/wechat-helper": "^0.3.6-beta-1",
|
|
29
|
+
"@ray-js/wechat-event": "^0.3.6-beta-1"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {}
|
|
32
|
+
}
|