@ray-js/wechat-mqtt 0.0.15-beta-1 → 0.0.15-beta-2
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/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 s,bytesToString as i}from"@ray-js/wechat-helper";import{createEmitter as n}from"@ray-js/wechat-event";function c(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())}))}var a,l;!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"}(a||(a={})),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"}(l||(l={}));const d=(r,s=0)=>{const i=r<<4|s;let n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0,d=new Uint8Array(100),u=0;const p=(r,s,i,n=!1,c=!1)=>{let a;a="string"==typeof i?e(i):"number"==typeof i?[i]:i;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,s+(a.length+l.length)),n&&r.set(l,s),s+=l.length,r.set(a,s),[r,s+=a.length]};function f(e,o=!1,t=!1){const[r,s]=p(n,c,e,o,t);n=r,c=s}function m(e,o=!0,t=!1){const[r,s]=p(a,l,e,o,t);a=r,l=s}return{header:f,payload:m,cleanCache(){d=new Uint8Array(100),u=0},cache:(e,o=!1,t=!1)=>{const[r,s]=p(d,u,e,o,t);d=r,u=s},putHeader(){f(d.slice(0,u),!0,!0)},putPayload(){m(d.slice(0,u),!0,!0)},getCache:()=>d.slice(0,u),getPacket:()=>{const e=c,o=l,r=e+o,s=t(r),d=new Uint8Array(r+s.length+1);d[0]=i;let u=1;return d.set(s,u),u+=s.length,d.set(n.slice(0,e),u),u+=e,console.log("===",e,o,r,u),d.set(a.slice(0,o),u),d}}},u=t=>(r,s)=>{const i=e(r),n=o(i.length,2);s(t),s(n),s(i)},p=e=>(o,t)=>{t(e),t(o?1:0)},f=e=>(t,r)=>{r(e),r(o(t))},m=e=>(t,r)=>{r(e),r(o(t,2))},v=e=>(t,r)=>{const s=o(t.length,2);r(e),r(s),r(t)},g={sessionExpiryInterval:f(l.sessionExpiryInterval),receiveMaximum:m(l.receiveMaximum),maximumPacketSize:f(l.maximumPacketSize),topicAliasMaximum:m(l.topicAliasMaximum),topicAlias:m(l.topicAlias),requestResponseInformation:p(l.requestProblemInformation),requestProblemInformation:p(l.requestProblemInformation),userProperties:(h=l.userProperties,(o,t)=>{Object.keys(o).forEach((r=>{const s=o[r],i=e(r);Array.isArray(s)?s.forEach((o=>{t(h),t(i),t(e(o))})):(t(h),t(i),t(e(s)))}))}),authenticationMethod:u(l.authenticationMethod),authenticationData:v(l.authenticationData),willDelayInterval:f(l.willDelayInterval),payloadFormatIndicator:p(l.payloadFormatIndicator),messageExpiryInterval:f(l.messageExpiryInterval),contentType:u(l.contentType),responseTopic:u(l.responseTopic),correlationData:v(l.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t(o))})(l.subscriptionIdentifier)};var h;const C=(e,o)=>{Object.keys(e||{}).map((t=>{g[t]&&g[t](e[t],o)}))},M=(e,o)=>{const{properties:t,reasonCode:r}=o,s=d(a.AUTH);if(s.header(r),!t)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return C(t,s.cache),s.putHeader(),e.send(s.getPacket())},y=[],P=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};function b(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}const w=(e,o)=>[s(e.slice(o,o+=2)),o],I=(e,o)=>[s(e.slice(o,o+=4)),o],T=(e,o)=>[1===e[o++],o],E=(e,o)=>{const t=s(e.slice(o,o+=2));return[i(e.slice(o,o+=t)),o]},A=(e,o)=>{const t=s(e.slice(o,o+=2));return[e.slice(o,o+=t),o]},U={sessionExpiryInterval:I,receiveMaximum:w,maximumPacketSize:I,topicAliasMaximum:w,topicAlias:w,requestResponseInformation:T,requestProblemInformation:T,userProperties:(e,o)=>{const[t,r]=E(e,o),[s,i]=E(e,r);return[[t,s],i]},authenticationMethod:E,authenticationData:A,willDelayInterval:I,payloadFormatIndicator:T,messageExpiryInterval:I,contentType:E,responseTopic:E,correlationData:A,subscriptionIdentifier:(e,o)=>{const{num:t,end:s}=r(e,o);return[t,s]}},S=e=>{let o=e.length>0,t=0;const r={};for(;o;){const s=e[t++],i=Object.keys(l).find((e=>l[e]===s));if(!i)throw{errCode:63013,errMsg:`Unrecognized property: ${s}`};{const n=U[i](e,t);if(s===l.userProperties){const e=r[i],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[i]=n[0];t=n[1],o=t<e.length}}return r},q=(e,o)=>{const{end:t}=r(e,1),i=e.slice(t),n=s(i.slice(0,2));let c,a=0;if(5===o.protocolVersion){a=i[2];const{num:o,end:t}=r(i,3);c=S(e.slice(t,o))}return{id:n,reasonCode:a,properties:c}},x=(t,r)=>c(void 0,void 0,void 0,(function*(){console.log("=======publish",r);const{dup:s,qos:i=0,topicName:n,id:c,properties:l,payload:u}=r;let p=0|(s?0===i?0:8:0);p|=i<<1;const f=d(a.PUBLISH,p);f.header(e(n),!0),i>0&&f.header(o(c,2)),5===t.protocolVersion&&(C(l,f.cache),f.putHeader()),f.payload(u);try{yield t.send(f.getPacket())}catch(e){return void t.emitError(e)}if(0!==i)if(1===i)try{yield D(t,r)}catch(e){x(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){x(t,r)}})),B=(e,t,r,s=0)=>c(void 0,void 0,void 0,(function*(){const{id:i,properties:n,reasonCode:c}=t,a=d(r,s);a.header(o(i,2)),5===e.protocolVersion&&(a.header(c||0),C(n,a.cache),a.putHeader()),e.send(a.getPacket())})),N=(e,o)=>c(void 0,void 0,void 0,(function*(){B(e,o,a.PUBACK)})),k=(e,o)=>c(void 0,void 0,void 0,(function*(){B(e,o,a.PUBREL,2)})),R=(e,o)=>c(void 0,void 0,void 0,(function*(){B(e,o,a.PUBREC,0)})),O=(e,o)=>c(void 0,void 0,void 0,(function*(){B(e,o,a.PUBCOMP,0)})),D=(e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const s=n=>{if(n[0]>>4===a.PUBACK){const c=q(n,e);if(c.id===o.id)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),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 s=n=>{if(n[0]>>4===a.PUBREC){const c=q(n,e);if(c.id===o)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),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 s=n=>{if(n[0]>>4===a.PUBCOMP){const c=q(n,e);if(c.id===o.id)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))}));P((()=>!(!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 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)}}}))));P((()=>(console.log("-====wx",wx),!(!wx||!wx.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 s=wx.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:r});s&&t(s)}))})))(e,o);return console.log("=====socketTask",t),{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,r)=>{t.send({data:e,fail:r,success:o})})),close:()=>{console.log("--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:s,end:i}=r(e,1);return{reasonCode:t,properties:S(e.slice(i,i+s))}})(e);if(24===t.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};M(o,o.options.onAuth(t))}},L=(e,o)=>{const t=((e,o)=>{const t=e[0],i=(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 u=E(e,c),[p]=u;let f,m;if(c=u[1],i>0&&(f=s(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:i,dup:n,topicName:p,id:f,payload:e.slice(c,d),properties:m}})(e,o);let{topicName:i}=t;if(o.protocolVersion>=5&&t.properties){const{topicAlias:e}=t.properties;if(e)if(i)o.applyTopic(e,i);else if(i=o.getTopic(e),!i)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(i))switch(t.qos){case 0:o.emitMqttMessage({topic:i,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?R(o,o.options.onPubrec(t)):R(o,{id:t.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},Q=(e,o)=>{const t=q(e,o);o.options.onPubcomp?O(o,o.options.onPubcomp(t)):O(o,{id:t.id,reasonCode:0})},j=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([a.PINGREQ<<4,0])),new Promise(((o,t)=>{const r=t=>{t[0]>>4===a.PINGRESP&&(e.offMessage(r),clearTimeout(s),o(!0))};e.onMessage(r);const s=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.close()}}));setTimeout(t,o)},z=t=>c(void 0,void 0,void 0,(function*(){const i=yield(e=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let r=0;const s=n();let i=null,a=0;const l={};return{options:e,protocolVersion:o,sessionPresent:0,connect:(n=!1)=>c(void 0,void 0,void 0,(function*(){if(n&&i)try{i.close()}catch(e){}const c=++a;return r=0,i=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{console.log("========ws connect time out"),r=2,o(new Error("ws connect time out"))}),1e4);i&&i.onError((e=>{0===r?(clearTimeout(t),o(e)):c===a&&(r=2,s.emit("error",e),s.emit("close",e))})),i&&i.onOpen((()=>{clearTimeout(t),r=1,i&&i.onClose((e=>{c===a&&(r=2,s.emit("close",e))})),i&&i.onMessage((e=>{c===a&&s.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===r,isOnline:()=>1===r,getStatus:()=>r,send:e=>{if(i&&1===r)return i.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{s.on("close",e)},offClose:e=>{s.off("close",e)},onError:e=>{s.on("error",e)},offError:e=>{s.off("error",e)},onMessage:e=>{s.on("message",e)},offMessage:e=>{s.off("message",e)},close:()=>{r=2,i&&i.close()},emitError:e=>{console.log("has error",e),s.emit("error",e)},emitMqttMessage:e=>{s.emit("mqttMessage",e)},onMqttMessage:e=>{s.on("mqttMessage",e)},offMqttMessage:e=>{s.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],checkTopic:o=>"string"==typeof e.subscribeTopics?b(e.subscribeTopics,o):e.subscribeTopics.some((e=>b(e,o)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(t);yield i.connect(),i.onMessage((e=>{((e,o)=>{const t=e[0]>>4;console.log("============cmd",t);const{end:s,num:i}=r(e,1);switch(t){case a.AUTH:return V(e.slice(s,s+i),o);case a.PUBLISH:return L(e,o);case a.PUBCOMP:return Q(e,o);case a.DISCONNECT:o.close()}})(e,i)})),yield((e,t)=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:s=4,connectTimeout:i=10,username:n,password:c,will:l,keepalive:u=60,clean:p,clientId:f}=t,m=d(a.CONNECT);m.header([0,4,77,81,84,84]),m.header(s);let v=0;if(v|=n?128:0,v|=c?64:0,v|=l&&l.retain?32:0,v|=l&&l.qos?l.qos<<3:0,v|=l?4:0,v|=p?2:0,m.header(v),m.header(o(u,2)),5===s&&(C(t.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(f),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(),C(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 n&&m.payload(n),c&&m.payload(c),e.send(m.getPacket()),new Promise(((o,t)=>{const s=i=>{if(i[0]>>4===a.CONNACK){e.offMessage(s),clearTimeout(n);const{end:c}=r(i,1),a=i.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(s);const n=setTimeout((()=>{e.offMessage(s),e.close(),t({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*i)}))})))(i,t),j(i);let l=0;const u=()=>(++l,16777215===l&&(l=1),l);return{getStatus:i.getStatus,onMessage:i.onMqttMessage,offMessage:i.offMqttMessage,subscribe:(e,t)=>((e,t)=>c(void 0,void 0,void 0,(function*(){console.log("=======subscribe",t);const{id:i,properties:n,payload:c}=t,l=d(a.SUBSCRIBE,2);if(l.header(o(i,2)),5===e.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};C(n,l.cache),l.putHeader()}return c.forEach((o=>{l.payload(o.topic);let t=o.qos||0;if(5===e.protocolVersion){const{nl:e=0,rap:r=0,rh:s=0}=o;t|=e<<2,t|=r<<3,t|=s<<4}l.payload(t,!1)})),console.log("=======subscribe packet",l.getPacket()),e.send(l.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===a.SUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(s(d.slice(0,2))===i){let t,s=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,s);s=e+o,t=S(d.slice(e,s))}const i=d.slice(s);e.offMessage(n),clearTimeout(c),o({reasonCode:i,properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(i,{id:u(),properties:null==t?void 0:t.properties,payload:[{topic:e,qos:null==t?void 0:t.qos,nl:null==t?void 0:t.nl,rap:null==t?void 0:t.rap,rh:null==t?void 0:t.rh}]}),unsubscribe:(e,t)=>((e,t)=>{const{id:i,properties:n,topics:c}=t,l=d(a.UNSUBSCRIBE,2);return l.header(o(i,2)),5===e.protocolVersion&&(C(n,l.cache),l.putHeader()),c.forEach((e=>{l.payload(e)})),e.send(l.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===a.UNSUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(s(d.slice(0,2))===i){let t,s=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,s);s=e+o,t=S(d.slice(e,s))}const i=d.slice(s);e.offMessage(n),clearTimeout(c),o({reasonCode:i,properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(i,{id:u(),properties:null==t?void 0:t.properties,topics:[e]}),publish:(o,t,r)=>{const s=u();return x(i,Object.assign({id:s,topicName:o,payload:"string"==typeof t?e(t):t},r))},reAuth:e=>{M(i,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,s=d(a.DISCONNECT);5===e.protocolVersion&&(s.header(t),C(r,s.cache),s.putHeader()),yield e.send(s.getPacket()),e.close()}))})(i,e||{reasonCode:0})},onClose:i.onClose,onError:i.onError}}));export{z as createMQTT};
|
|
1
|
+
import{stringToBytes as e,uintToBytes as o,uintToBytesBy128 as t,bytesToIntBy128 as r,bytesToUint as s,bytesToString as i}from"@ray-js/wechat-helper";import{createEmitter as n}from"@ray-js/wechat-event";function c(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())}))}var a,l;!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"}(a||(a={})),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"}(l||(l={}));const d=(r,s=0)=>{const i=r<<4|s;let n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0,d=new Uint8Array(100),p=0;const u=(r,s,i,n=!1,c=!1)=>{let a;a="string"==typeof i?e(i):"number"==typeof i?[i]:i;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,s+(a.length+l.length)),n&&r.set(l,s),s+=l.length,r.set(a,s),[r,s+=a.length]};function f(e,o=!1,t=!1){const[r,s]=u(n,c,e,o,t);n=r,c=s}function m(e,o=!0,t=!1){const[r,s]=u(a,l,e,o,t);a=r,l=s}return{header:f,payload:m,cleanCache(){d=new Uint8Array(100),p=0},cache:(e,o=!1,t=!1)=>{const[r,s]=u(d,p,e,o,t);d=r,p=s},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,s=t(r),d=new Uint8Array(r+s.length+1);d[0]=i;let p=1;return d.set(s,p),p+=s.length,d.set(n.slice(0,e),p),p+=e,d.set(a.slice(0,o),p),d}}},p=t=>(r,s)=>{const i=e(r),n=o(i.length,2);s(t),s(n),s(i)},u=e=>(o,t)=>{t(e),t(o?1:0)},f=e=>(t,r)=>{r(e),r(o(t))},m=e=>(t,r)=>{r(e),r(o(t,2))},v=e=>(t,r)=>{const s=o(t.length,2);r(e),r(s),r(t)},g={sessionExpiryInterval:f(l.sessionExpiryInterval),receiveMaximum:m(l.receiveMaximum),maximumPacketSize:f(l.maximumPacketSize),topicAliasMaximum:m(l.topicAliasMaximum),topicAlias:m(l.topicAlias),requestResponseInformation:u(l.requestProblemInformation),requestProblemInformation:u(l.requestProblemInformation),userProperties:(h=l.userProperties,(o,t)=>{Object.keys(o).forEach((r=>{const s=o[r],i=e(r);Array.isArray(s)?s.forEach((o=>{t(h),t(i),t(e(o))})):(t(h),t(i),t(e(s)))}))}),authenticationMethod:p(l.authenticationMethod),authenticationData:v(l.authenticationData),willDelayInterval:f(l.willDelayInterval),payloadFormatIndicator:u(l.payloadFormatIndicator),messageExpiryInterval:f(l.messageExpiryInterval),contentType:p(l.contentType),responseTopic:p(l.responseTopic),correlationData:v(l.correlationData),subscriptionIdentifier:(e=>(o,r)=>{r(e),r(t(o))})(l.subscriptionIdentifier)};var h;const C=(e,o)=>{Object.keys(e||{}).map((t=>{g[t]&&g[t](e[t],o)}))},M=(e,o)=>{const{properties:t,reasonCode:r}=o,s=d(a.AUTH);if(s.header(r),!t)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return C(t,s.cache),s.putHeader(),e.send(s.getPacket())},y=[],P=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};function b(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}const I=(e,o)=>[s(e.slice(o,o+=2)),o],w=(e,o)=>[s(e.slice(o,o+=4)),o],T=(e,o)=>[1===e[o++],o],E=(e,o)=>{const t=s(e.slice(o,o+=2));return[i(e.slice(o,o+=t)),o]},A=(e,o)=>{const t=s(e.slice(o,o+=2));return[e.slice(o,o+=t),o]},U={sessionExpiryInterval:w,receiveMaximum:I,maximumPacketSize:w,topicAliasMaximum:I,topicAlias:I,requestResponseInformation:T,requestProblemInformation:T,userProperties:(e,o)=>{const[t,r]=E(e,o),[s,i]=E(e,r);return[[t,s],i]},authenticationMethod:E,authenticationData:A,willDelayInterval:w,payloadFormatIndicator:T,messageExpiryInterval:w,contentType:E,responseTopic:E,correlationData:A,subscriptionIdentifier:(e,o)=>{const{num:t,end:s}=r(e,o);return[t,s]}},S=e=>{let o=e.length>0,t=0;const r={};for(;o;){const s=e[t++],i=Object.keys(l).find((e=>l[e]===s));if(!i)throw{errCode:63013,errMsg:`Unrecognized property: ${s}`};{const n=U[i](e,t);if(s===l.userProperties){const e=r[i],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[i]=n[0];t=n[1],o=t<e.length}}return r},q=(e,o)=>{const{end:t}=r(e,1),i=e.slice(t),n=s(i.slice(0,2));let c,a=0;if(5===o.protocolVersion){a=i[2];const{num:o,end:t}=r(i,3);c=S(e.slice(t,o))}return{id:n,reasonCode:a,properties:c}},B=(t,r)=>c(void 0,void 0,void 0,(function*(){const{dup:s,qos:i=0,topicName:n,id:c,properties:l,payload:p}=r;let u=0|(s?0===i?0:8:0);u|=i<<1;const f=d(a.PUBLISH,u);f.header(e(n),!0),i>0&&f.header(o(c,2)),5===t.protocolVersion&&(C(l,f.cache),f.putHeader()),f.payload(p);try{yield t.send(f.getPacket())}catch(e){return void t.emitError(e)}if(0!==i)if(1===i)try{yield D(t,r)}catch(e){B(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){B(t,r)}})),x=(e,t,r,s=0)=>c(void 0,void 0,void 0,(function*(){const{id:i,properties:n,reasonCode:c}=t,a=d(r,s);a.header(o(i,2)),5===e.protocolVersion&&(a.header(c||0),C(n,a.cache),a.putHeader()),e.send(a.getPacket())})),N=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,a.PUBACK)})),k=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,a.PUBREL,2)})),R=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,a.PUBREC,0)})),O=(e,o)=>c(void 0,void 0,void 0,(function*(){x(e,o,a.PUBCOMP,0)})),D=(e,o)=>c(void 0,void 0,void 0,(function*(){return new Promise(((t,r)=>{const s=n=>{if(n[0]>>4===a.PUBACK){const c=q(n,e);if(c.id===o.id)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),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 s=n=>{if(n[0]>>4===a.PUBREC){const c=q(n,e);if(c.id===o)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),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 s=n=>{if(n[0]>>4===a.PUBCOMP){const c=q(n,e);if(c.id===o.id)if(e.offMessage(s),clearTimeout(i),0===c.reasonCode)t(c);else{const o={errCode:63010,errMsg:`MQTT publish failure, code: ${c.reasonCode}`};r(o),e.emitError(o)}}};e.onMessage(s);const i=setTimeout((()=>{e.offMessage(s),e.close();const o={errCode:63009,errMsg:"Mqtt publish timeout"};r(o),e.emitError(o)}),1e4)}))}));P((()=>!(!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 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)}}}))));P((()=>!(!wx||!wx.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 s=wx.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:r});s&&t(s)}))})))(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:s,end:i}=r(e,1);return{reasonCode:t,properties:S(e.slice(i,i+s))}})(e);if(24===t.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};M(o,o.options.onAuth(t))}},L=(e,o)=>{const t=((e,o)=>{const t=e[0],i=(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],i>0&&(f=s(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:i,dup:n,topicName:u,id:f,payload:e.slice(c,d),properties:m}})(e,o);let{topicName:i}=t;if(o.protocolVersion>=5&&t.properties){const{topicAlias:e}=t.properties;if(e)if(i)o.applyTopic(e,i);else if(i=o.getTopic(e),!i)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(i))switch(t.qos){case 0:o.emitMqttMessage({topic:i,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?R(o,o.options.onPubrec(t)):R(o,{id:t.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},Q=(e,o)=>{const t=q(e,o);o.options.onPubcomp?O(o,o.options.onPubcomp(t)):O(o,{id:t.id,reasonCode:0})},j=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([a.PINGREQ<<4,0])),new Promise(((o,t)=>{const r=t=>{t[0]>>4===a.PINGRESP&&(e.offMessage(r),clearTimeout(s),o(!0))};e.onMessage(r);const s=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.close()}}));setTimeout(t,o)},z=t=>c(void 0,void 0,void 0,(function*(){const i=yield(e=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let r=0;const s=n();let i=null,a=0;const l={};return{options:e,protocolVersion:o,sessionPresent:0,connect:(n=!1)=>c(void 0,void 0,void 0,(function*(){if(n&&i)try{i.close()}catch(e){}const c=++a;return r=0,i=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{r=2,o(new Error("ws connect time out"))}),1e4);i&&i.onError((e=>{0===r?(clearTimeout(t),o(e)):c===a&&(r=2,s.emit("error",e),s.emit("close",e))})),i&&i.onOpen((()=>{clearTimeout(t),r=1,i&&i.onClose((e=>{c===a&&(r=2,s.emit("close",e))})),i&&i.onMessage((e=>{c===a&&s.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===r,isOnline:()=>1===r,getStatus:()=>r,send:e=>{if(i&&1===r)return i.send(e.buffer);throw{errCode:63017,errMsg:"Websocket is closed"}},onClose:e=>{s.on("close",e)},offClose:e=>{s.off("close",e)},onError:e=>{s.on("error",e)},offError:e=>{s.off("error",e)},onMessage:e=>{s.on("message",e)},offMessage:e=>{s.off("message",e)},close:()=>{r=2,i&&i.close()},emitError:e=>{s.emit("error",e)},emitMqttMessage:e=>{s.emit("mqttMessage",e)},onMqttMessage:e=>{s.on("mqttMessage",e)},offMqttMessage:e=>{s.off("mqttMessage",e)},applyTopic:(e,o)=>{l[e]=o},getTopic:e=>l[e],checkTopic:o=>"string"==typeof e.subscribeTopics?b(e.subscribeTopics,o):e.subscribeTopics.some((e=>b(e,o)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(t);yield i.connect(),i.onMessage((e=>{((e,o)=>{const t=e[0]>>4,{end:s,num:i}=r(e,1);switch(t){case a.AUTH:return V(e.slice(s,s+i),o);case a.PUBLISH:return L(e,o);case a.PUBCOMP:return Q(e,o);case a.DISCONNECT:o.close()}})(e,i)})),yield((e,t)=>c(void 0,void 0,void 0,(function*(){const{protocolVersion:s=4,connectTimeout:i=10,username:n,password:c,will:l,keepalive:p=60,clean:u,clientId:f}=t,m=d(a.CONNECT);m.header([0,4,77,81,84,84]),m.header(s);let v=0;if(v|=n?128:0,v|=c?64:0,v|=l&&l.retain?32:0,v|=l&&l.qos?l.qos<<3:0,v|=l?4:0,v|=u?2:0,m.header(v),m.header(o(p,2)),5===s&&(C(t.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(f),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(),C(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 n&&m.payload(n),c&&m.payload(c),e.send(m.getPacket()),new Promise(((o,t)=>{const s=i=>{if(i[0]>>4===a.CONNACK){e.offMessage(s),clearTimeout(n);const{end:c}=r(i,1),a=i.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(s);const n=setTimeout((()=>{e.offMessage(s),e.close(),t({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*i)}))})))(i,t),j(i);let l=0;const p=()=>(++l,16777215===l&&(l=1),l);return{getStatus:i.getStatus,onMessage:i.onMqttMessage,offMessage:i.offMqttMessage,subscribe:(e,t)=>((e,t)=>c(void 0,void 0,void 0,(function*(){const{id:i,properties:n,payload:c}=t,l=d(a.SUBSCRIBE,2);if(l.header(o(i,2)),5===e.protocolVersion){if(!n)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};C(n,l.cache),l.putHeader()}return c.forEach((o=>{l.payload(o.topic);let t=o.qos||0;if(5===e.protocolVersion){const{nl:e=0,rap:r=0,rh:s=0}=o;t|=e<<2,t|=r<<3,t|=s<<4}l.payload(t,!1)})),e.send(l.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===a.SUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(s(d.slice(0,2))===i){let t,s=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,s);s=e+o,t=S(d.slice(e,s))}const i=d.slice(s);e.offMessage(n),clearTimeout(c),o({reasonCode:i,properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(i,{id:p(),properties:null==t?void 0:t.properties,payload:[{topic:e,qos:null==t?void 0:t.qos,nl:null==t?void 0:t.nl,rap:null==t?void 0:t.rap,rh:null==t?void 0:t.rh}]}),unsubscribe:(e,t)=>((e,t)=>{const{id:i,properties:n,topics:c}=t,l=d(a.UNSUBSCRIBE,2);return l.header(o(i,2)),5===e.protocolVersion&&(C(n,l.cache),l.putHeader()),c.forEach((e=>{l.payload(e)})),e.send(l.getPacket()),new Promise(((o,t)=>{const n=t=>{if(t[0]>>4===a.UNSUBACK){const a=r(t,1),l=a.end+a.num,d=t.slice(a.end,l);if(s(d.slice(0,2))===i){let t,s=2;if(5===e.protocolVersion){const{end:e,num:o}=r(d,s);s=e+o,t=S(d.slice(e,s))}const i=d.slice(s);e.offMessage(n),clearTimeout(c),o({reasonCode:i,properties:t})}}};e.onMessage(n);const c=setTimeout((()=>{e.offMessage(n),e.close(),t({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(i,{id:p(),properties:null==t?void 0:t.properties,topics:[e]}),publish:(o,t,r)=>{const s=p();return B(i,Object.assign({id:s,topicName:o,payload:"string"==typeof t?e(t):t},r))},reAuth:e=>{M(i,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,s=d(a.DISCONNECT);5===e.protocolVersion&&(s.header(t),C(r,s.cache),s.putHeader()),yield e.send(s.getPacket()),e.close()}))})(i,e||{reasonCode:0})},onClose:i.onClose,onError:i.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"),s=require("@ray-js/wechat-event");function r(e,o,t,s){return new(t||(t=Promise))((function(r,n){function i(e){try{a(s.next(e))}catch(e){n(e)}}function c(e){try{a(s.throw(e))}catch(e){n(e)}}function a(e){var o;e.done?r(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(i,c)}a((s=s.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 n=(e,o=0)=>{const s=e<<4|o;let r=new Uint8Array(100),n=0,i=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0;const d=(e,o,s,r=!1,n=!1)=>{let i;i="string"==typeof s?t.stringToBytes(s):"number"==typeof s?[s]:s;let c=new Uint8Array;r&&(c=n?t.uintToBytesBy128(i.length):t.uintToBytes(i.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+(i.length+c.length)),r&&e.set(c,o),o+=c.length,e.set(i,o),[e,o+=i.length]};function u(e,o=!1,t=!1){const[s,i]=d(r,n,e,o,t);r=s,n=i}function p(e,o=!0,t=!1){const[s,r]=d(i,c,e,o,t);i=s,c=r}return{header:u,payload:p,cleanCache(){a=new Uint8Array(100),l=0},cache:(e,o=!1,t=!1)=>{const[s,r]=d(a,l,e,o,t);a=s,l=r},putHeader(){u(a.slice(0,l),!0,!0)},putPayload(){p(a.slice(0,l),!0,!0)},getCache:()=>a.slice(0,l),getPacket:()=>{const e=n,o=c,a=e+o,l=t.uintToBytesBy128(a),d=new Uint8Array(a+l.length+1);d[0]=s;let u=1;return d.set(l,u),u+=l.length,d.set(r.slice(0,e),u),u+=e,console.log("===",e,o,a,u),d.set(i.slice(0,o),u),d}}},i=e=>(o,s)=>{const r=t.stringToBytes(o),n=t.uintToBytes(r.length,2);s(e),s(n),s(r)},c=e=>(o,t)=>{t(e),t(o?1:0)},a=e=>(o,s)=>{s(e),s(t.uintToBytes(o))},l=e=>(o,s)=>{s(e),s(t.uintToBytes(o,2))},d=e=>(o,s)=>{const r=t.uintToBytes(o.length,2);s(e),s(r),s(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((s=>{const r=e[s],n=t.stringToBytes(s);Array.isArray(r)?r.forEach((e=>{o(p),o(n),o(t.stringToBytes(e))})):(o(p),o(n),o(t.stringToBytes(r)))}))}),authenticationMethod:i(o.authenticationMethod),authenticationData:d(o.authenticationData),willDelayInterval:a(o.willDelayInterval),payloadFormatIndicator:c(o.payloadFormatIndicator),messageExpiryInterval:a(o.messageExpiryInterval),contentType:i(o.contentType),responseTopic:i(o.responseTopic),correlationData:d(o.correlationData),subscriptionIdentifier:(e=>(o,s)=>{s(e),s(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:s,reasonCode:r}=t,i=n(e.AUTH);if(i.header(r),!s)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return f(s,i.cache),i.putHeader(),o.send(i.getPacket())},y=[],g=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};function v(e,o){const t=e.split("/"),s=e.split("/");if(e===o)return!0;for(let e=0;e<s.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==s[e])return!1}}return!1}const h=(e,o)=>[t.bytesToUint(e.slice(o,o+=2)),o],T=(e,o)=>[t.bytesToUint(e.slice(o,o+=4)),o],C=(e,o)=>[1===e[o++],o],b=(e,o)=>{const s=t.bytesToUint(e.slice(o,o+=2));return[t.bytesToString(e.slice(o,o+=s)),o]},M=(e,o)=>{const s=t.bytesToUint(e.slice(o,o+=2));return[e.slice(o,o+=s),o]},P={sessionExpiryInterval:T,receiveMaximum:h,maximumPacketSize:T,topicAliasMaximum:h,topicAlias:h,requestResponseInformation:C,requestProblemInformation:C,userProperties:(e,o)=>{const[t,s]=b(e,o),[r,n]=b(e,s);return[[t,r],n]},authenticationMethod:b,authenticationData:M,willDelayInterval:T,payloadFormatIndicator:C,messageExpiryInterval:T,contentType:b,responseTopic:b,correlationData:M,subscriptionIdentifier:(e,o)=>{const{num:s,end:r}=t.bytesToIntBy128(e,o);return[s,r]}},I=e=>{let t=e.length>0,s=0;const r={};for(;t;){const n=e[s++],i=Object.keys(o).find((e=>o[e]===n));if(!i)throw{errCode:63013,errMsg:`Unrecognized property: ${n}`};{const c=P[i](e,s);if(n===o.userProperties){const e=r[i],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 r[i]=c[0];s=c[1],t=s<e.length}}return r},B=(e,o)=>{const{end:s}=t.bytesToIntBy128(e,1),r=e.slice(s),n=t.bytesToUint(r.slice(0,2));let i,c=0;if(5===o.protocolVersion){c=r[2];const{num:o,end:s}=t.bytesToIntBy128(r,3);i=I(e.slice(s,o))}return{id:n,reasonCode:c,properties:i}},w=(o,s)=>r(void 0,void 0,void 0,(function*(){console.log("=======publish",s);const{dup:r,qos:i=0,topicName:c,id:a,properties:l,payload:d}=s;let u=0|(r?0===i?0:8:0);u|=i<<1;const p=n(e.PUBLISH,u);p.header(t.stringToBytes(c),!0),i>0&&p.header(t.uintToBytes(a,2)),5===o.protocolVersion&&(f(l,p.cache),p.putHeader()),p.payload(d);try{yield o.send(p.getPacket())}catch(e){return void o.emitError(e)}if(0!==i)if(1===i)try{yield x(o,s)}catch(e){w(o,s)}else try{const e=yield N(o,a);o.options.onPubrel?A(o,o.options.onPubrel(e)):A(o,{id:a,reasonCode:0}),yield k(o,s)}catch(e){w(o,s)}})),E=(e,o,s,i=0)=>r(void 0,void 0,void 0,(function*(){const{id:r,properties:c,reasonCode:a}=o,l=n(s,i);l.header(t.uintToBytes(r,2)),5===e.protocolVersion&&(l.header(a||0),f(c,l.cache),l.putHeader()),e.send(l.getPacket())})),U=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBACK)})),A=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),S=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREC,0)})),q=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBCOMP,0)})),x=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{const n=c=>{if(c[0]>>4===e.PUBACK){const e=B(c,o);if(e.id===t.id)if(o.offMessage(n),clearTimeout(i),0===e.reasonCode)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(n);const i=setTimeout((()=>{o.offMessage(n),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))})),N=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{const n=c=>{if(c[0]>>4===e.PUBREC){const e=B(c,o);if(e.id===t)if(o.offMessage(n),clearTimeout(i),0===e.reasonCode)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(n);const i=setTimeout((()=>{o.offMessage(n),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))})),k=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{const n=c=>{if(c[0]>>4===e.PUBCOMP){const e=B(c,o);if(e.id===t.id)if(o.offMessage(n),clearTimeout(i),0===e.reasonCode)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(n);const i=setTimeout((()=>{o.offMessage(n),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))}));g((()=>!(!window||!window.WebSocket)),((e,o)=>r(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 s=0;const r=setInterval((()=>{s++,200===s&&o(),0===t.bufferedAmount&&(clearInterval(r),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",e)},onError:e=>{t.addEventListener("error",e)}}}))));g((()=>(console.log("-====wx",wx),!(!wx||!wx.connectSocket))),((e,o)=>r(void 0,void 0,void 0,(function*(){const t=yield((e,o)=>r(void 0,void 0,void 0,(function*(){return new Promise(((t,s)=>{const r=wx.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:s});r&&t(r)}))})))(e,o);return console.log("=====socketTask",t),{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,s)=>{t.send({data:e,fail:s,success:o})})),close:()=>{console.log("--close--"),t.close()},onClose:e=>{t.onClose(e)},onMessage:e=>{t.onMessage(e)},onError:e=>{t.onError(e)}}}))));const R=(e,o)=>{const s=(e=>{let o=0;const s=e[o++],{num:r,end:n}=t.bytesToIntBy128(e,1);return{reasonCode:s,properties:I(e.slice(n,n+r))}})(e);if(24===s.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};m(o,o.options.onAuth(s))}},O=(e,o)=>{const s=((e,o)=>{const s=e[0],r=(6&s)>>1,n=(8&s)>>3==1;let i=1;const{num:c,end:a}=t.bytesToIntBy128(e,i),l=a+c;i=a;const d=b(e,i),[u]=d;let p,f;if(i=d[1],r>0&&(p=t.bytesToUint(e.slice(i,i+=2))),5===o.protocolVersion){const{num:o,end:s}=t.bytesToIntBy128(e,i);f=I(e.slice(s,o)),i=o+s}return{qos:r,dup:n,topicName:u,id:p,payload:e.slice(i,l),properties:f}})(e,o);let{topicName:r}=s;if(o.protocolVersion>=5&&s.properties){const{topicAlias:e}=s.properties;if(e)if(r)o.applyTopic(e,r);else if(r=o.getTopic(e),!r)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(r))switch(s.qos){case 0:o.emitMqttMessage({topic:r,payload:s.payload});break;case 1:o.options.onPuback?U(o,o.options.onPuback(s)):U(o,{id:s.id,reasonCode:0});break;case 2:o.options.onPubrec?S(o,o.options.onPubrec(s)):S(o,{id:s.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},D=(e,o)=>{const t=B(e,o);o.options.onPubcomp?q(o,o.options.onPubcomp(t)):q(o,{id:t.id,reasonCode:0})},H=o=>{const t=1e3*(o.options.keepalive||60),s=()=>r(void 0,void 0,void 0,(function*(){try{!o.isClose()&&(yield(o=>(o.send(new Uint8Array([e.PINGREQ<<4,0])),new Promise(((t,s)=>{const r=s=>{s[0]>>4===e.PINGRESP&&(o.offMessage(r),clearTimeout(n),t(!0))};o.onMessage(r);const n=setTimeout((()=>{o.offMessage(r),o.close(),s({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(o)),setTimeout(s,t)}catch(e){console.warn("ping error",e),o.close()}}));setTimeout(s,t)};exports.createMQTT=o=>r(void 0,void 0,void 0,(function*(){const i=yield(e=>r(void 0,void 0,void 0,(function*(){const{protocolVersion:o=4}=e,t=y.find((e=>e[0]()));if(t){let n=0;const i=s.createEmitter();let c=null,a=0;const l={};return{options:e,protocolVersion:o,sessionPresent:0,connect:(s=!1)=>r(void 0,void 0,void 0,(function*(){if(s&&c)try{c.close()}catch(e){}const r=++a;return n=0,c=yield t[1](e.url,o),new Promise(((e,o)=>{const t=setTimeout((()=>{console.log("========ws connect time out"),n=2,o(new Error("ws connect time out"))}),1e4);c&&c.onError((e=>{0===n?(clearTimeout(t),o(e)):r===a&&(n=2,i.emit("error",e),i.emit("close",e))})),c&&c.onOpen((()=>{clearTimeout(t),n=1,c&&c.onClose((e=>{r===a&&(n=2,i.emit("close",e))})),c&&c.onMessage((e=>{r===a&&i.emit("message",new Uint8Array(e.data))})),e(!0)}))}))})),isClose:()=>2===n,isOnline:()=>1===n,getStatus:()=>n,send:e=>{if(c&&1===n)return c.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:()=>{n=2,c&&c.close()},emitError:e=>{console.log("has error",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],checkTopic:o=>"string"==typeof e.subscribeTopics?v(e.subscribeTopics,o):e.subscribeTopics.some((e=>v(e,o)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(o);yield i.connect(),i.onMessage((o=>{((o,s)=>{const r=o[0]>>4;console.log("============cmd",r);const{end:n,num:i}=t.bytesToIntBy128(o,1);switch(r){case e.AUTH:return R(o.slice(n,n+i),s);case e.PUBLISH:return O(o,s);case e.PUBCOMP:return D(o,s);case e.DISCONNECT:s.close()}})(o,i)})),yield((o,s)=>r(void 0,void 0,void 0,(function*(){const{protocolVersion:r=4,connectTimeout:i=10,username:c,password:a,will:l,keepalive:d=60,clean:u,clientId:p}=s,m=n(e.CONNECT);m.header([0,4,77,81,84,84]),m.header(r);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===r&&(f(s.properties,m.cache),m.putHeader()),r<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===r){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(((s,r)=>{const n=i=>{if(i[0]>>4===e.CONNACK){o.offMessage(n),clearTimeout(c);const{end:e}=t.bytesToIntBy128(i,1),a=i.slice(e),l=1&a[0];o.sessionPresent=l;const d=a[1];return 0===d?void s(!0):void r({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};o.onMessage(n);const c=setTimeout((()=>{o.offMessage(n),o.close(),r({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*i)}))})))(i,o),H(i);let c=0;const a=()=>(++c,16777215===c&&(c=1),c);return{getStatus:i.getStatus,onMessage:i.onMqttMessage,offMessage:i.offMqttMessage,subscribe:(o,s)=>((o,s)=>r(void 0,void 0,void 0,(function*(){console.log("=======subscribe",s);const{id:r,properties:i,payload:c}=s,a=n(e.SUBSCRIBE,2);if(a.header(t.uintToBytes(r,2)),5===o.protocolVersion){if(!i)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};f(i,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:s=0,rh:r=0}=e;t|=o<<2,t|=s<<3,t|=r<<4}a.payload(t,!1)})),console.log("=======subscribe packet",a.getPacket()),o.send(a.getPacket()),new Promise(((s,n)=>{const i=n=>{if(n[0]>>4===e.SUBACK){const e=t.bytesToIntBy128(n,1),a=e.end+e.num,l=n.slice(e.end,a);if(t.bytesToUint(l.slice(0,2))===r){let e,r=2;if(5===o.protocolVersion){const{end:o,num:s}=t.bytesToIntBy128(l,r);r=o+s,e=I(l.slice(o,r))}const n=l.slice(r);o.offMessage(i),clearTimeout(c),s({reasonCode:n,properties:e})}}};o.onMessage(i);const c=setTimeout((()=>{o.offMessage(i),o.close(),n({errCode:63011,errMsg:"Mqtt subscribe timeout"})}),1e4)}))})))(i,{id:a(),properties:null==s?void 0:s.properties,payload:[{topic:o,qos:null==s?void 0:s.qos,nl:null==s?void 0:s.nl,rap:null==s?void 0:s.rap,rh:null==s?void 0:s.rh}]}),unsubscribe:(o,s)=>((o,s)=>{const{id:r,properties:i,topics:c}=s,a=n(e.UNSUBSCRIBE,2);return a.header(t.uintToBytes(r,2)),5===o.protocolVersion&&(f(i,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),o.send(a.getPacket()),new Promise(((s,n)=>{const i=n=>{if(n[0]>>4===e.UNSUBACK){const e=t.bytesToIntBy128(n,1),a=e.end+e.num,l=n.slice(e.end,a);if(t.bytesToUint(l.slice(0,2))===r){let e,r=2;if(5===o.protocolVersion){const{end:o,num:s}=t.bytesToIntBy128(l,r);r=o+s,e=I(l.slice(o,r))}const n=l.slice(r);o.offMessage(i),clearTimeout(c),s({reasonCode:n,properties:e})}}};o.onMessage(i);const c=setTimeout((()=>{o.offMessage(i),o.close(),n({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(i,{id:a(),properties:null==s?void 0:s.properties,topics:[o]}),publish:(e,o,s)=>{const r=a();return w(i,Object.assign({id:r,topicName:e,payload:"string"==typeof o?t.stringToBytes(o):o},s))},reAuth:e=>{m(i,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:o=>{((o,t)=>{r(void 0,void 0,void 0,(function*(){const{reasonCode:s=0,properties:r}=t,i=n(e.DISCONNECT);5===o.protocolVersion&&(i.header(s),f(r,i.cache),i.putHeader()),yield o.send(i.getPacket()),o.close()}))})(i,o||{reasonCode:0})},onClose:i.onClose,onError:i.onError}}));
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,o,t=require("@ray-js/wechat-helper"),s=require("@ray-js/wechat-event");function r(e,o,t,s){return new(t||(t=Promise))((function(r,i){function n(e){try{a(s.next(e))}catch(e){i(e)}}function c(e){try{a(s.throw(e))}catch(e){i(e)}}function a(e){var o;e.done?r(e.value):(o=e.value,o instanceof t?o:new t((function(e){e(o)}))).then(n,c)}a((s=s.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 s=e<<4|o;let r=new Uint8Array(100),i=0,n=new Uint8Array(100),c=0,a=new Uint8Array(100),l=0;const d=(e,o,s,r=!1,i=!1)=>{let n;n="string"==typeof s?t.stringToBytes(s):"number"==typeof s?[s]:s;let c=new Uint8Array;r&&(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)),r&&e.set(c,o),o+=c.length,e.set(n,o),[e,o+=n.length]};function u(e,o=!1,t=!1){const[s,n]=d(r,i,e,o,t);r=s,i=n}function p(e,o=!0,t=!1){const[s,r]=d(n,c,e,o,t);n=s,c=r}return{header:u,payload:p,cleanCache(){a=new Uint8Array(100),l=0},cache:(e,o=!1,t=!1)=>{const[s,r]=d(a,l,e,o,t);a=s,l=r},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]=s;let u=1;return d.set(l,u),u+=l.length,d.set(r.slice(0,e),u),u+=e,d.set(n.slice(0,o),u),d}}},n=e=>(o,s)=>{const r=t.stringToBytes(o),i=t.uintToBytes(r.length,2);s(e),s(i),s(r)},c=e=>(o,t)=>{t(e),t(o?1:0)},a=e=>(o,s)=>{s(e),s(t.uintToBytes(o))},l=e=>(o,s)=>{s(e),s(t.uintToBytes(o,2))},d=e=>(o,s)=>{const r=t.uintToBytes(o.length,2);s(e),s(r),s(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((s=>{const r=e[s],i=t.stringToBytes(s);Array.isArray(r)?r.forEach((e=>{o(p),o(i),o(t.stringToBytes(e))})):(o(p),o(i),o(t.stringToBytes(r)))}))}),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,s)=>{s(e),s(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:s,reasonCode:r}=t,n=i(e.AUTH);if(n.header(r),!s)throw{errCode:63005,errMsg:"Properties must be given when protocol version is 5.x"};return f(s,n.cache),n.putHeader(),o.send(n.getPacket())},y=[],v=(e,o,t)=>{t?y.splice(0,0,[e,o]):y.push([e,o])};function g(e,o){const t=e.split("/"),s=e.split("/");if(e===o)return!0;for(let e=0;e<s.length;e++){const o=t[e];switch(o){case"#":return!0;case"+":continue;default:if(o!==s[e])return!1}}return!1}const h=(e,o)=>[t.bytesToUint(e.slice(o,o+=2)),o],C=(e,o)=>[t.bytesToUint(e.slice(o,o+=4)),o],T=(e,o)=>[1===e[o++],o],M=(e,o)=>{const s=t.bytesToUint(e.slice(o,o+=2));return[t.bytesToString(e.slice(o,o+=s)),o]},b=(e,o)=>{const s=t.bytesToUint(e.slice(o,o+=2));return[e.slice(o,o+=s),o]},P={sessionExpiryInterval:C,receiveMaximum:h,maximumPacketSize:C,topicAliasMaximum:h,topicAlias:h,requestResponseInformation:T,requestProblemInformation:T,userProperties:(e,o)=>{const[t,s]=M(e,o),[r,i]=M(e,s);return[[t,r],i]},authenticationMethod:M,authenticationData:b,willDelayInterval:C,payloadFormatIndicator:T,messageExpiryInterval:C,contentType:M,responseTopic:M,correlationData:b,subscriptionIdentifier:(e,o)=>{const{num:s,end:r}=t.bytesToIntBy128(e,o);return[s,r]}},I=e=>{let t=e.length>0,s=0;const r={};for(;t;){const i=e[s++],n=Object.keys(o).find((e=>o[e]===i));if(!n)throw{errCode:63013,errMsg:`Unrecognized property: ${i}`};{const c=P[n](e,s);if(i===o.userProperties){const e=r[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 r[n]=c[0];s=c[1],t=s<e.length}}return r},B=(e,o)=>{const{end:s}=t.bytesToIntBy128(e,1),r=e.slice(s),i=t.bytesToUint(r.slice(0,2));let n,c=0;if(5===o.protocolVersion){c=r[2];const{num:o,end:s}=t.bytesToIntBy128(r,3);n=I(e.slice(s,o))}return{id:i,reasonCode:c,properties:n}},w=(o,s)=>r(void 0,void 0,void 0,(function*(){const{dup:r,qos:n=0,topicName:c,id:a,properties:l,payload:d}=s;let u=0|(r?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);try{yield o.send(p.getPacket())}catch(e){return void o.emitError(e)}if(0!==n)if(1===n)try{yield x(o,s)}catch(e){w(o,s)}else try{const e=yield N(o,a);o.options.onPubrel?A(o,o.options.onPubrel(e)):A(o,{id:a,reasonCode:0}),yield k(o,s)}catch(e){w(o,s)}})),E=(e,o,s,n=0)=>r(void 0,void 0,void 0,(function*(){const{id:r,properties:c,reasonCode:a}=o,l=i(s,n);l.header(t.uintToBytes(r,2)),5===e.protocolVersion&&(l.header(a||0),f(c,l.cache),l.putHeader()),e.send(l.getPacket())})),U=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBACK)})),A=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREL,2)})),S=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBREC,0)})),q=(o,t)=>r(void 0,void 0,void 0,(function*(){E(o,t,e.PUBCOMP,0)})),x=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{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)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))})),N=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{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)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))})),k=(o,t)=>r(void 0,void 0,void 0,(function*(){return new Promise(((s,r)=>{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)s(e);else{const t={errCode:63010,errMsg:`MQTT publish failure, code: ${e.reasonCode}`};r(t),o.emitError(t)}}};o.onMessage(i);const n=setTimeout((()=>{o.offMessage(i),o.close();const e={errCode:63009,errMsg:"Mqtt publish timeout"};r(e),o.emitError(e)}),1e4)}))}));v((()=>!(!window||!window.WebSocket)),((e,o)=>r(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 s=0;const r=setInterval((()=>{s++,200===s&&o(),0===t.bufferedAmount&&(clearInterval(r),t.close(),e(!0))}),16)})),onClose:e=>{t.addEventListener("close",e)},onMessage:e=>{t.addEventListener("message",e)},onError:e=>{t.addEventListener("error",e)}}}))));v((()=>!(!wx||!wx.connectSocket)),((e,o)=>r(void 0,void 0,void 0,(function*(){const t=yield((e,o)=>r(void 0,void 0,void 0,(function*(){return new Promise(((t,s)=>{const r=wx.connectSocket({url:e,protocols:4===o?["mqttv3.1"]:["mqtt"],fail:s});r&&t(r)}))})))(e,o);return{onOpen:e=>{t.onOpen(e)},send:e=>new Promise(((o,s)=>{t.send({data:e,fail:s,success:o})})),close:()=>{t.close()},onClose:e=>{t.onClose(e)},onMessage:e=>{t.onMessage(e)},onError:e=>{t.onError(e)}}}))));const R=(e,o)=>{const s=(e=>{let o=0;const s=e[o++],{num:r,end:i}=t.bytesToIntBy128(e,1);return{reasonCode:s,properties:I(e.slice(i,i+r))}})(e);if(24===s.reasonCode){if(void 0===o.options.onAuth)throw{errCode:63018,errMsg:"The option onAuth not set"};m(o,o.options.onAuth(s))}},O=(e,o)=>{const s=((e,o)=>{const s=e[0],r=(6&s)>>1,i=(8&s)>>3==1;let n=1;const{num:c,end:a}=t.bytesToIntBy128(e,n),l=a+c;n=a;const d=M(e,n),[u]=d;let p,f;if(n=d[1],r>0&&(p=t.bytesToUint(e.slice(n,n+=2))),5===o.protocolVersion){const{num:o,end:s}=t.bytesToIntBy128(e,n);f=I(e.slice(s,o)),n=o+s}return{qos:r,dup:i,topicName:u,id:p,payload:e.slice(n,l),properties:f}})(e,o);let{topicName:r}=s;if(o.protocolVersion>=5&&s.properties){const{topicAlias:e}=s.properties;if(e)if(r)o.applyTopic(e,r);else if(r=o.getTopic(e),!r)return void o.emitError({errCode:63019,errMsg:"Received unregistered Topic Alias"})}if(o.checkTopic(r))switch(s.qos){case 0:o.emitMqttMessage({topic:r,payload:s.payload});break;case 1:o.options.onPuback?U(o,o.options.onPuback(s)):U(o,{id:s.id,reasonCode:0});break;case 2:o.options.onPubrec?S(o,o.options.onPubrec(s)):S(o,{id:s.id,reasonCode:0})}else o.emitError({errCode:63020,errMsg:"Received unsubscribe Topic"})},D=(e,o)=>{const t=B(e,o);o.options.onPubcomp?q(o,o.options.onPubcomp(t)):q(o,{id:t.id,reasonCode:0})},H=o=>{const t=1e3*(o.options.keepalive||60),s=()=>r(void 0,void 0,void 0,(function*(){try{!o.isClose()&&(yield(o=>(o.send(new Uint8Array([e.PINGREQ<<4,0])),new Promise(((t,s)=>{const r=s=>{s[0]>>4===e.PINGRESP&&(o.offMessage(r),clearTimeout(i),t(!0))};o.onMessage(r);const i=setTimeout((()=>{o.offMessage(r),o.close(),s({errCode:63016,errMsg:"Mqtt ping timeout"})}),1e4)}))))(o)),setTimeout(s,t)}catch(e){console.warn("ping error",e),o.close()}}));setTimeout(s,t)};exports.createMQTT=o=>r(void 0,void 0,void 0,(function*(){const n=yield(e=>r(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=s.createEmitter();let c=null,a=0;const l={};return{options:e,protocolVersion:o,sessionPresent:0,connect:(s=!1)=>r(void 0,void 0,void 0,(function*(){if(s&&c)try{c.close()}catch(e){}const r=++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=>{0===i?(clearTimeout(t),o(e)):r===a&&(i=2,n.emit("error",e),n.emit("close",e))})),c&&c.onOpen((()=>{clearTimeout(t),i=1,c&&c.onClose((e=>{r===a&&(i=2,n.emit("close",e))})),c&&c.onMessage((e=>{r===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:()=>{i=2,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],checkTopic:o=>"string"==typeof e.subscribeTopics?g(e.subscribeTopics,o):e.subscribeTopics.some((e=>g(e,o)))}}throw{errCode:63e3,errMsg:"The current environment does not support MQTT"}})))(o);yield n.connect(),n.onMessage((o=>{((o,s)=>{const r=o[0]>>4,{end:i,num:n}=t.bytesToIntBy128(o,1);switch(r){case e.AUTH:return R(o.slice(i,i+n),s);case e.PUBLISH:return O(o,s);case e.PUBCOMP:return D(o,s);case e.DISCONNECT:s.close()}})(o,n)})),yield((o,s)=>r(void 0,void 0,void 0,(function*(){const{protocolVersion:r=4,connectTimeout:n=10,username:c,password:a,will:l,keepalive:d=60,clean:u,clientId:p}=s,m=i(e.CONNECT);m.header([0,4,77,81,84,84]),m.header(r);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===r&&(f(s.properties,m.cache),m.putHeader()),r<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===r){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(((s,r)=>{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 s(!0):void r({errCode:63008,errMsg:`MQTT connect failure, code: ${d}`})}};o.onMessage(i);const c=setTimeout((()=>{o.offMessage(i),o.close(),r({errCode:63007,errMsg:"Mqtt Connect timeout"})}),1e3*n)}))})))(n,o),H(n);let c=0;const a=()=>(++c,16777215===c&&(c=1),c);return{getStatus:n.getStatus,onMessage:n.onMqttMessage,offMessage:n.offMqttMessage,subscribe:(o,s)=>((o,s)=>r(void 0,void 0,void 0,(function*(){const{id:r,properties:n,payload:c}=s,a=i(e.SUBSCRIBE,2);if(a.header(t.uintToBytes(r,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:s=0,rh:r=0}=e;t|=o<<2,t|=s<<3,t|=r<<4}a.payload(t,!1)})),o.send(a.getPacket()),new Promise(((s,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))===r){let e,r=2;if(5===o.protocolVersion){const{end:o,num:s}=t.bytesToIntBy128(l,r);r=o+s,e=I(l.slice(o,r))}const i=l.slice(r);o.offMessage(n),clearTimeout(c),s({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==s?void 0:s.properties,payload:[{topic:o,qos:null==s?void 0:s.qos,nl:null==s?void 0:s.nl,rap:null==s?void 0:s.rap,rh:null==s?void 0:s.rh}]}),unsubscribe:(o,s)=>((o,s)=>{const{id:r,properties:n,topics:c}=s,a=i(e.UNSUBSCRIBE,2);return a.header(t.uintToBytes(r,2)),5===o.protocolVersion&&(f(n,a.cache),a.putHeader()),c.forEach((e=>{a.payload(e)})),o.send(a.getPacket()),new Promise(((s,i)=>{const n=i=>{if(i[0]>>4===e.UNSUBACK){const e=t.bytesToIntBy128(i,1),a=e.end+e.num,l=i.slice(e.end,a);if(t.bytesToUint(l.slice(0,2))===r){let e,r=2;if(5===o.protocolVersion){const{end:o,num:s}=t.bytesToIntBy128(l,r);r=o+s,e=I(l.slice(o,r))}const i=l.slice(r);o.offMessage(n),clearTimeout(c),s({reasonCode:i,properties:e})}}};o.onMessage(n);const c=setTimeout((()=>{o.offMessage(n),o.close(),i({errCode:63014,errMsg:"Mqtt unsubscribe timeout"})}),1e4)}))})(n,{id:a(),properties:null==s?void 0:s.properties,topics:[o]}),publish:(e,o,s)=>{const r=a();return w(n,Object.assign({id:r,topicName:e,payload:"string"==typeof o?t.stringToBytes(o):o},s))},reAuth:e=>{m(n,Object.assign(Object.assign({},e),{reasonCode:25}))},disconnect:o=>{((o,t)=>{r(void 0,void 0,void 0,(function*(){const{reasonCode:s=0,properties:r}=t,n=i(e.DISCONNECT);5===o.protocolVersion&&(n.header(s),f(r,n.cache),n.putHeader()),yield o.send(n.getPacket()),o.close()}))})(n,o||{reasonCode:0})},onClose:n.onClose,onError:n.onError}}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ray-js/wechat-mqtt",
|
|
3
|
-
"version": "0.0.15-beta-
|
|
3
|
+
"version": "0.0.15-beta-2",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
}
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@ray-js/wechat-helper": "^0.0.15-beta-
|
|
21
|
-
"@ray-js/wechat-event": "^0.0.15-beta-
|
|
20
|
+
"@ray-js/wechat-helper": "^0.0.15-beta-2",
|
|
21
|
+
"@ray-js/wechat-event": "^0.0.15-beta-2"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {}
|
|
24
24
|
}
|