u8-mqtt 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/cjs/basic-v4.cjs +5 -10
- package/cjs/basic-v4.cjs.map +1 -1
- package/cjs/basic-v5.cjs +5 -10
- package/cjs/basic-v5.cjs.map +1 -1
- package/cjs/index.cjs +22 -20
- package/cjs/index.cjs.map +1 -1
- package/cjs/v4.cjs +22 -20
- package/cjs/v4.cjs.map +1 -1
- package/cjs/v5.cjs +22 -20
- package/cjs/v5.cjs.map +1 -1
- package/code/base.jsy +4 -9
- package/code/router_path.jsy +15 -9
- package/code/with_topic_router.jsy +4 -3
- package/esm/deno/basic-v4.js +5 -10
- package/esm/deno/basic-v4.js.map +1 -1
- package/esm/deno/basic-v5.js +5 -10
- package/esm/deno/basic-v5.js.map +1 -1
- package/esm/deno/index.js +22 -20
- package/esm/deno/index.js.map +1 -1
- package/esm/deno/v4.js +22 -20
- package/esm/deno/v4.js.map +1 -1
- package/esm/deno/v5.js +22 -20
- package/esm/deno/v5.js.map +1 -1
- package/esm/node/basic-v4.js +5 -10
- package/esm/node/basic-v4.js.map +1 -1
- package/esm/node/basic-v4.mjs +5 -10
- package/esm/node/basic-v4.mjs.map +1 -1
- package/esm/node/basic-v5.js +5 -10
- package/esm/node/basic-v5.js.map +1 -1
- package/esm/node/basic-v5.mjs +5 -10
- package/esm/node/basic-v5.mjs.map +1 -1
- package/esm/node/index.js +22 -20
- package/esm/node/index.js.map +1 -1
- package/esm/node/index.mjs +22 -20
- package/esm/node/index.mjs.map +1 -1
- package/esm/node/v4.js +22 -20
- package/esm/node/v4.js.map +1 -1
- package/esm/node/v4.mjs +22 -20
- package/esm/node/v4.mjs.map +1 -1
- package/esm/node/v5.js +22 -20
- package/esm/node/v5.js.map +1 -1
- package/esm/node/v5.mjs +22 -20
- package/esm/node/v5.mjs.map +1 -1
- package/esm/web/basic-v4.js +5 -10
- package/esm/web/basic-v4.js.map +1 -1
- package/esm/web/basic-v4.min.js +1 -1
- package/esm/web/basic-v4.min.js.br +0 -0
- package/esm/web/basic-v4.min.js.gz +0 -0
- package/esm/web/basic-v5.js +5 -10
- package/esm/web/basic-v5.js.map +1 -1
- package/esm/web/basic-v5.min.js +1 -1
- package/esm/web/basic-v5.min.js.br +0 -0
- package/esm/web/basic-v5.min.js.gz +0 -0
- package/esm/web/index.js +22 -20
- package/esm/web/index.js.map +1 -1
- package/esm/web/index.min.js +1 -1
- package/esm/web/index.min.js.br +0 -0
- package/esm/web/index.min.js.gz +0 -0
- package/esm/web/v4.js +22 -20
- package/esm/web/v4.js.map +1 -1
- package/esm/web/v4.min.js +1 -1
- package/esm/web/v4.min.js.br +0 -0
- package/esm/web/v4.min.js.gz +0 -0
- package/esm/web/v5.js +22 -20
- package/esm/web/v5.js.map +1 -1
- package/esm/web/v5.min.js +1 -1
- package/esm/web/v5.min.js.br +0 -0
- package/esm/web/v5.min.js.gz +0 -0
- package/package.json +1 -1
package/esm/web/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[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_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}class o extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}}function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[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"])}(t),t.reasons("connack",[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"])}function p(t){t.reasons("puback",[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"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[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"])}function f(t){t.reasons("unsuback",[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"])}function d(t){t.reasons("disconnect",[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"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=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,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e){return t(e,this)}get on_topic(){return this.router.add}_sub_chain(t,e,r){let n=this.subscribe([[t]],e,r),s=this.subs||(this.subs=new Map);return s.set(n.topic=t,s.last=n),this}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this._sub_chain(n,...e)}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe([[n]],...e)}},w=y(q),g=t=>t.replace(/[*].*$/,"#").replace(/:\w+\??/g,"+"),k=t=>t.replace(/#$/,"*").split(/([^\/]*[+][^\/]*)/).reduce(((t,e,r)=>t+(1&r?":$"+(1+r>>1):e)));function v(t,e,r){r.done=!0}function q(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){for(let r of t)for(let t of r){let r=x(e,t);void 0!==r&&(yield r)}}(t,e);return{find:r,mqtt_topic:g,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(!1!==n)throw new TypeError;n=v}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(k(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>S([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&S(t,i),s.done)break;s.idx++}let{pkt_id:i,qos:o}=n;1===o&&await s.mqtt._send("puback",{pkt_id:i})}}}function x(t,{keys:e,pattern:r,tgt:n}){let s="/"!==t[0]?r.exec("/"+t):r.exec(t);if(null===s)return;if(!1===e){let{groups:t}=s;if(!t)return[n];let e={};for(let r in t)e[r]=t[r];return[n,e]}if(0===e.length)return[n];let i={};for(let t=0;t<e.length;t++)i[e[t]]=s[1+t];return[n,i]}function S(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return!!e.splice(t,1)}return!1}function A(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function T(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=A(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const P=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function j(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const N=j();function U(t,[e,r]){let n,s,i=N(),o=N(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:I((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=N(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=N(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}function I(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const M={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};function E(t,e){let r=M.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}class Q extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class ${constructor(t={}){this._conn_=U(this,this._init_dispatch(t,this))}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];n?await n.call(this,this,e,r):r&&await this.on_error(r,t)}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||["u8-mqtt--",""];Array.isArray(e)&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}subscribe(t,e,r){return t=L(t,e,r),this._send("subscribe",t,t)}unsubscribe(t,e,r){return t=L(t,e,r),this._send("unsubscribe",t,t)}publish(t,e){return O(this,t,e)}post(t,e,r){return O.m(this,t,e,r)}send(t,e,r){return O.mq(this,t,e,r)}store(t,e,r){return O.mqr(this,t,e,r)}json_post(t,e,r){return O.o(this,t,e,r)}json_send(t,e,r){return O.oq(this,t,e,r)}json_store(t,e,r){return O.oqr(this,t,e,r)}obj_post(t,e,r){return O.o(this,t,e,r)}obj_send(t,e,r){return O.oq(this,t,e,r)}obj_store(t,e,r){return O.oqr(this,t,e,r)}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=t.join(" "),r=sessionStorage.getItem(e);return null==r&&(r=this.new_client_id(t),sessionStorage.setItem(e,r)),r}_init_dispatch(t){this.constructor?._once_();let e=this.router=this._init_router?.(t,this),r={__proto__:t.on_mqtt_type||{},router:e};return r.mqtt_publish||=e?.invoke,E(this,r)}static _aliases(){return" pub:publish sub:subscribe unsub:unsubscribe "}static _once_(t=this){t._once_=t=>0,t.MQTTError=Q;let e=t.prototype;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}const C=(t,e)=>Array.from(e,(e=>e.trim?C(t,e):t+e));function L(t,e,r){return e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r&&(t.topics=C(r,t.topics)),t}async function O(t,e,r){if(void 0===e.payload){"function"==typeof r&&(r={fn_encode:r});let{msg:n}=e;switch(typeof n){case"function":r={...r,fn_encode:n};case"undefined":return n=>O(t,{...e,[e.arg||"payload"]:n},r);default:let{fn_encode:s}=r||{};e.payload=s?await s(n):JSON.stringify(n)}}return r&&(r.props&&(e.props=r.props),r.xform&&(e=r.xform(e)||e)),t._send("publish",e,e.qos?e:void 0)}Object.assign(O,{m:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:0},n),mq:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:1},n),mqr:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:1,retain:1},n),o:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:0},n),oq:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:1},n),oqr:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:1,retain:1},n)});const z={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class R extends ${constructor(t={}){super(t),this.with(t)}static mqtt_ctx(t,e,r=z){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return P[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=T(t),t}}}(t,e,r),n}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const D="0.4.0",B=w(R.mqtt_ctx(4,m)),W=w(R.mqtt_ctx(5,m)),F=t=>new B(t),G=t=>new W(t);export{$ as MQTTBase,B as MQTTClient_v4,W as MQTTClient_v5,R as MQTTCore,Q as MQTTError,M as _mqtt_cmdid_dispatch,U as _mqtt_conn,E as _mqtt_dispatch,N as ao_defer_v,k as as_topic_path,F as default,F as mqtt_v4,G as mqtt_v5,D as version,w as with_topic_path_router,y as with_topic_router};
|
|
1
|
+
function t(t,e=[]){do{const r=127&t;t>>>=7,e.push(r|(0===t?0:128))}while(t>0);return e}function e(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}const r=n();function n(){let t=new Map,e=[[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_qos"],[37,"u8","retain_available"],[38,"pair","user_properties",{op:"kv_obj"}],[39,"u32","maximum_packet_size"],[40,"u8","wildcard_subscription_available"],[41,"u8","subscription_identifiers_available",{op:"u8_vec"}],[42,"u8","shared_subscription_available"]];for(let[r,n,s,i]of e){let e={id:r,type:n,name:s,...i};t.set(e.id,e),t.set(e.name,e)}return t}class s extends Number{static of(t,e,r){let n=new this(t);return n.reason=r?.[e]?.get(t)||e,n}}class i{static of(t){return this.prototype.of(t)}of(t){let e=(t,r)=>(r=0|e.k,e.k=r+t,r);return{__proto__:this,buf:t,step:e}}has_more(){return this.buf.byteLength>(0|this.step.k)}u8(){return this.buf[this.step(1)]}u16(){let{buf:t,step:e}=this,r=e(2);return t[r]<<8|t[r+1]}u32(){let{buf:t,step:e}=this,r=e(4);return t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3]}vint(){let{buf:t,step:r}=this,[n,s,i]=e(t,0|r.k);return r(s-i),n}bin(){let{buf:t,step:e}=this,r=e(2),n=t[r]<<8|t[r+1];return r=e(n),t.subarray(r,r+n)}utf8(){return new TextDecoder("utf-8").decode(this.bin())}pair(){return[this.utf8(),this.utf8()]}flags(t){return new t(this.buf[this.step(1)])}reason(t){let e=this.buf[this.step(1)];if(null!=e)return s.of(e,t,this._reasons_by)}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}}class o extends i{props(){let{buf:t,step:n}=this,[s,i,o]=e(t,0|n.k);if(n(s+i-o),0===s)return null;let u={},a=this.of(t.subarray(i,0|n.k));for(;a.has_more();){let t=r.get(a.u8()),e=a[t.type]();u[t.name]=t.op?a[t.op](u[t.name],e):e}return u}kv_obj(t=Object.create(null),[e,r]){return t[e]=r,t}u8_vec(t=[],e){return t.push(e),t}}function u(t,...e){t=class extends t{static reasons(t,...e){let r=this.prototype;r._reasons_by={...r._reasons_by};let n=r._reasons_by[t]||=new Map;for(let[t,r]of e)n.set(t,r);return this}};for(let r of e)r(t);return t}class a{static of(){return this.prototype.of()}of(){return{__proto__:this,$:[]}}static init(){return this}as_pkt(t){return this.pack([t])}push(...t){this.$.push(...t)}pack(e){let r,n,s=0,i=this.$;for(r of(this.$=!1,i))s+=r.length;n=(e=t(s,e)).length;let o=new Uint8Array(n+s);for(r of(o.set(e,0),i))o.set(r,n),n+=r.length;return o}u8(t){this.push([255&t])}u16(t){this.push([t>>>8&255,255&t])}u32(t){this.push([t>>>24&255,t>>>16&255,t>>>8&255,255&t])}vint(e){this.push(t(e))}bin(t){return t?"string"==typeof t?this.utf8(t):(t.length!==t.byteLength&&(t=new Uint8Array(t)),this.u16(t.byteLength),void this.push(t)):this.u16(0)}utf8(t){let e=new TextEncoder("utf-8").encode(t);this.u16(e.byteLength),this.push(e)}pair(t,e){this.utf8(t),this.utf8(e)}flags(t,e,r=0){return void 0!==t&&isNaN(+t)&&(t=e(t,0)),t|=r,this.push([t]),t}reason(t){this.push([0|t])}flush(t){null!=t&&this.push("string"==typeof t?new TextEncoder("utf-8").encode(t):t),this.push=!1}}function c(t){!function(t){t.reasons("connack",[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"])}(t),t.reasons("connack",[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"])}function p(t){t.reasons("puback",[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"])}function l(t){return(e,r)=>{let n=t.of(r);e.pkt_id=n.u16(),5<=e.mqtt_level&&(e.props=n.props());let s=e.answers=[];for(;n.has_more();)s.push(n.reason(e.type));return e}}function _(t){!function(t){t.reasons("suback",[0,"Granted QoS 0"],[1,"Granted QoS 1"],[2,"Granted QoS 2"])}(t),t.reasons("suback",[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"])}function f(t){t.reasons("unsuback",[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"])}function d(t){t.reasons("disconnect",[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"])}function h(t){t.reasons("auth",[0,"Success"],[24,"Continue authentication"],[25,"Re-authenticate"])}const b=[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=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,s)=>{let i=e.of(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,c=i.flags(s.flags,n,0|(u?128:0)|(a?64:0)|(o?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(o):0));return i.u16(s.keep_alive),5<=t&&i.props(s.props),i.utf8(s.client_id),4&c&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&c&&i.utf8(u),64&c&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.of(r);return n.u16(r.pkt_id),5<=t&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(64)}},function(t,e){return t.publish=(t,r)=>{let n=(3&r.qos)<<1,s=e.of(r);return s.utf8(r.topic),0!==n&&s.u16(r.pkt_id),5<=t?(s.props(r.props),s.flush(r.payload)):s.flush(r.payload),s.as_pkt(48|n|(r.dup?8:0)|(r.retain?1:0))}},function(t,e){const r=t=>0|3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.of(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let i=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(i);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(i):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.of(r);n.u16(r.pkt_id),5<=t&&n.props(r.props);for(let t of r.topics)n.utf8(t);return n.as_pkt(162)}},function(t){t.pingreq=()=>new Uint8Array([192,0]),t.pingresp=()=>new Uint8Array([208,0])},function(t,e){return t.disconnect=(t,r)=>{let n=e.of(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}},function(t,e){return t.auth=(t,r)=>{if(5>t)throw new Error("Auth packets are only available after MQTT 5.x");let n=e.of(r);return n.reason(r.reason),n.props(r.props),n.as_pkt(240)}}],m={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.of(n);return t.flags=s.flags(r),t.reason=s.reason(t.type),5<=t.mqtt_level&&(t.props=s.props()),t}},function(t,e){return t[3]=(t,r)=>{let{hdr:n}=t;t.dup=Boolean(8&n),t.retain=Boolean(1&n);let s=t.qos=n>>1&3,i=e.of(r);return t.topic=i.utf8(),0!==s&&(t.pkt_id=i.u16()),5<=t.mqtt_level&&(t.props=i.props()),t.payload=i.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.of(r);return t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.reason=n.reason(t.type),t.props=n.props()),t}},function(t,e){return t[9]=l(e)},function(t,e){return t[11]=l(e)},function(t){return t[12]=t[13]=t=>t},function(t,e){return t[14]=(t,r)=>{if(r&&5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}},function(t,e){return t[15]=(t,r)=>{if(5<=t.mqtt_level){let n=e.of(r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:u(o,c,p,_,f,d,h),encode_fns:b,mqtt_writer:class extends a{props(t){if(!t)return this.u8(0);if(Array.isArray(t)||(t=t.entries?Array.from(t.entries()):Object.entries(t)),0===t.length)return this.u8(0);let e=this.of();for(let[n,s]of t){let t=r.get(n);e[t.op||"one"](s,t)}this.push(e.pack())}one(t,e){this.u8(e.id),this[e.type](t)}kv_obj(t,e){for(let r of Object.entries(t))this.u8(e.id),this.pair(r)}u8_vec(t,e){for(let r of t)this.u8(e.id),this.u8(r)}}};const y=t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){let s=this.router=n.router=t(e,this);return s?.invoke}get on_topic(){return this.router.add}_sub_chain(t,e,r){let n=this.subscribe([[t]],e,r),s=this.subs||(this.subs=new Map);return s.set(n.topic=t,s.last=n),this}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this._sub_chain(n,...e)}unsubscribe_topic(t,...e){let r=this.router;r.remove(t,!0);let n=r.mqtt_topic(t);return this.unsubscribe([[n]],...e)}},w=y(q),g=t=>t.replace(/[*].*$/,"#").replace(/:\w+\??/g,"+"),k=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function v(t,e,r){r.done=!0}function q(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){for(let r of t)for(let t of r){let r=x(e,t);void 0!==r&&(yield r)}}(t,e);return{find:r,mqtt_topic:g,add(e,...r){let n=r.pop(),s=r.pop();if("function"!=typeof n){if(!1!==n)throw new TypeError;n=v}let i=function(t,e){if(t instanceof RegExp)return{keys:!1,pattern:t};var r,n,s,i,o=[],u="",a=t.split("/");for(a[0]||a.shift();s=a.shift();)"*"===(r=s[0])?(o.push("wild"),u+="/(.*)"):":"===r?(n=s.indexOf("?",1),i=s.indexOf(".",1),o.push(s.substring(1,~n?n:~i?i:s.length)),u+=~n&&!~i?"(?:/([^/]+?))?":"/([^/]+?)",~i&&(u+=(~n?"?":"")+"\\"+s.substring(i))):u+="/"+s;return{keys:o,pattern:new RegExp("^"+u+(e?"(?=$|/)":"/?$"),"i")}}(k(e));return i.key=e,i.tgt=n,t[s?0:1].push(i),this},remove:(e,r)=>S([t[r?0:1]],e),clear(e){t[e?0:1]=[],null==e&&(t[1]=[])},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o]of r(n.topic)){let r=await i(n,o,s);if(e===r&&S(t,i),s.done)break;s.idx++}let{pkt_id:i,qos:o}=n;1===o&&await s.mqtt._send("puback",{pkt_id:i})}}}function x(t,{keys:e,pattern:r,tgt:n}){let s="/"!==t[0]?r.exec("/"+t):r.exec(t);if(null===s)return;if(!1===e){let{groups:t}=s;if(!t)return[n];let e={};for(let r in t)e[r]=t[r];return[n,e]}if(0===e.length)return[n];let i={};for(let t=0;t<e.length;t++)i[e[t]]=s[1+t];return[n,i]}function S(t,e){let r=t=>t===e||t.tgt===e||t.key===e;for(let e of t){let t=e.findIndex(r);if(0<=t)return!!e.splice(t,1)}return!1}function A(t,e=0){let r=e,n=(127&t[e])<<0;return 128&t[e++]&&(n|=(127&t[e])<<7,128&t[e++]&&(n|=(127&t[e])<<14,128&t[e++]&&(n|=(127&t[e])<<21))),[n,e,r]}function T(t){let e=new Uint8Array(0);return r=>{e=0===e.byteLength?r:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,r);let n=[];for(;;){let[r,s]=A(e,1),i=r+s;if(e.byteLength<i)return n;let o=e[0],u=0===r?null:e.subarray(s,i);e=e.subarray(i);let a=t.decode_pkt(o,u,t);null!=a&&n.push(a)}}}const P=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];function j(t=((...t)=>t)){let e,r,n=(t,n)=>{e=t,r=n};return s=>(s=new Promise(n),t(s,e,r))}const N=j();function U(t,[e,r]){let n,s,i=N(),o=N(),u=async(...t)=>(await o[0])(...t);return t._send=u,{async when_ready(){await o[0]},ping:I((()=>n?.("pingreq"))),reset(e){n&&(e&&i[2](e),n=null,i=N(),t._send=u,t.conn_emit("on_disconnect",!1===e,e))},async send_connect(...e){n||await i[0];let r=await n(...e);return 0==r[0].reason&&(s=!0,o[1](t._send=n),o=N(),t.conn_emit("on_ready")),r},is_set:()=>!!n,set(o,u){if(n)throw new Error("Already connected");o=o.mqtt_stream();let a={mqtt:t};return n=async(t,e,n)=>{let s=void 0===n||r(n);return await u(o.encode_pkt(t,e)),s},i[1](n),t.conn_emit("on_live",s),t=>e(o.decode(t),a)}}}function I(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}Promise.resolve({type:"init"});const M={create(t){return{__proto__:this,target:t,hashbelt:[new Map]}},bind_pkt_future(t=100){let e,{hashbelt:r}=this,n=t=>r[0].set(e,t);return r=>("string"==typeof r?e=r:(t=t+1&65535,e=r.pkt_id=t),new Promise(n))},answer(t,e){for(let r of this.hashbelt){let n=r.get(t);if(void 0!==n)return r.delete(t),n([e]),!0}return!1},rotate_belt(t){let{hashbelt:e}=this;e.unshift(new Map);for(let r of e.splice(t||5))for(let t of r.values())t([,"expired"])},cmdids:(()=>{return[()=>{},r,e,r,t,t,t,t,r,t,r,t,e,e,r,e];function t(t,e){t.answer(e.pkt_id,e)}function e(t,e,n){t.answer(e.type,e),r(t,e,n)}async function r({target:t},e,r){let n=t[`mqtt_${e.type}`]||t.mqtt_pkt;await(n?.call(t,e,r))}})()};function E(t,e){let r=M.create(e),{cmdids:n}=r,{td:s=1e3,n:i=5}=t&&t.rotate||{},o=s+Date.now();return[function(t,e){for(let s of t)n[s.id](r,s,e);Date.now()>o&&(r.rotate_belt(i),o=s+Date.now())},r.bind_pkt_future()]}class Q extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class ${constructor(t={}){this._conn_=U(this,this._init_dispatch(t,this))}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];n?await n.call(this,this,e,r):r&&await this.on_error(r,t)}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}async connect(t={}){let e=t.client_id||["u8-mqtt--",""];Array.isArray(e)&&(t.client_id=e=this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._conn_.send_connect("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this._conn_.ping(t.keep_alive),r}async disconnect(t={}){let e=await this._send("disconnect",t);return this._conn_.reset(!1),e}auth(t={}){return this._send("auth",t,"auth")}ping(){return this._send("pingreq",null,"pingresp")}subscribe(t,e,r){return t=L(t,e,r),this._send("subscribe",t,t)}unsubscribe(t,e,r){return t=L(t,e,r),this._send("unsubscribe",t,t)}publish(t,e){return O(this,t,e)}post(t,e,r){return O.m(this,t,e,r)}send(t,e,r){return O.mq(this,t,e,r)}store(t,e,r){return O.mqr(this,t,e,r)}json_post(t,e,r){return O.o(this,t,e,r)}json_send(t,e,r){return O.oq(this,t,e,r)}json_store(t,e,r){return O.oqr(this,t,e,r)}obj_post(t,e,r){return O.o(this,t,e,r)}obj_send(t,e,r){return O.oq(this,t,e,r)}obj_store(t,e,r){return O.oqr(this,t,e,r)}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=t.join(" "),r=sessionStorage.getItem(e);return null==r&&(r=this.new_client_id(t),sessionStorage.setItem(e,r)),r}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),E(this,e)}static _aliases(){return" pub:publish sub:subscribe unsub:unsubscribe "}static _once_(t=this){t._once_=t=>0,t.MQTTError=Q;let e=t.prototype;for(let r of t._aliases().split(/\s+/)){r=r.split(":");let t=r[1]&&e[r[1]];t&&(e[r[0]]=t)}}}const C=(t,e)=>Array.from(e,(e=>e.trim?C(t,e):t+e));function L(t,e,r){return e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r&&(t.topics=C(r,t.topics)),t}async function O(t,e,r){if(void 0===e.payload){"function"==typeof r&&(r={fn_encode:r});let{msg:n}=e;switch(typeof n){case"function":r={...r,fn_encode:n};case"undefined":return n=>O(t,{...e,[e.arg||"payload"]:n},r);default:let{fn_encode:s}=r||{};e.payload=s?await s(n):JSON.stringify(n)}}return r&&(r.props&&(e.props=r.props),r.xform&&(e=r.xform(e)||e)),t._send("publish",e,e.qos?e:void 0)}Object.assign(O,{m:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:0},n),mq:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:1},n),mqr:(t,e,r,n)=>O(t,{topic:e,payload:r,qos:1,retain:1},n),o:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:0},n),oq:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:1},n),oqr:(t,e,r,n)=>O(t,{topic:e,msg:r,arg:"msg",qos:1,retain:1},n)});const z={utf8(t){return new TextDecoder("utf-8").decode(t||this.payload)},json(t){return JSON.parse(this.utf8(t)||null)},text(t){return this.utf8(t)}};class R extends ${constructor(t={}){super(t),this.with(t)}static mqtt_ctx(t,e,r=z){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r){r={__proto__:r||e.pkt_ctx,mqtt_level:t,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return P[this.b0>>>4]}};let n,s=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(s,e.mqtt_reader);return{pkt_ctx:r,encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){let r=s[t>>>4]||s[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(){let t={__proto__:this,pkt_ctx:{__proto__:r}};return t.pkt_ctx._base_=t.pkt_ctx,t.decode=T(t),t}}}(t,e,r),n}with(t){for(let[e,r]of Object.entries(t))"function"==typeof r&&(this[e]=r);return this}on_live(t,e){if(e)return t.connect()}_use_conn(t){return(this.reconnect=t)?.()}with_autoreconnect(t=2e3){return t.toFixed&&(t={delay:t}),this.with({on_reconnect(){this.delay(t.delay||2e3).then(this.reconnect).then(t.reconnect,t.error)}})}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){let r=this._conn_.set(this.mqtt_ctx,e);return this._msg_loop=(async()=>{try{t=await t;for await(let e of t)r(e);this._conn_.reset()}catch(t){this._conn_.reset(t)}})(),this}with_stream(t,e){return void 0===e&&(e=t),this.with_async_iter(t,(t=>e.write(t)))}with_websock(t){if(!t?.send)return t=new URL(t||"ws://127.0.0.1:9001"),this._use_conn((()=>this.with_websock(new WebSocket(t,["mqtt"]))));t.binaryType="arraybuffer";let e,{readyState:r}=t;if(1!==r){if(0!==r)throw new Error("Invalid WebSocket readyState");e=new Promise((e=>t.onopen=e))}let{_conn_:n}=this,s=n.set(this.mqtt_ctx,(async r=>(await e,t.send(r))));return t.onmessage=t=>s(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket connection close");e.code=t.code,e.reason=t.reason}n.reset(e)},this}}const D="0.4.1",B=w(R.mqtt_ctx(4,m)),W=w(R.mqtt_ctx(5,m)),F=t=>new B(t),G=t=>new W(t);export{$ as MQTTBase,B as MQTTClient_v4,W as MQTTClient_v5,R as MQTTCore,Q as MQTTError,M as _mqtt_cmdid_dispatch,U as _mqtt_conn,E as _mqtt_dispatch,N as ao_defer_v,k as as_topic_path,F as default,F as mqtt_v4,G as mqtt_v5,D as version,w as with_topic_path_router,y as with_topic_router};
|
package/esm/web/index.min.js.br
CHANGED
|
Binary file
|
package/esm/web/index.min.js.gz
CHANGED
|
Binary file
|
package/esm/web/v4.js
CHANGED
|
@@ -556,9 +556,10 @@ const with_topic_router = mqtt_topic_router =>
|
|
|
556
556
|
return super._aliases() +
|
|
557
557
|
' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
|
|
558
558
|
|
|
559
|
-
_init_router(opt) {
|
|
560
|
-
|
|
561
|
-
|
|
559
|
+
_init_router(opt, client, target) {
|
|
560
|
+
let router = this.router = target.router =
|
|
561
|
+
mqtt_topic_router(opt, this);
|
|
562
|
+
return router?.invoke}
|
|
562
563
|
get on_topic() {return this.router.add}
|
|
563
564
|
|
|
564
565
|
_sub_chain(topic, ex, topic_prefix) {
|
|
@@ -594,14 +595,20 @@ const mqtt_topic = topic_route =>
|
|
|
594
595
|
.replace(/[*].*$/, '#')
|
|
595
596
|
.replace(/:\w+\??/g, '+');
|
|
596
597
|
|
|
597
|
-
|
|
598
|
+
/* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
|
|
599
|
+
4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
|
|
600
|
+
... MUST be specified either on its own or following a topic level separator.
|
|
601
|
+
In either case it MUST be the last character specified in the Topic Filter
|
|
602
|
+
|
|
603
|
+
4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
|
|
604
|
+
...it MUST occupy an entire level of the filter.
|
|
605
|
+
*/
|
|
606
|
+
|
|
607
|
+
const as_topic_path = (topic_route, id) =>(
|
|
608
|
+
id=1,
|
|
598
609
|
topic_route
|
|
599
|
-
.replace(/#$/, '*')
|
|
600
|
-
.
|
|
601
|
-
.reduce (( sz, v, idx ) => sz +(
|
|
602
|
-
idx & 1 // even entires are body, odd are MQTT + tokens
|
|
603
|
-
? `:$${1 + idx>>1}` // replace with `:$#` sequential ids, using ? for partial entries
|
|
604
|
-
: v ) ) );// pass through body
|
|
610
|
+
.replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
|
|
611
|
+
.replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
|
|
605
612
|
|
|
606
613
|
function _ignore(pkt, params, ctx) {ctx.done = true;}
|
|
607
614
|
|
|
@@ -1095,15 +1102,10 @@ class MQTTBase {
|
|
|
1095
1102
|
|
|
1096
1103
|
_init_dispatch(opt) {
|
|
1097
1104
|
this.constructor?._once_();
|
|
1098
|
-
let
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
__proto__: opt.on_mqtt_type || {}
|
|
1103
|
-
, router};
|
|
1104
|
-
|
|
1105
|
-
tgt.mqtt_publish ||= router?.invoke;
|
|
1106
|
-
return _mqtt_dispatch(this, tgt)}
|
|
1105
|
+
let target ={__proto__: opt.on_mqtt_type};
|
|
1106
|
+
target.mqtt_publish ||=
|
|
1107
|
+
this._init_router?.(opt, this, target);
|
|
1108
|
+
return _mqtt_dispatch(this, target)}
|
|
1107
1109
|
|
|
1108
1110
|
static _aliases() {
|
|
1109
1111
|
return ' pub:publish sub:subscribe unsub:unsubscribe '}
|
|
@@ -1366,7 +1368,7 @@ class MQTTCore extends MQTTBase {
|
|
|
1366
1368
|
|
|
1367
1369
|
return this} }
|
|
1368
1370
|
|
|
1369
|
-
const version = '0.4.
|
|
1371
|
+
const version = '0.4.1';
|
|
1370
1372
|
|
|
1371
1373
|
const MQTTClient_v4 = /* #__PURE__ */
|
|
1372
1374
|
with_topic_path_router(
|