u8-mqtt 0.1.0 → 0.1.3
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/cjs/index.cjs +64 -33
- package/cjs/index.cjs.map +1 -1
- package/cjs/v4.cjs +64 -33
- package/cjs/v4.cjs.map +1 -1
- package/cjs/v5.cjs +64 -33
- package/cjs/v5.cjs.map +1 -1
- package/code/base.jsy +63 -32
- package/esm/deno/index.js +64 -33
- package/esm/deno/index.js.map +1 -1
- package/esm/deno/index.mjs +64 -33
- package/esm/deno/index.mjs.map +1 -1
- package/esm/deno/v4.js +64 -33
- package/esm/deno/v4.js.map +1 -1
- package/esm/deno/v4.mjs +64 -33
- package/esm/deno/v4.mjs.map +1 -1
- package/esm/deno/v5.js +64 -33
- package/esm/deno/v5.js.map +1 -1
- package/esm/deno/v5.mjs +64 -33
- package/esm/deno/v5.mjs.map +1 -1
- package/esm/node/index.js +64 -33
- package/esm/node/index.js.map +1 -1
- package/esm/node/index.mjs +64 -33
- package/esm/node/index.mjs.map +1 -1
- package/esm/node/v4.js +64 -33
- package/esm/node/v4.js.map +1 -1
- package/esm/node/v4.mjs +64 -33
- package/esm/node/v4.mjs.map +1 -1
- package/esm/node/v5.js +64 -33
- package/esm/node/v5.js.map +1 -1
- package/esm/node/v5.mjs +64 -33
- package/esm/node/v5.mjs.map +1 -1
- package/esm/web/index.js +64 -33
- package/esm/web/index.js.map +1 -1
- package/esm/web/index.min.mjs +1 -1
- package/esm/web/index.mjs +64 -33
- package/esm/web/index.mjs.map +1 -1
- package/esm/web/v4.js +64 -33
- package/esm/web/v4.js.map +1 -1
- package/esm/web/v4.min.mjs +1 -1
- package/esm/web/v4.mjs +64 -33
- package/esm/web/v4.mjs.map +1 -1
- package/esm/web/v5.js +64 -33
- package/esm/web/v5.js.map +1 -1
- package/esm/web/v5.min.mjs +1 -1
- package/esm/web/v5.mjs +64 -33
- package/esm/web/v5.mjs.map +1 -1
- package/package.json +4 -4
package/esm/web/v4.min.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function n(t){let n=new Uint8Array(0);return r=>{n=0===n.byteLength?r:function(t,e){const n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(n,r);const s=[];for(;;){const[r,i]=e(n,1),o=r+i;if(n.byteLength<o)return s;let u=n[0],a=0===r?null:n.subarray(i,o);n=n.subarray(o);const c=t(u,a);null!=c&&s.push(c)}}}const r=new Map;{const t=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qo_s"],[37,"u8","retain_available"],[38,"pair","user_properties",!0],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",!0],[42,"u8","shared_subscription_available"]];for(const[e,n,s,i]of t){const t={id:e,type:n,name:s};i&&(t.plural=i),r.set(t.id,t),r.set(t.name,t)}}const s=t=>new TextDecoder("utf-8").decode(t),i=t=>(e,n)=>(n=t,t+=e,n);class o{constructor(t,e=0){this.buf=t,this.step=i(e)}_fork(t,e){return{__proto__:this,buf:t,step:i(e)}}has_more(){const{buf:t,step:e}=this;return t.byteLength>e(0)}u8(){const{buf:t,step:e}=this;return t[e(1)]}u16(){const{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){const{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){const{buf:t,step:n}=this,[r,s,i]=e(t,n(0));return n(s-i),r}vbuf(){const{buf:t,step:n}=this,[r,s,i]=e(t,n(0));return n(r+s-i),0===r?null:t.subarray(s,n(0))}bin(){const{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1],s=e(r);return t.subarray(s,s+r)}utf8(){return s(this.bin())}pair(){return[s(this.bin()),s(this.bin())]}u8_flags(t){const{buf:e,step:n}=this;return new t(e[n(1)])}u8_reason(t){const{buf:e,step:n}=this;return t(e[n(1)])}flush(){const{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(e(0))}props(){let t=this.vbuf();return null===t?null:this._fork(t,0)._read_props([])}_read_props(t){for(;this.has_more();){let e=this.u8(),n=r.get(e),s=this[n.type]();t.push([n.name,s])}return t}}class u extends Number{constructor(t,e){super(t),this.reason=e}}function a(t){const e=new Map;for(const[n,r]of t)e.set(n,new u(n,r));return e.get.bind(e)}function c(t){class e extends Number{get session_present(){return!0&this}}const n=a([[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"]]);return t[2]=(t,r)=>{const s=new o(r,0);return t.flags=s.u8_flags(e),t.reason=s.u8_reason(n),5<=t.mqtt_level&&(t.props=s.props()),t}}function p(t){return t[3]=(t,e)=>{const{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);const r=t.qos=n>>1&3,s=new o(e,0);return t.topic=s.utf8(),0!==r&&(t.pkt_id=s.u16()),5<=t.mqtt_level&&(t.props=s.props()),t.payload=s.flush(),t}}function l(t){const e=a([[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"]]);return t[4]=(t,n)=>{const r=new o(n,0);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.u8_reason(e),t.props=r.props()),t}}function _(t){const e=a([[0,"Success"],[146,"Packet Identifier not found"]]);return t[5]=t[6]=t[7]=(t,n)=>{const r=new o(n,0);return t.pkt_id=r.u16(),t.reason=r.u8_reason(e),5<=t.mqtt_level&&(t.props=r.props()),t}}function d(t){return(e,n)=>{const r=new o(n,0);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());const s=e.answers=[];for(;r.has_more();)s.push(r.u8_reason(t));return e}}function f(t){const e=a([[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"]]);return t[9]=d(e)}function h(t){const e=a([[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"]]);return t[11]=d(e)}function b(t){return t[12]=t[13]=t=>t}function m(t){const e=a([[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"]]);return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){const r=new o(n,0);t.reason=r.u8_reason(e),t.props=r.props()}return t}}function v(t){const e=a([[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"]]);return t[15]=(t,n)=>{if(5<=t.mqtt_level){const r=new o(n,0);t.reason=r.u8_reason(e),t.props=r.props()}return t}}const w=Array.isArray,y=t=>[t>>>8&255,255&t];class g{constructor(){this._pkt_writer(this)}as_pkt(t){return this.pack([t])}u8(t){this.push([255&t])}u16(t){this.push(y(t))}u32(t){this.push((t=>[t>>>24&255,t>>>16&255,t>>>8&255,255&t])(t))}vint(e){this.push(t(e))}_u16_bin(t){const{push:e}=this;e(y(t.byteLength)),e(t)}flush(t){var e;null!=t&&this.push("string"==typeof t?(e=t,new TextEncoder("utf-8").encode(e)):t),this.push=!1}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),void this._u16_bin(t)):this.u16(0)}utf8(t){this._u16_bin(new TextEncoder("utf-8").encode(t))}pair(t,e){this.utf8(t),this.utf8(e)}u8_flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}u8_reason(t){this.push([0|t])}props(t){if(!t)return this.u8(0);if(w(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);const e=this._fork();for(const[n,s]of t){const{id:t,type:i}=r.get(n);e.u8(t),e[i](s)}this.push(e.pack([]))}_fork(){let t={__proto__:this};return this._pkt_writer(t),t}}g.prototype._pkt_writer=function(){const e=[];return n=>0===e.length?function(e,n){let r=0,s=[];return i(e);function i(t){(e=t).push=o,e.pack=u}function o(t){s.push(t),r+=t.length}function u(o){e=e.push=e.pack=null;const u=function(e,n,r){const s=t(n,e);let i=s.length;const o=new Uint8Array(n+i);o.set(s,0);for(const t of r)o.set(t,i),i+=t.length;return o}(o,r,s);return r=0,s=[],void 0!==n&&n.push(i),u}}(n,e):e.pop()(n)}();const k=new Uint8Array([0,4,77,81,84,84]);function q(t){const e=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,n)=>{const r=new g;r.push(k),r.u8(t);const{will:s,username:i,password:o}=n,u=r.u8_flags(n.flags,e,0|(i?128:0)|(o?64:0)|(s?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(s):0));return r.u16(n.keep_alive),5<=t&&r.props(n.props),r.utf8(n.client_id),4&u&&(5<=t&&r.props(s.props),r.utf8(s.topic),r.bin(s.payload)),128&u&&r.utf8(i),64&u&&r.bin(o),r.as_pkt(16)}}function x(t){return t.publish=(t,e)=>{const n=(3&e.qos)<<1,r=new g;return r.utf8(e.topic),0!==n&&r.u16(e.pkt_id),5<=t?(r.props(e.props),r.flush(e.payload)):r.flush(e.payload),r.as_pkt(48|n|(e.dup?8:0)|(e.retain?1:0))}}function S(t){return t.puback=(t,e)=>{const n=new g;return n.u16(e.pkt_id),5<=t&&(n.u8_reason(e.reason),n.props(e.props)),n.as_pkt(64)}}function N(t){const e=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{const r=new g;r.u16(n.pkt_id),5<=t&&r.props(n.props);const s=e(n);for(const t of n.topics)if("string"==typeof t)r.utf8(t),r.u8(s);else{let[n,i]=w(t)?t:[t.topic,t.opts];r.utf8(n),void 0===i?r.u8(s):r.u8_flags(i,e)}return r.as_pkt(130)}}function P(t){return t.unsubscribe=(t,e)=>{const n=new g;n.u16(e.pkt_id),5<=t&&n.props(e.props);for(const t of e.topics)n.utf8(t);return n.as_pkt(162)}}function A(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])}function I(t){return t.disconnect=(t,e)=>{const n=new g;return e&&5<=t&&(e.reason||e.props)&&(n.u8_reason(e.reason),n.props(e.props)),n.as_pkt(224)}}function T(t){return t.auth=(t,e)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");const n=new g;return n.u8_reason(e.reason),n.props(e.props),n.as_pkt(240)}}const U=["reserved","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"],j=t=>Object.defineProperties(t||{},{hdr:{get(){return 15&this.b0}},id:{get(){return this.b0>>>4}},type:{get(){return U[this.b0>>>4]}}});function M(t,e,r){return t=function(t){const e=[];for(const n of t)n(e);return t=>n(((n,r)=>{const s=e[n>>>4]||e[0];if(void 0!==s)return s({__proto__:t,b0:n},r)}))}(t),e=function(t){const e={};for(const n of t)n(e);return({mqtt_level:t})=>(n,r)=>e[n](t,r)}(e),r=j(r),n=>s=>[t(s=s||{__proto__:r,mqtt_level:n,get _base_(){return s}}),e(s),s]}function E(t){let{ctx:e}=E;if(void 0===e){let t=t=>new TextDecoder("utf-8").decode(t),n={utf8(e){return t(e||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};E.ctx=e=M([c,m,p,l,_,b,f,h,v],[q,I,x,S,A,N,P,T],n)}return e(t)}async function Q(t,e){void 0!==e&&await e.call(t,await t)}function C(){let t=[];return t.then=e=>{t.push(e)},t.notify=e=>{for(let n of t.splice(0,t.length))n(e)},t}function L(t,e,n){n.done=!0}function O(){let t=[[],[]],e=e=>function*(t,e){for(let n of t)for(let t of n){let n=z(e,t);void 0!==n&&(yield n)}}(t,e);return{find:e,add(e,...n){let r=n.pop(),s=n.pop();if("function"!=typeof r){if(!1!==r)throw new TypeError;r=L}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var n,r,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(n=s[0])?(o.push("wild"),u+="/(.*)"):":"===n?(r=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~r?r:~i?i:s.length)),u+=~r&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~r?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(e.replace(/[+#]$/,"*"));return i.key=e,i.tgt=r,t[s?0:1].push(i),this},remove(e,n){let r=t[n?0:1];r=r.filter((t=>t.key!==e)),t[n?0:1]=r},clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(t,n){n.idx=0;for(let[r,s]of e(t.topic)){if(await r(t,s,n),n.done)break;n.idx++}let{pkt_id:r,qos:s}=t;1===s&&await n.mqtt._send("puback",{pkt_id:r})}}}function z(t,{keys:e,pattern:n,tgt:r}){let s="/"!==t[0]?n.exec("/"+t):n.exec(t);if(null===s)return;if(!1===e){let{groups:t}=s;if(!t)return[r];let e={};for(let n in t)e[n]=t[n];return[r,e]}if(0===e.length)return[r];let i={};for(let t=0;t<e.length;t++)i[e[t]]=s[1+t];return[r,i]}const R={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;void 0!==r&&await r.call(t,e,n)}})()};class D{constructor(t={}){this._conn_=function(t,[e,n]){let r,s=C(),i=C(),o=async(...t)=>(await i)(...t),u=t._send=o,a=()=>t._send("pingreq"),c=!1;return{is_live:()=>o!==u,is_set:()=>c,reset(){r=clearInterval(r),t._send=u=o,c=!1,Q(t,t.on_reconnect)},ping(t){r=clearInterval(r),t&&(r=setInterval(a,1e3*t),r.unref&&r.unref())},async send_connect(...e){o===u&&(u=await s);let n=await u(...e);return t._send=u,i.notify(u),n},set(r,i){c=!0;let[o,a]=r;return u=async(t,e,r)=>{let s=void 0===r||n(r);return await i(a(t,e)),s},s.notify(u),Q(t,t.on_live),n=>e(o(n),{mqtt:t})}}}(this,this._init_dispatch(t,this))}async connect(t={}){let{client_id:e}=t;e?Array.isArray(e)?t.client_id=e=this.init_client_id(e):this.client_id=e:t.client_id=e=this.init_client_id(["u8-mqtt--",""]),null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}subscribe(t,e){return t=$(t,e),this._send("subscribe",t,t)}unsubscribe(t,e){return t=$(t,e),this._send("unsubscribe",t,t)}get on_topic(){return this.router.add}subscribe_topic(t,...e){let n=this.topic_for(t);return this.router.add(t,!0,e.pop()),this.subscribe([[n]],e.pop()),this}unsubscribe_topic(t){let e=this.topic_for(t);return this.router.remove(t,!0),this.unsubscribe([[e]])}topic_for(t){return t.replace(/[:*].*$/,"#")}publish(t,e){return B(this,t,e)}post(t,e){return B.m(this,t,e)}send(t,e){return B.mq(this,t,e)}store(t,e){return B.mqr(this,t,e)}json_post(t,e){return B.o(this,t,e)}json_send(t,e){return B.oq(this,t,e)}json_store(t,e){return B.oqr(this,t,e)}obj_post(t,e,n){return B.o(this,t,e,n)}obj_send(t,e,n){return B.oq(this,t,e,n)}obj_store(t,e,n){return B.oqr(this,t,e,n)}init_client_id(t){let e=this.client_id;return void 0===e&&(this.client_id=e=this.sess_client_id(t)),e}new_client_id(t){return[t[0],Math.random().toString(36).slice(2),t[1]].join("")}sess_client_id(t){let e=`client_id ${t.join("")}`,n=sessionStorage.getItem(e);return null==n&&(n=this.new_client_id(t),sessionStorage.setItem(e,n)),n}_init_router(t){return this.router=O()}_init_dispatch(t){let e=this._init_router(t,this),n={__proto__:t.on_mqtt_type||{},router:e};return n.mqtt_publish||(n.mqtt_publish=e.invoke),function(t,e){let n=R.create(e),{cmdids:r}=n,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>o&&(n.rotate_belt(i),o=s+Date.now())},n.bind_pkt_future()]}(this,n)}}{let t=D.prototype;Object.assign(t,{pub:t.publish,sub:t.subscribe,unsub:t.unsubscribe,sub_topic:t.subscribe_topic,unsub_topic:t.unsubscribe_topic})}function $(t,e){return"string"==typeof t?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t}async function B(t,e,n){if(void 0===e.payload){let{msg:r}=e;switch(typeof r){case"function":n=r,r=void 0;case"undefined":let s=e.arg||"payload";return r=>B(t,{...e,[s]:r},n);default:e.payload=n?await n(r):JSON.stringify(r)}}return t._send("publish",e,e.qos?e:void 0)}Object.assign(B,{m:(t,e,n)=>B(t,{topic:e,payload:n,qos:0}),mq:(t,e,n)=>B(t,{topic:e,payload:n,qos:1}),mqr:(t,e,n)=>B(t,{topic:e,payload:n,qos:1,retain:1}),o:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:0},r),oq:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:1},r),oqr:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:1,retain:1},r)});class W extends D{static _with_session(t){this.prototype._mqtt_session=t}constructor(t={}){super(t),this.with_live(t.on_live),this.with_reconnect(t.on_reconnect)}with_live(t){return t&&(this.on_live=t),this}with_reconnect(t){return t&&(this.on_reconnect=t,this._conn_.is_set||t(this)),this}with_async_iter(t,e){let n=this._conn_.set(this._mqtt_session(),e);return this._msg_loop=(async()=>{t=await t;for await(let e of t)n(e);this._conn_.reset()})(),this}with_websock(t){null==t&&(t="ws://127.0.0.1:9001"),(t.origin||"string"==typeof t)&&(t=new WebSocket(new URL(t),["mqtt"])),t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.addEventListener("open",e,{once:!0})))}let{_conn_:r}=this,s=r.set(this._mqtt_session(),(async n=>(await e,t.send(n))));return t.addEventListener("close",(()=>{delete t.onmessage,r.reset()}),{once:!0}),t.onmessage=t=>s(new Uint8Array(t.data)),this}}class F extends W{_mqtt_session(){return E(4)()}}const G=t=>new F(t);export{F as MQTTClient,F as MQTTClient_v4,G as default,G as mqtt,G as mqtt_v4};
|
|
1
|
+
function t(t,e=[]){do{const n=127&t;t>>>=7,e.push(n|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let n=e,r=(127&t[e])<<0;return 128&t[e++]&&(r|=(127&t[e])<<7,128&t[e++]&&(r|=(127&t[e])<<14,128&t[e++]&&(r|=(127&t[e])<<21))),[r,e,n]}function n(t){let n=new Uint8Array(0);return r=>{n=0===n.byteLength?r:function(t,e){const n=t.byteLength,r=new Uint8Array(n+e.byteLength);return r.set(t,0),r.set(e,n),r}(n,r);const s=[];for(;;){const[r,i]=e(n,1),o=r+i;if(n.byteLength<o)return s;let u=n[0],a=0===r?null:n.subarray(i,o);n=n.subarray(o);const c=t(u,a);null!=c&&s.push(c)}}}const r=new Map;{const t=[[1,"u8","payload_format_indicator"],[2,"u32","message_expiry_interval"],[3,"utf8","content_type"],[8,"utf8","response_topic"],[9,"bin","correlation_data"],[11,"vint","subscription_identifier"],[17,"u32","session_expiry_interval"],[18,"utf8","assigned_client_identifier"],[19,"u16","server_keep_alive"],[21,"utf8","authentication_method"],[22,"bin","authentication_data"],[23,"u8","request_problem_information"],[24,"u32","will_delay_interval"],[25,"u8","request_response_information"],[26,"utf8","response_information"],[28,"utf8","server_reference"],[31,"utf8","reason_string"],[33,"u16","receive_maximum"],[34,"u16","topic_alias_maximum"],[35,"u16","topic_alias"],[36,"u8","maximum_qo_s"],[37,"u8","retain_available"],[38,"pair","user_properties",!0],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",!0],[42,"u8","shared_subscription_available"]];for(const[e,n,s,i]of t){const t={id:e,type:n,name:s};i&&(t.plural=i),r.set(t.id,t),r.set(t.name,t)}}const s=t=>new TextDecoder("utf-8").decode(t),i=t=>(e,n)=>(n=t,t+=e,n);class o{constructor(t,e=0){this.buf=t,this.step=i(e)}_fork(t,e){return{__proto__:this,buf:t,step:i(e)}}has_more(){const{buf:t,step:e}=this;return t.byteLength>e(0)}u8(){const{buf:t,step:e}=this;return t[e(1)]}u16(){const{buf:t,step:e}=this,n=e(2);return t[n]<<8|t[n+1]}u32(){const{buf:t,step:e}=this,n=e(4);return t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3]}vint(){const{buf:t,step:n}=this,[r,s,i]=e(t,n(0));return n(s-i),r}vbuf(){const{buf:t,step:n}=this,[r,s,i]=e(t,n(0));return n(r+s-i),0===r?null:t.subarray(s,n(0))}bin(){const{buf:t,step:e}=this,n=e(2),r=t[n]<<8|t[n+1],s=e(r);return t.subarray(s,s+r)}utf8(){return s(this.bin())}pair(){return[s(this.bin()),s(this.bin())]}u8_flags(t){const{buf:e,step:n}=this;return new t(e[n(1)])}u8_reason(t){const{buf:e,step:n}=this;return t(e[n(1)])}flush(){const{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(e(0))}props(){let t=this.vbuf();return null===t?null:this._fork(t,0)._read_props([])}_read_props(t){for(;this.has_more();){let e=this.u8(),n=r.get(e),s=this[n.type]();t.push([n.name,s])}return t}}class u extends Number{constructor(t,e){super(t),this.reason=e}}function a(t){const e=new Map;for(const[n,r]of t)e.set(n,new u(n,r));return e.get.bind(e)}function c(t){class e extends Number{get session_present(){return!0&this}}const n=a([[0,"Success"],[1,"Connection refused, unacceptable protocol version"],[2,"Connection refused, identifier rejected"],[3,"Connection refused, server unavailable"],[4,"Connection refused, bad user name or password"],[5,"Connection refused, not authorized"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[132,"Unsupported Protocol Version"],[133,"Client Identifier not valid"],[134,"Bad User Name or Password"],[135,"Not authorized"],[136,"Server unavailable"],[137,"Server busy"],[138,"Banned"],[140,"Bad authentication method"],[144,"Topic Name invalid"],[149,"Packet too large"],[151,"Quota exceeded"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[159,"Connection rate exceeded"]]);return t[2]=(t,r)=>{const s=new o(r,0);return t.flags=s.u8_flags(e),t.reason=s.u8_reason(n),5<=t.mqtt_level&&(t.props=s.props()),t}}function p(t){return t[3]=(t,e)=>{const{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);const r=t.qos=n>>1&3,s=new o(e,0);return t.topic=s.utf8(),0!==r&&(t.pkt_id=s.u16()),5<=t.mqtt_level&&(t.props=s.props()),t.payload=s.flush(),t}}function l(t){const e=a([[0,"Success"],[16,"No matching subscribers"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[144,"Topic Name invalid"],[145,"Packet identifier in use"],[151,"Quota exceeded"],[153,"Payload format invalid"]]);return t[4]=(t,n)=>{const r=new o(n,0);return t.pkt_id=r.u16(),5<=t.mqtt_level&&(t.reason=r.u8_reason(e),t.props=r.props()),t}}function _(t){const e=a([[0,"Success"],[146,"Packet Identifier not found"]]);return t[5]=t[6]=t[7]=(t,n)=>{const r=new o(n,0);return t.pkt_id=r.u16(),t.reason=r.u8_reason(e),5<=t.mqtt_level&&(t.props=r.props()),t}}function d(t){return(e,n)=>{const r=new o(n,0);e.pkt_id=r.u16(),5<=e.mqtt_level&&(e.props=r.props());const s=e.answers=[];for(;r.has_more();)s.push(r.u8_reason(t));return e}}function h(t){const e=a([[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"],[151,"Quota exceeded"],[158,"Shared Subscriptions not supported"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"]]);return t[9]=d(e)}function f(t){const e=a([[0,"Success"],[17,"No subscription existed"],[128,"Unspecified error"],[131,"Implementation specific error"],[135,"Not authorized"],[143,"Topic Filter invalid"],[145,"Packet Identifier in use"]]);return t[11]=d(e)}function b(t){return t[12]=t[13]=t=>t}function m(t){const e=a([[0,"Normal disconnection"],[4,"Disconnect with Will Message"],[128,"Unspecified error"],[129,"Malformed Packet"],[130,"Protocol Error"],[131,"Implementation specific error"],[135,"Not authorized"],[137,"Server busy"],[139,"Server shutting down"],[141,"Keep Alive timeout"],[142,"Session taken over"],[143,"Topic Filter invalid"],[144,"Topic Name invalid"],[147,"Receive Maximum exceeded"],[148,"Topic Alias invalid"],[149,"Packet too large"],[150,"Message rate too high"],[151,"Quota exceeded"],[152,"Administrative action"],[153,"Payload format invalid"],[154,"Retain not supported"],[155,"QoS not supported"],[156,"Use another server"],[157,"Server moved"],[158,"Shared Subscriptions not supported"],[159,"Connection rate exceeded"],[160,"Maximum connect time"],[161,"Subscription Identifiers not supported"],[162,"Wildcard Subscriptions not supported"]]);return t[14]=(t,n)=>{if(n&&5<=t.mqtt_level){const r=new o(n,0);t.reason=r.u8_reason(e),t.props=r.props()}return t}}function w(t){const e=a([[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"]]);return t[15]=(t,n)=>{if(5<=t.mqtt_level){const r=new o(n,0);t.reason=r.u8_reason(e),t.props=r.props()}return t}}const v=Array.isArray,y=t=>[t>>>8&255,255&t];class g{constructor(){this._pkt_writer(this)}as_pkt(t){return this.pack([t])}u8(t){this.push([255&t])}u16(t){this.push(y(t))}u32(t){this.push((t=>[t>>>24&255,t>>>16&255,t>>>8&255,255&t])(t))}vint(e){this.push(t(e))}_u16_bin(t){const{push:e}=this;e(y(t.byteLength)),e(t)}flush(t){var e;null!=t&&this.push("string"==typeof t?(e=t,new TextEncoder("utf-8").encode(e)):t),this.push=!1}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),void this._u16_bin(t)):this.u16(0)}utf8(t){this._u16_bin(new TextEncoder("utf-8").encode(t))}pair(t,e){this.utf8(t),this.utf8(e)}u8_flags(t,e,n=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=n,this.push([t]),t}u8_reason(t){this.push([0|t])}props(t){if(!t)return this.u8(0);if(v(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);const e=this._fork();for(const[n,s]of t){const{id:t,type:i}=r.get(n);e.u8(t),e[i](s)}this.push(e.pack([]))}_fork(){let t={__proto__:this};return this._pkt_writer(t),t}}g.prototype._pkt_writer=function(){const e=[];return n=>0===e.length?function(e,n){let r=0,s=[];return i(e);function i(t){(e=t).push=o,e.pack=u}function o(t){s.push(t),r+=t.length}function u(o){e=e.push=e.pack=null;const u=function(e,n,r){const s=t(n,e);let i=s.length;const o=new Uint8Array(n+i);o.set(s,0);for(const t of r)o.set(t,i),i+=t.length;return o}(o,r,s);return r=0,s=[],void 0!==n&&n.push(i),u}}(n,e):e.pop()(n)}();const k=new Uint8Array([0,4,77,81,84,84]);function q(t){const e=t=>0|(t.reserved?1:0)|(3&t.will_qos)<<3|(t.clean_start?2:0)|(t.will_flag?4:0)|(t.will_retain?32:0)|(t.password?64:0)|(t.username?128:0);return t.connect=(t,n)=>{const r=new g;r.push(k),r.u8(t);const{will:s,username:i,password:o}=n,u=r.u8_flags(n.flags,e,0|(i?128:0)|(o?64:0)|(s?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(s):0));return r.u16(n.keep_alive),5<=t&&r.props(n.props),r.utf8(n.client_id),4&u&&(5<=t&&r.props(s.props),r.utf8(s.topic),r.bin(s.payload)),128&u&&r.utf8(i),64&u&&r.bin(o),r.as_pkt(16)}}function x(t){return t.publish=(t,e)=>{const n=(3&e.qos)<<1,r=new g;return r.utf8(e.topic),0!==n&&r.u16(e.pkt_id),5<=t?(r.props(e.props),r.flush(e.payload)):r.flush(e.payload),r.as_pkt(48|n|(e.dup?8:0)|(e.retain?1:0))}}function S(t){return t.puback=(t,e)=>{const n=new g;return n.u16(e.pkt_id),5<=t&&(n.u8_reason(e.reason),n.props(e.props)),n.as_pkt(64)}}function N(t){const e=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{const r=new g;r.u16(n.pkt_id),5<=t&&r.props(n.props);const s=e(n);for(const t of n.topics)if("string"==typeof t)r.utf8(t),r.u8(s);else{let[n,i]=v(t)?t:[t.topic,t.opts];r.utf8(n),void 0===i?r.u8(s):r.u8_flags(i,e)}return r.as_pkt(130)}}function P(t){return t.unsubscribe=(t,e)=>{const n=new g;n.u16(e.pkt_id),5<=t&&n.props(e.props);for(const t of e.topics)n.utf8(t);return n.as_pkt(162)}}function A(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])}function I(t){return t.disconnect=(t,e)=>{const n=new g;return e&&5<=t&&(e.reason||e.props)&&(n.u8_reason(e.reason),n.props(e.props)),n.as_pkt(224)}}function T(t){return t.auth=(t,e)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");const n=new g;return n.u8_reason(e.reason),n.props(e.props),n.as_pkt(240)}}const U=["reserved","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"],j=t=>Object.defineProperties(t||{},{hdr:{get(){return 15&this.b0}},id:{get(){return this.b0>>>4}},type:{get(){return U[this.b0>>>4]}}});function M(t,e,r){return t=function(t){const e=[];for(const n of t)n(e);return t=>n(((n,r)=>{const s=e[n>>>4]||e[0];if(void 0!==s)return s({__proto__:t,b0:n},r)}))}(t),e=function(t){const e={};for(const n of t)n(e);return({mqtt_level:t})=>(n,r)=>e[n](t,r)}(e),r=j(r),n=>s=>[t(s=s||{__proto__:r,mqtt_level:n,get _base_(){return s}}),e(s),s]}function $(t){let{ctx:e}=$;if(void 0===e){let t=t=>new TextDecoder("utf-8").decode(t),n={utf8(e){return t(e||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};$.ctx=e=M([c,m,p,l,_,b,h,f,w],[q,I,x,S,A,N,P,T],n)}return e(t)}async function E(t,e){void 0!==e&&await e.call(t,await t)}function Q(){let t=[];return t.then=e=>{t.push(e)},t.notify=e=>{for(let n of t.splice(0,t.length))n(e)},t}function C(t,e,n){n.done=!0}function L(){let t=[[],[]],e=e=>function*(t,e){for(let n of t)for(let t of n){let n=O(e,t);void 0!==n&&(yield n)}}(t,e);return{find:e,add(e,...n){let r=n.pop(),s=n.pop();if("function"!=typeof r){if(!1!==r)throw new TypeError;r=C}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var n,r,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(n=s[0])?(o.push("wild"),u+="/(.*)"):":"===n?(r=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~r?r:~i?i:s.length)),u+=~r&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~r?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(e.replace(/[+#]$/,"*"));return i.key=e,i.tgt=r,t[s?0:1].push(i),this},remove(e,n){let r=t[n?0:1];r=r.filter((t=>t.key!==e)),t[n?0:1]=r},clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(t,n){n.idx=0;for(let[r,s]of e(t.topic)){if(await r(t,s,n),n.done)break;n.idx++}let{pkt_id:r,qos:s}=t;1===s&&await n.mqtt._send("puback",{pkt_id:r})}}}function O(t,{keys:e,pattern:n,tgt:r}){let s="/"!==t[0]?n.exec("/"+t):n.exec(t);if(null===s)return;if(!1===e){let{groups:t}=s;if(!t)return[r];let e={};for(let n in t)e[n]=t[n];return[r,e]}if(0===e.length)return[r];let i={};for(let t=0;t<e.length;t++)i[e[t]]=s[1+t];return[r,i]}const z={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:n}=this,r=t=>n[0].set(e,t);return n=>("string"==typeof n?e=n:(t=t+1&65535,e=n.pkt_id=t),new Promise(r))},answer(t,e){for(let n of this.hashbelt){let r=n.get(t);if(void 0!==r)return n.delete(t),r([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let n of e.splice(t||5))for(let t of n.values())t([,"expired"])},cmdids:(()=>{return[()=>{},n,e,n,t,t,t,t,n,t,n,t,e,e,n,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,r){t.answer(e.type,e),n(t,e,r)}async function n({target:t},e,n){let r=t[`mqtt_${e.type}`]||t.mqtt_pkt;void 0!==r&&await r.call(t,e,n)}})()};class R{constructor(t={}){this._conn_=function(t,[e,n]){let r,s=Q(),i=Q(),o=async(...t)=>(await i)(...t),u=t._send=o,a=()=>t._send("pingreq"),c=!1;return{is_live:()=>o!==u,is_set:()=>c,reset(){r=clearInterval(r),t._send=u=o,c=!1,E(t,t.on_reconnect)},ping(t){r=clearInterval(r),t&&(r=setInterval(a,1e3*t),r.unref&&r.unref())},async send_connect(...e){o===u&&(u=await s);let n=await u(...e);return t._send=u,i.notify(u),n},set(r,i){c=!0;let[o,a]=r;return u=async(t,e,r)=>{let s=void 0===r||n(r);return await i(a(t,e)),s},s.notify(u),E(t,t.on_live),n=>e(o(n),{mqtt:t})}}}(this,this._init_dispatch(t,this))}async connect(t={}){let{client_id:e}=t;e?Array.isArray(e)?t.client_id=e=this.init_client_id(e):this.client_id=e:t.client_id=e=this.init_client_id(["u8-mqtt--",""]),null==t.keep_alive&&(t.keep_alive=60);let n=await this._conn_.send_connect("connect",t,"connack");return this._conn_.ping(t.keep_alive),n}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}subscribe(t,e){return t=D(t,e),this._send("subscribe",t,t)}_sub_chain(t,e){return(this.subs||(this.subs=new Map)).set(t,this.subscribe([[t]],e)),this}unsubscribe(t,e){return t=D(t,e),this._send("unsubscribe",t,t)}get on_topic(){return this.router.add}subscribe_topic(t,...e){this.router.add(t,!0,e.pop());let n=this.topic_for(t);return this._sub_chain(n,e.pop())}unsubscribe_topic(t){this.router.remove(t,!0);let e=this.topic_for(t);return this.unsubscribe([[e]])}shared_subscribe(t,e,...n){this.router.add(e,!0,n.pop());let r=this.topic_for(e);return null!=t&&(r=`$share/${t}/${r}`),this._sub_chain(r,n.pop())}shared_unsubscribe(t,e){this.router.remove(e,!0);let n=this.topic_for(e);return null!=t&&(n=`$share/${t}/${n}`),this.unsubscribe([[n]])}topic_for(t){return t.replace(/[:*].*$/,"#")}publish(t,e){return B(this,t,e)}post(t,e,n){return B.m(this,t,e,n)}send(t,e,n){return B.mq(this,t,e,n)}store(t,e,n){return B.mqr(this,t,e,n)}json_post(t,e,n){return B.o(this,t,e,n)}json_send(t,e,n){return B.oq(this,t,e,n)}json_store(t,e,n){return B.oqr(this,t,e,n)}obj_post(t,e,n){return B.o(this,t,e,n)}obj_send(t,e,n){return B.oq(this,t,e,n)}obj_store(t,e,n){return B.oqr(this,t,e,n)}init_client_id(t){let e=this.client_id;return void 0===e&&(this.client_id=e=this.sess_client_id(t)),e}new_client_id(t){return[t[0],Math.random().toString(36).slice(2),t[1]].join("")}sess_client_id(t){let e=`client_id ${t.join("")}`,n=sessionStorage.getItem(e);return null==n&&(n=this.new_client_id(t),sessionStorage.setItem(e,n)),n}_init_router(t){return this.router=L()}_init_dispatch(t){let e=this._init_router(t,this),n={__proto__:t.on_mqtt_type||{},router:e};return n.mqtt_publish||(n.mqtt_publish=e.invoke),function(t,e){let n=z.create(e),{cmdids:r}=n,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)r[s.id](n,s,e);Date.now()>o&&(n.rotate_belt(i),o=s+Date.now())},n.bind_pkt_future()]}(this,n)}}{let t=R.prototype;Object.assign(t,{pub:t.publish,sub:t.subscribe,unsub:t.unsubscribe,sub_topic:t.subscribe_topic,unsub_topic:t.unsubscribe_topic,shared_sub:t.shared_subscribe,shared_unsub:t.shared_unsubscribe})}function D(t,e){return"string"==typeof t?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t}async function B(t,e,n){if(void 0===e.payload){"function"==typeof n&&(n={fn_encode:n});let{msg:r}=e;switch(typeof r){case"function":n={...n,fn_encode:r};case"undefined":return r=>B(t,{...e,[e.arg||"payload"]:r},n);default:let{fn_encode:s}=n||{};e.payload=s?await s(r):JSON.stringify(r)}}return n&&(n.props&&(e.props=n.props),n.xform&&(e=n.xform(e)||e)),t._send("publish",e,e.qos?e:void 0)}Object.assign(B,{m:(t,e,n,r)=>B(t,{topic:e,payload:n,qos:0},r),mq:(t,e,n,r)=>B(t,{topic:e,payload:n,qos:1},r),mqr:(t,e,n,r)=>B(t,{topic:e,payload:n,qos:1,retain:1},r),o:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:0},r),oq:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:1},r),oqr:(t,e,n,r)=>B(t,{topic:e,msg:n,arg:"msg",qos:1,retain:1},r)});class W extends R{static _with_session(t){this.prototype._mqtt_session=t}constructor(t={}){super(t),this.with_live(t.on_live),this.with_reconnect(t.on_reconnect)}with_live(t){return t&&(this.on_live=t),this}with_reconnect(t){return t&&(this.on_reconnect=t,this._conn_.is_set||t(this)),this}with_async_iter(t,e){let n=this._conn_.set(this._mqtt_session(),e);return this._msg_loop=(async()=>{t=await t;for await(let e of t)n(e);this._conn_.reset()})(),this}with_websock(t){null==t&&(t="ws://127.0.0.1:9001"),(t.origin||"string"==typeof t)&&(t=new WebSocket(new URL(t),["mqtt"])),t.binaryType="arraybuffer";let e,{readyState:n}=t;if(1!==n){if(0!==n)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.addEventListener("open",e,{once:!0})))}let{_conn_:r}=this,s=r.set(this._mqtt_session(),(async n=>(await e,t.send(n))));return t.addEventListener("close",(()=>{delete t.onmessage,r.reset()}),{once:!0}),t.onmessage=t=>s(new Uint8Array(t.data)),this}}class F extends W{_mqtt_session(){return $(4)()}}const G=t=>new F(t);export{F as MQTTClient,F as MQTTClient_v4,G as default,G as mqtt,G as mqtt_v4};
|
package/esm/web/v4.mjs
CHANGED
|
@@ -1180,6 +1180,10 @@ class MQTTBaseClient {
|
|
|
1180
1180
|
subscribe(pkt, ex) {
|
|
1181
1181
|
pkt = _as_topics(pkt, ex);
|
|
1182
1182
|
return this._send('subscribe', pkt, pkt)}
|
|
1183
|
+
_sub_chain(topic, ex) {
|
|
1184
|
+
let subs = this.subs ||(this.subs = new Map());
|
|
1185
|
+
subs.set(topic, this.subscribe([[ topic ]], ex));
|
|
1186
|
+
return this }// fluent api -- return this and track side effects
|
|
1183
1187
|
|
|
1184
1188
|
// alias: unsub
|
|
1185
1189
|
unsubscribe(pkt, ex) {
|
|
@@ -1190,15 +1194,30 @@ class MQTTBaseClient {
|
|
|
1190
1194
|
|
|
1191
1195
|
// alias: sub_topic
|
|
1192
1196
|
subscribe_topic(topic_route, ...args) {
|
|
1193
|
-
let topic = this.topic_for(topic_route);
|
|
1194
1197
|
this.router.add(topic_route, true, args.pop() );// handler
|
|
1195
|
-
|
|
1196
|
-
return this}
|
|
1198
|
+
let topic = this.topic_for(topic_route);
|
|
1199
|
+
return this._sub_chain(topic, args.pop() ) }// ex
|
|
1197
1200
|
|
|
1198
1201
|
// alias: unsub_topic
|
|
1199
1202
|
unsubscribe_topic(topic_route) {
|
|
1203
|
+
this.router.remove(topic_route, true);
|
|
1200
1204
|
let topic = this.topic_for(topic_route);
|
|
1205
|
+
return this.unsubscribe([[ topic ]]) }
|
|
1206
|
+
|
|
1207
|
+
// alias: shared_sub
|
|
1208
|
+
shared_subscribe(group, topic_route, ...args) {
|
|
1209
|
+
this.router.add(topic_route, true, args.pop() );// handler
|
|
1210
|
+
let topic = this.topic_for(topic_route);
|
|
1211
|
+
if (null != group) {
|
|
1212
|
+
topic = `$share/${group}/${topic}`;}
|
|
1213
|
+
return this._sub_chain(topic, args.pop() ) }// ex
|
|
1214
|
+
|
|
1215
|
+
// alias: shared_unsub
|
|
1216
|
+
shared_unsubscribe(group, topic_route) {
|
|
1201
1217
|
this.router.remove(topic_route, true);
|
|
1218
|
+
let topic = this.topic_for(topic_route);
|
|
1219
|
+
if (null != group) {
|
|
1220
|
+
topic = `$share/${group}/${topic}`;}
|
|
1202
1221
|
return this.unsubscribe([[ topic ]]) }
|
|
1203
1222
|
|
|
1204
1223
|
topic_for(topic_route) {
|
|
@@ -1206,18 +1225,18 @@ class MQTTBaseClient {
|
|
|
1206
1225
|
|
|
1207
1226
|
|
|
1208
1227
|
// alias: pub
|
|
1209
|
-
publish(pkt,
|
|
1210
|
-
post(topic, payload) {return _pub.m(this, topic, payload)}
|
|
1211
|
-
send(topic, payload) {return _pub.mq(this, topic, payload)}
|
|
1212
|
-
store(topic, payload) {return _pub.mqr(this, topic, payload)}
|
|
1228
|
+
publish(pkt, pub_opt) {return _pub(this, pkt, pub_opt)}
|
|
1229
|
+
post(topic, payload, pub_opt) {return _pub.m(this, topic, payload, pub_opt)}
|
|
1230
|
+
send(topic, payload, pub_opt) {return _pub.mq(this, topic, payload, pub_opt)}
|
|
1231
|
+
store(topic, payload, pub_opt) {return _pub.mqr(this, topic, payload, pub_opt)}
|
|
1213
1232
|
|
|
1214
|
-
json_post(topic, msg) {return _pub.o(this, topic, msg)}
|
|
1215
|
-
json_send(topic, msg) {return _pub.oq(this, topic, msg)}
|
|
1216
|
-
json_store(topic, msg) {return _pub.oqr(this, topic, msg)}
|
|
1233
|
+
json_post(topic, msg, pub_opt) {return _pub.o(this, topic, msg, pub_opt)}
|
|
1234
|
+
json_send(topic, msg, pub_opt) {return _pub.oq(this, topic, msg, pub_opt)}
|
|
1235
|
+
json_store(topic, msg, pub_opt) {return _pub.oqr(this, topic, msg, pub_opt)}
|
|
1217
1236
|
|
|
1218
|
-
obj_post(topic, msg,
|
|
1219
|
-
obj_send(topic, msg,
|
|
1220
|
-
obj_store(topic, msg,
|
|
1237
|
+
obj_post(topic, msg, pub_opt) {return _pub.o(this, topic, msg, pub_opt)}
|
|
1238
|
+
obj_send(topic, msg, pub_opt) {return _pub.oq(this, topic, msg, pub_opt)}
|
|
1239
|
+
obj_store(topic, msg, pub_opt) {return _pub.oqr(this, topic, msg, pub_opt)}
|
|
1221
1240
|
|
|
1222
1241
|
|
|
1223
1242
|
|
|
@@ -1276,7 +1295,9 @@ class MQTTBaseClient {
|
|
|
1276
1295
|
, sub: p.subscribe
|
|
1277
1296
|
, unsub: p.unsubscribe
|
|
1278
1297
|
, sub_topic: p.subscribe_topic
|
|
1279
|
-
, unsub_topic: p.unsubscribe_topic
|
|
1298
|
+
, unsub_topic: p.unsubscribe_topic
|
|
1299
|
+
, shared_sub: p.shared_subscribe
|
|
1300
|
+
, shared_unsub: p.shared_unsubscribe} );
|
|
1280
1301
|
|
|
1281
1302
|
/*
|
|
1282
1303
|
p.on_mqtt_type = {
|
|
@@ -1303,41 +1324,51 @@ function _as_topics(pkt, ex) {
|
|
|
1303
1324
|
return ex ? {...pkt, ...ex} : pkt}
|
|
1304
1325
|
|
|
1305
1326
|
|
|
1306
|
-
async function _pub(self, pkt,
|
|
1327
|
+
async function _pub(self, pkt, pub_opt) {
|
|
1307
1328
|
if (undefined === pkt.payload) {
|
|
1329
|
+
if ('function' === typeof pub_opt) {
|
|
1330
|
+
pub_opt = {fn_encode: pub_opt};}
|
|
1331
|
+
|
|
1308
1332
|
let {msg} = pkt;
|
|
1309
1333
|
switch (typeof msg) {
|
|
1310
1334
|
case 'function':
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1335
|
+
pub_opt = {...pub_opt, fn_encode: msg};
|
|
1336
|
+
// flow into 'undefined' case
|
|
1314
1337
|
case 'undefined':
|
|
1315
|
-
|
|
1316
|
-
return v => _pub(self, {...pkt, [arg]: v},
|
|
1338
|
+
// return a single-value closure to publish packets
|
|
1339
|
+
return v => _pub(self, {...pkt, [pkt.arg || 'payload']: v}, pub_opt)
|
|
1317
1340
|
|
|
1318
1341
|
default:
|
|
1342
|
+
// Encode payload from msg; fn_encode allows alternative to JSON.stringify
|
|
1343
|
+
let {fn_encode} = pub_opt || {};
|
|
1319
1344
|
pkt.payload = fn_encode
|
|
1320
1345
|
? await fn_encode(msg)
|
|
1321
1346
|
: JSON.stringify(msg);} }
|
|
1322
1347
|
|
|
1348
|
+
if (pub_opt) {
|
|
1349
|
+
if (pub_opt.props) {
|
|
1350
|
+
pkt.props = pub_opt.props;}
|
|
1351
|
+
if (pub_opt.xform) {
|
|
1352
|
+
pkt = pub_opt.xform(pkt) || pkt;} }
|
|
1353
|
+
|
|
1323
1354
|
return self._send('publish', pkt,
|
|
1324
1355
|
pkt.qos ? pkt : void 0 ) }// key
|
|
1325
1356
|
|
|
1326
1357
|
{
|
|
1327
1358
|
Object.assign(_pub,{
|
|
1328
|
-
m: (self, topic, payload) =>
|
|
1329
|
-
_pub(self, {topic, payload, qos:0})
|
|
1330
|
-
, mq: (self, topic, payload) =>
|
|
1331
|
-
_pub(self, {topic, payload, qos:1})
|
|
1332
|
-
, mqr: (self, topic, payload) =>
|
|
1333
|
-
_pub(self, {topic, payload, qos:1, retain: 1})
|
|
1334
|
-
|
|
1335
|
-
, o: (self, topic, msg,
|
|
1336
|
-
_pub(self, {topic, msg, arg: 'msg', qos:0},
|
|
1337
|
-
, oq: (self, topic, msg,
|
|
1338
|
-
_pub(self, {topic, msg, arg: 'msg', qos:1},
|
|
1339
|
-
, oqr: (self, topic, msg,
|
|
1340
|
-
_pub(self, {topic, msg, arg: 'msg', qos:1, retain: 1},
|
|
1359
|
+
m: (self, topic, payload, pub_opt) =>
|
|
1360
|
+
_pub(self, {topic, payload, qos:0}, pub_opt)
|
|
1361
|
+
, mq: (self, topic, payload, pub_opt) =>
|
|
1362
|
+
_pub(self, {topic, payload, qos:1}, pub_opt)
|
|
1363
|
+
, mqr: (self, topic, payload, pub_opt) =>
|
|
1364
|
+
_pub(self, {topic, payload, qos:1, retain: 1}, pub_opt)
|
|
1365
|
+
|
|
1366
|
+
, o: (self, topic, msg, pub_opt) =>
|
|
1367
|
+
_pub(self, {topic, msg, arg: 'msg', qos:0}, pub_opt)
|
|
1368
|
+
, oq: (self, topic, msg, pub_opt) =>
|
|
1369
|
+
_pub(self, {topic, msg, arg: 'msg', qos:1}, pub_opt)
|
|
1370
|
+
, oqr: (self, topic, msg, pub_opt) =>
|
|
1371
|
+
_pub(self, {topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)} ); }
|
|
1341
1372
|
|
|
1342
1373
|
class MQTTCoreClient extends MQTTBaseClient {
|
|
1343
1374
|
static _with_session(mqtt_session) {
|