u8-mqtt 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/cjs/basic-v4.cjs +16 -11
  2. package/cjs/basic-v4.cjs.map +1 -1
  3. package/cjs/basic-v5.cjs +16 -11
  4. package/cjs/basic-v5.cjs.map +1 -1
  5. package/cjs/full-v4.cjs +39 -20
  6. package/cjs/full-v4.cjs.map +1 -1
  7. package/cjs/full-v5.cjs +39 -20
  8. package/cjs/full-v5.cjs.map +1 -1
  9. package/cjs/index.cjs +39 -20
  10. package/cjs/index.cjs.map +1 -1
  11. package/cjs/v4.cjs +39 -20
  12. package/cjs/v4.cjs.map +1 -1
  13. package/cjs/v5.cjs +39 -20
  14. package/cjs/v5.cjs.map +1 -1
  15. package/code/_conn.jsy +5 -4
  16. package/code/base.jsy +3 -2
  17. package/code/core.jsy +7 -4
  18. package/code/router_path.jsy +20 -10
  19. package/code/with_topic_router.jsy +3 -0
  20. package/esm/basic-v4.js +16 -11
  21. package/esm/basic-v4.js.map +1 -1
  22. package/esm/basic-v5.js +16 -11
  23. package/esm/basic-v5.js.map +1 -1
  24. package/esm/deno/basic-v4.js +16 -11
  25. package/esm/deno/basic-v4.js.map +1 -1
  26. package/esm/deno/basic-v5.js +16 -11
  27. package/esm/deno/basic-v5.js.map +1 -1
  28. package/esm/deno/full-v4.js +39 -20
  29. package/esm/deno/full-v4.js.map +1 -1
  30. package/esm/deno/full-v5.js +39 -20
  31. package/esm/deno/full-v5.js.map +1 -1
  32. package/esm/deno/index.js +39 -20
  33. package/esm/deno/index.js.map +1 -1
  34. package/esm/deno/v4.js +39 -20
  35. package/esm/deno/v4.js.map +1 -1
  36. package/esm/deno/v5.js +39 -20
  37. package/esm/deno/v5.js.map +1 -1
  38. package/esm/full-v4.js +39 -20
  39. package/esm/full-v4.js.map +1 -1
  40. package/esm/full-v5.js +39 -20
  41. package/esm/full-v5.js.map +1 -1
  42. package/esm/index.js +39 -20
  43. package/esm/index.js.map +1 -1
  44. package/esm/node/basic-v4.js +16 -11
  45. package/esm/node/basic-v4.js.map +1 -1
  46. package/esm/node/basic-v4.mjs +16 -11
  47. package/esm/node/basic-v4.mjs.map +1 -1
  48. package/esm/node/basic-v5.js +16 -11
  49. package/esm/node/basic-v5.js.map +1 -1
  50. package/esm/node/basic-v5.mjs +16 -11
  51. package/esm/node/basic-v5.mjs.map +1 -1
  52. package/esm/node/full-v4.js +39 -20
  53. package/esm/node/full-v4.js.map +1 -1
  54. package/esm/node/full-v4.mjs +39 -20
  55. package/esm/node/full-v4.mjs.map +1 -1
  56. package/esm/node/full-v5.js +39 -20
  57. package/esm/node/full-v5.js.map +1 -1
  58. package/esm/node/full-v5.mjs +39 -20
  59. package/esm/node/full-v5.mjs.map +1 -1
  60. package/esm/node/index.js +39 -20
  61. package/esm/node/index.js.map +1 -1
  62. package/esm/node/index.mjs +39 -20
  63. package/esm/node/index.mjs.map +1 -1
  64. package/esm/node/v4.js +39 -20
  65. package/esm/node/v4.js.map +1 -1
  66. package/esm/node/v4.mjs +39 -20
  67. package/esm/node/v4.mjs.map +1 -1
  68. package/esm/node/v5.js +39 -20
  69. package/esm/node/v5.js.map +1 -1
  70. package/esm/node/v5.mjs +39 -20
  71. package/esm/node/v5.mjs.map +1 -1
  72. package/esm/v4.js +39 -20
  73. package/esm/v4.js.map +1 -1
  74. package/esm/v5.js +39 -20
  75. package/esm/v5.js.map +1 -1
  76. package/esm/web/basic-v4.js +16 -11
  77. package/esm/web/basic-v4.js.map +1 -1
  78. package/esm/web/basic-v4.min.js +1 -1
  79. package/esm/web/basic-v4.min.js.br +0 -0
  80. package/esm/web/basic-v4.min.js.gz +0 -0
  81. package/esm/web/basic-v5.js +16 -11
  82. package/esm/web/basic-v5.js.map +1 -1
  83. package/esm/web/basic-v5.min.js +1 -1
  84. package/esm/web/basic-v5.min.js.br +0 -0
  85. package/esm/web/basic-v5.min.js.gz +0 -0
  86. package/esm/web/full-v4.js +39 -20
  87. package/esm/web/full-v4.js.map +1 -1
  88. package/esm/web/full-v4.min.js +1 -1
  89. package/esm/web/full-v4.min.js.br +0 -0
  90. package/esm/web/full-v4.min.js.gz +0 -0
  91. package/esm/web/full-v5.js +39 -20
  92. package/esm/web/full-v5.js.map +1 -1
  93. package/esm/web/full-v5.min.js +1 -1
  94. package/esm/web/full-v5.min.js.br +0 -0
  95. package/esm/web/full-v5.min.js.gz +0 -0
  96. package/esm/web/index.js +39 -20
  97. package/esm/web/index.js.map +1 -1
  98. package/esm/web/index.min.js +1 -1
  99. package/esm/web/index.min.js.br +0 -0
  100. package/esm/web/index.min.js.gz +0 -0
  101. package/esm/web/v4.js +39 -20
  102. package/esm/web/v4.js.map +1 -1
  103. package/esm/web/v4.min.js +1 -1
  104. package/esm/web/v4.min.js.br +0 -0
  105. package/esm/web/v4.min.js.gz +0 -0
  106. package/esm/web/v5.js +39 -20
  107. package/esm/web/v5.js.map +1 -1
  108. package/esm/web/v5.min.js +1 -1
  109. package/esm/web/v5.min.js.br +0 -0
  110. package/esm/web/v5.min.js.gz +0 -0
  111. package/package.json +16 -17
package/esm/web/v4.min.js CHANGED
@@ -1 +1 @@
1
- function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}class e extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}function r(t,e){for(let[t,r]of Object.entries(e))e[t]=new Map(r);return class extends t{_reason_for(t,r){return e[r]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const n=r(class{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let r=(t,e)=>(e=0|r.k,r.k=e+t,e);return{__proto__:this,buf:t,step:r,...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:e}=this,[r,n,s]=function(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}(t,0|e.k);return e(n-s),r}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 r=this.buf[this.step(1)];if(null!=r)return new e(r,this._reason_for?.(r,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}},{connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]});const s={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.for(t,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.for(t,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.for(t,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]=t[11]=(t,r)=>{let n=e.for(t,r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.answers=[];for(;n.has_more();)s.push(n.reason(t.type));return t}},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.for(t,r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:n,encode_fns:[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>(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.for(s);i.push(r),i.u8(t);let{will:o,username:u,password:a}=s,p=i.flags(s.flags,n,(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&p&&(5<=t&&i.props(o.props),i.utf8(o.topic),i.bin(o.payload)),128&p&&i.utf8(u),64&p&&i.bin(a),i.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.for(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.for(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=>3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.for(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.for(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.for(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}}],mqtt_writer:class{static for(t){return(new this).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}}};const i=t=>"function"==typeof t,o=t=>"string"==typeof t;const u=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router,n=e.at(-1)?.call?e.pop():null;r.remove(t,!0,n);let s=r.mqtt_topic(t);return this.unsubscribe(s,...e)}on_topic(...t){return this.router.add(...t),this}})(l),a=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),p=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function c(t,e,r){r.done=!0}function l(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t.flat()){let t=r?.pattern.exec(e);if(t){let e=r.keys;if(e){let n,s=0,i={__proto__:h};for(n of e)i[n]=t[++s];yield[r.tgt,i,r]}else yield[r.tgt,t.groups??t,r]}}}(t,e);return{find:r,mqtt_topic:a,add(e,...r){let n=r.pop(),s=r.pop();if(!i(n)){if(n)throw new TypeError;n=c}let o=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(r),u+="?"===s[1]?"(?:/(.*))?":"/(.*)"):":"===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")}}(p(e));return o.topic=e,o.tgt=n,t[s?0:1].push(o),this},remove(e,...r){let n=t;return"boolean"==typeof r[0]&&(n=[t[r.shift()?0:1]]),"string"==typeof e&&(e={topic:e,tgt:r.pop()}),_(n,e)},clear(e){null==e?t=[[],[]]:t[e?0:1]=[]},async invoke(n,s){s.idx=0,s.rm=e;for(let[i,o,u]of r(n.topic)){let r=await i(n,o,s);if(e===r&&_(t,u),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}const h={get wild(){return this["*"]},set wild(t){return this["*"]=wild}};function _(t,e){for(let r of t){let t=0;for(let n of r){let s=n===e;s||n.topic!==e.topic||(s=null==e.tgt||n.tgt===e.tgt),s||(r[t++]=n)}r.length=t}return!1}function f(t,e=0,r){let n=0,s=e,i=t[s++],o=127&i;for(;128&i;)o|=(127&(i=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[o,s,e]}function d(t){let e=new Uint8Array(0),r=0;return n=>{e=0===e.byteLength?n:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,n);let s=[];for(;e.byteLength>=r;){let[n,i]=f(e,1,NaN),o=n+i;if(!(o<=e.byteLength)){r=o||0;break}let u=e[0],a=0===n?null:e.subarray(i,o);e=e.subarray(o);let p=t.decode_pkt(u,a,t);null!=p&&s.push(p)}return s}}const b=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];async function w(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function g(t,e,r,n){e(r.type,r),w(t,0,r,n)}function y(t,e,r){e(r.pkt_id,r)}const m=[t=>{},w,g,w,y,y,y,y,w,y,w,y,g,g,w,g];class k extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class q{async connect(t={}){let e=t.client_id;o(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._send0("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this.conn.on_conn(t,r)}async disconnect(t={}){let e=await this._send0("disconnect",t);return this.conn.on_dis(t,e)}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=v(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=v(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){i(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||i(r))return r&&(e={...e,fn_encode:r}),r=>this.pub({...t,[t.arg||"payload"]:r},e);t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:null)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r,n=[],s=0,{td:i=1e3,n:u=5}=t?.rotate||{},a=100,p=t=>n[0].set(r,t);return l([]),[l,function(t){return o(t)?r=t:(a=a+1&65535,r=t.pkt_id=a),new Promise(p)}];function c(t,e){for(let r of n){let n=r.get(t);if(n)return r.delete(t),n([e]),!0}return!1}function l(t,r){for(let n of t)m[n.id](e,c,n,r);let o=Date.now();if(o>s)for(s=i+o,n.unshift(new Map);n.length>u;)for(let t of n.pop().values())t([,"expired"])}}(t,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;var e,r,n=t.prototype;for(e of(n.MQTTError=k,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function v(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const x=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function j(t,e,r){let n={set:i},s=async(...t)=>(await n.p)(...t);return i();function i(){return s!==t[e]&&(x(n).p.then(r,(t=>0)),t[e]=s),n}}function T(t,e,[r,n]){let s,i=j(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),o=j(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(r,n)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||n[0].props?.server_keep_alive||r.keep_alive,e.conn_emit("on_conn"),t.use_auth?n:a.on_auth(null,n)),on_auth:(r,n)=>(o.a(i.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!r),n),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&i.e(t),s.e(t),delete a.is_set,a.ready=p(),e.conn_emit("on_disconnect",!1===t,t)},abort:()=>(o.e(err),a.reset(err)),async setup(t,s,o){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};o((e=>r(u.decode(e),t)),a)}s=await s,i.a((async(t,e,r)=>{let i=void 0===r||n(r);return await s(u.encode_pkt(t,e)),i}))}});return a.ready=p(),a;async function p(){s=x({}),u(0),i.set(),o.set();try{return e._send0=await Promise.race([i.p,s.p]),e._send=await Promise.race([o.p,s.p]),!0}catch(t){return!1}}}const $={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)}},E={sess_stg:globalThis.sessionStorage};const S="0.6.5-web",A=u(class extends q{constructor(t){t={...E,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=T(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))i(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=$){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r=e.pkt_ctx){let n,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return b[this.b0>>>4]},mqtt_level:t}),i=[],o={};for(n of e.encode_fns)n(o,e.mqtt_writer);for(n of e.decode_fns)n(i,e.mqtt_reader);return{pkt_api:r,pkt_ctx:s(r),encode_pkt:(e,r)=>o[e](t,r),decode_pkt(t,e){if(t.map)return d(this)(t)[0];let r=i[t>>>4]||i[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=d(e),e}}}(t,e,r),n}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}log_conn(t,e,r){console.info("[[u8-mqtt conn: %s]]",t,e,r)}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e){if(!e)return t.on_reconnect?.()}_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)}})}delay(t){return new Promise((e=>setTimeout(e,t)))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,r)=>{try{t=await t;for await(let r of t)e(r);r.reset()}catch(t){r.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,r=t.readyState;if(1!==r){if(0!==r)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,r)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}r.reset(e)}})),this}}.mqtt_ctx(4,s)),L=t=>new A(t);export{A as MQTTClient,A as MQTTClient_v4,L as default,L as mqtt,L as mqtt_v4,S as version};
1
+ function t(t,e=[]){for(e.push((t<128?0:128)|127&t);(t>>>=7)>0;)e.push((t<128?0:128)|127&t);return e}class e extends Number{constructor(t,e){super(t),this.reason=`:${(this.ok=t<128)?"ok":"fail"}:${e}`}}function r(t,e){for(let[t,r]of Object.entries(e))e[t]=new Map(r);return class extends t{_reason_for(t,r){return e[r]?.get(t)||e.all.get(t)}warn(t){let e=this.pkt;e.warn?e.warn(t,e):console.warn("[u8-mqtt-packet] "+t)}}}const n=r(class{static for(t,e){return(new this).of(e,{pkt:t})}of(t,e){let r=(t,e)=>(e=0|r.k,r.k=e+t,e);return{__proto__:this,buf:t,step:r,...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:e}=this,[r,n,s]=function(t,e=0,r){let n=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[i,s,e]}(t,0|e.k);return e(n-s),r}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 r=this.buf[this.step(1)];if(null!=r)return new e(r,this._reason_for?.(r,t))}flush(){let{buf:t,step:e}=this;return this.step=this.buf=null,t.subarray(0|e.k)}},{connack:[[1,"conn refused: unacceptable protocol version"],[2,"conn refused: identifier rejected"],[3,"conn refused: server unavailable"],[4,"conn refused: bad user name or password"],[5,"conn refused: not authorized"]],suback:[[0,"qos=0"],[1,"qos=1"],[2,"qos=2"]],unsuback:[[17,"no subscription existed"]],puback:[[16,"no matching subscribers"]],all:[[0,""],[128,"unspecified error"],[131,"implementation specific error"],[135,"not authorized"],[143,"topic filter invalid"],[145,"packet identifier in use"],[146,"packet identifier not found"]]});const s={decode_fns:[function(t,e){class r extends Number{get session_present(){return!0&this}}return t[2]=(t,n)=>{let s=e.for(t,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,o=e.for(t,r);return t.topic=o.utf8(),0!==s&&(t.pkt_id=o.u16()),5<=t.mqtt_level&&(t.props=o.props()),t.payload=o.flush(),t}},function(t,e){return t[4]=(t,r)=>{let n=e.for(t,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]=t[11]=(t,r)=>{let n=e.for(t,r);t.pkt_id=n.u16(),5<=t.mqtt_level&&(t.props=n.props());let s=t.answers=[];for(;n.has_more();)s.push(n.reason(t.type));return t}},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.for(t,r);t.reason=n.reason(t.type),t.props=n.props()}return t}}],mqtt_reader:n,encode_fns:[function(t,e){const r=new Uint8Array([0,4,77,81,84,84]),n=t=>(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 o=e.for(s);o.push(r),o.u8(t);let{will:i,username:u,password:a}=s,p=o.flags(s.flags,n,(u?128:0)|(a?64:0)|(i?(t=>4|(3&t.qos)<<3|(t.retain?32:0))(i):0));return o.u16(s.keep_alive),5<=t&&o.props(s.props),o.utf8(s.client_id),4&p&&(5<=t&&o.props(i.props),o.utf8(i.topic),o.bin(i.payload)),128&p&&o.utf8(u),64&p&&o.bin(a),o.as_pkt(16)}},function(t,e){return t.puback=(t,r)=>{let n=e.for(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.for(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=>3&t.qos|(t.retain?4:0)|(3&t.retain_handling)<<2;return t.subscribe=(t,n)=>{let s=e.for(n);s.u16(n.pkt_id),5<=t&&s.props(n.props);let o=r(n);for(let t of n.topics)if("string"==typeof t)s.utf8(t),s.u8(o);else{let[e,n]=Array.isArray(t)?t:[t.topic,t.opts];s.utf8(e),void 0===n?s.u8(o):s.flags(n,r)}return s.as_pkt(130)}},function(t,e){return t.unsubscribe=(t,r)=>{let n=e.for(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.for(r);return r&&5<=t&&(r.reason||r.props)&&(n.reason(r.reason),n.props(r.props)),n.as_pkt(224)}}],mqtt_writer:class{static for(t){return(new this).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,o=this.$;for(r of(this.$=!1,o))s+=r.length;n=(e=t(s,e)).length;let i=new Uint8Array(n+s);for(r of(i.set(e,0),o))i.set(r,n),n+=r.length;return i}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}}};const o=t=>"function"==typeof t,i=t=>"string"==typeof t;const u=(t=>e=>class extends e{static _aliases(){return super._aliases()+" sub_topic:subscribe_topic unsub_topic:unsubscribe_topic"}_init_router(e,r,n){this._subs=[];let s=this.router=n.router=t(e,this,n);return s?.invoke}on_sub(t,e){return t.pkt=e,this._subs.push(t),t}subs_settled(){return Promise.allSettled(this._subs.splice(0,1/0))}subscribe_topic(t,...e){let r=this.router;r.add(t,!0,e.pop());let n=r.mqtt_topic(t);return this.subscribe(n,...e),this}unsubscribe_topic(t,...e){let r=this.router,n=e.at(-1)?.call?e.pop():null;if(r.remove(t,!0,n),0!==r.count(t))return null;let s=r.mqtt_topic(t);return this.unsubscribe(s,...e)}on_topic(...t){return this.router.add(...t),this}})(l),a=t=>t.replace(/[*].*$/,"#").replace(/:\w[^\/]*/g,"+"),p=(t,e)=>(e=1,t.replace(/#$/,"*").replace(/\+/g,(()=>":$"+e++)));function c(t,e,r){r.done=!0}function l(){let t=[[],[]],e=Symbol(),r=e=>function*(t,e){e=e.replace(/^[\/]*/,"/");for(let r of t.flat()){let t=r?.pattern.exec(e);if(t){let e=r.keys;if(e){let n,s=0,o={__proto__:h};for(n of e)o[n]=t[++s];yield[r.tgt,o,r]}else yield[r.tgt,t.groups??t,r]}}}(t,e);return{find:r,mqtt_topic:a,add(e,...r){let n=r.pop(),s=r.pop();if(!o(n)){if(n)throw new TypeError;n=c}let i=function(t){if(t instanceof RegExp)return{keys:!1,pattern:t};var e,r,n,s,o=[],i="",u=t.split("/");for(u[0]||u.shift();n=u.shift();)"*"===(e=n[0])?(o.push(e),i+="?"===n[1]?"(?:/(.*))?":"/(.*)"):":"===e?(r=n.indexOf("?",1),s=n.indexOf(".",1),o.push(n.substring(1,~r?r:~s?s:n.length)),i+=~r&&!~s?"(?:/([^/]+?))?":"/([^/]+?)",~s&&(i+=(~r?"?":"")+"\\"+n.substring(s))):i+="/"+n;return{keys:o,pattern:new RegExp("^"+i+"/?$","i")}}(p(e));return i.topic=e,i.tgt=n,t[s?0:1].push(i),this},remove(e,...r){let n=t;return"boolean"==typeof r[0]&&(n=[t[r.shift()?0:1]]),"string"==typeof e&&(e={topic:e,tgt:r.pop()}),f(n,e)},count(e){if(!e)return t.reduce(((t,e)=>t+e.length),0);let r=0;for(let n of t)for(let t of n)e===t.topic&&r++;return r},clear(e){null==e?t=[[],[]]:t[e?0:1]=[]},async invoke(n,s){s.idx=0,s.rm=e;for(let[o,i,u]of r(n.topic)){let r=await o(n,i,s);if(e===r&&f(t,u),s.done)break;s.idx++}1===n.qos&&await s.mqtt.puback(n)}}}const h={get wild(){return this["*"]},set wild(t){return this["*"]=wild}};function f(t,e){let r=0;for(let n of t){let t=0;for(let s of n)s.topic!==e.topic||null!=e.tgt&&s.tgt!==e.tgt?n[t++]=s:r++;n.length=t}return r}function _(t,e=0,r){let n=0,s=e,o=t[s++],i=127&o;for(;128&o;)i|=(127&(o=t[s++]))<<(n+=7);return t.length<s?[r,e,e]:[i,s,e]}function d(t){let e=new Uint8Array(0),r=0;return n=>{e=0===e.byteLength?n:function(t,e){let r=t.byteLength,n=new Uint8Array(r+e.byteLength);return n.set(t,0),n.set(e,r),n}(e,n);let s=[];for(;e.byteLength>=r;){let[n,o]=_(e,1,NaN),i=n+o;if(!(i<=e.byteLength)){r=i||0;break}let u=e[0],a=0===n?null:e.subarray(o,i);e=e.subarray(i);let p=t.decode_pkt(u,a,t);null!=p&&s.push(p)}return s}}const b=["~","connect","connack","publish","puback","pubrec","pubrel","pubcomp","subscribe","suback","unsubscribe","unsuback","pingreq","pingresp","disconnect","auth"];async function w(t,e,r,n){let s=t[`mqtt_${r.type}`]||t.mqtt_pkt;await(s?.call(t,r,n))}function g(t,e,r,n){e(r.type,r),w(t,0,r,n)}function y(t,e,r){e(r.pkt_id,r)}const m=[t=>{},w,g,w,y,y,y,y,w,y,w,y,g,g,w,g];class k extends Error{constructor(t,e=t.reason){super(`[0x${e.toString(16)}] ${e.reason}`),this.mqtt_pkt=t,this.reason=e}}class q{async connect(t={}){let e=t.client_id;i(e)||(t.client_id=e=this.client_id||this.init_client_id(e)),this.client_id=e,null==t.keep_alive&&(t.keep_alive=60);let r=await this._send0("connect",t,"connack");if(0!=r[0].reason)throw new this.MQTTError(r[0]);return this.conn.on_conn(t,r)}async disconnect(t={}){let e=this._send0("disconnect",t);return await this.conn.on_dis(t,e),await e}async auth(t={}){let e=await this._send0("auth",t,"auth");if(e[0].reason)throw new this.MQTTError(e[0]);return this.conn.on_auth(t,e)}ping(){return this._send("pingreq",null,"pingresp")}puback({pkt_id:t}){return this._send("puback",{pkt_id:t})}subscribe(t,e,r){t=v(t,e,r);let n=this._send("subscribe",t,t);return this.on_sub?.(n,t)??n}unsubscribe(t,e,r){return t=v(t,e,r),this._send("unsubscribe",t,t)}post(t,e,r){return this.pub({topic:t,payload:e,qos:0},r)}send(t,e,r){return this.pub({topic:t,payload:e,qos:1},r)}store(t,e,r){return this.pub({topic:t,payload:e,qos:1,retain:1},r)}obj_post(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:0},r)}obj_send(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1},r)}obj_store(t,e,r){return this.pub({topic:t,msg:e,arg:"msg",qos:1,retain:1},r)}async pub(t,e){if(void 0===t.payload){o(e)&&(e={fn_encode:e});let r=t.msg,n=e?.fn_encode;if(null==r||o(r))return r&&(e={...e,fn_encode:r}),r=>this.pub({...t,[t.arg||"payload"]:r},e);t.payload=n?await n(r):JSON.stringify(r)}return e&&(e.props&&(t.props=e.props),e.xform&&(t=e.xform(t)||t)),this._send("publish",t,t.qos?t:null)}_init_dispatch(t){this.constructor?._once_();let e={__proto__:t.on_mqtt_type};return e.mqtt_publish||=this._init_router?.(t,this,e),function(t,e){let r,n=[],s=0,{td:o=1e3,n:u=5}=t?.rotate||{},a=100,p=t=>n[0].set(r,t);return l([]),[l,function(t){return i(t)?r=t:(a=a+1&65535,r=t.pkt_id=a),new Promise(p)}];function c(t,e){for(let r of n){let n=r.get(t);if(n)return r.delete(t),n([e]),!0}return!1}function l(t,r){for(let n of t)m[n.id](e,c,n,r);let i=Date.now();if(i>s)for(s=o+i,n.unshift(new Map);n.length>u;)for(let t of n.pop().values())t([,"expired"])}}(t,e)}static _aliases(){return" publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store"}static _once_(t=this){t._once_=t=>0;var e,r,n=t.prototype;for(e of(n.MQTTError=k,t._aliases().split(/\s+/)))[e,r]=e.split(":"),n[e]=n[r]}}function v(t,e,r){if(e?.trim&&(r=e,e=null),t=t.trim?{topics:[t],...e}:t[Symbol.iterator]?{topics:[...t],...e}:e?{...t,...e}:t,r){let e=t=>t.trim?r+t:t.map(e);t.topics=t.topics.map(e)}return t}const x=t=>(t.p=new Promise(((e,r)=>{t.a=e,t.e=r})),t);function j(t,e,r){let n={set:o},s=async(...t)=>(await n.p)(...t);return o();function o(){return s!==t[e]&&(x(n).p.then(r,(t=>0)),t[e]=s),n}}function T(t,e,[r,n]){let s,o=j(e,"_send0",(t=>e.conn_emit("on_live",a.has_connected))),i=j(e,"_send",(t=>e.conn_emit("on_ready"))),u=function(t){let e;return r=>{if(e=clearInterval(e),r)return e=setInterval(t,1e3*r),e.unref?.(),!0}}((()=>e._send0("pingreq"))),a=Object.create({ping:(t=a.keep_alive)=>u(t),on_conn:(r,n)=>(a.has_connected=!0,a.keep_alive=t.keep_alive||n[0].props?.server_keep_alive||r.keep_alive,e.conn_emit("on_conn"),t.use_auth?n:a.on_auth(null,n)),on_auth:(r,n)=>(i.a(o.p),0!=t.keep_alive&&a.ping(),e.conn_emit("on_auth",!r),n),on_dis:(t,e)=>(a.reset(!1),e),reset(t){t&&o.e(t),s.e(t),a.is_set&&(delete a.is_set,a.ready=p(),e.conn_emit("on_disconnect",!1===t,t))},abort:t=>(i.e(t),a.reset(t)),async setup(t,s,i){if(a.is_set)throw new Error;a.is_set=!0,await t;let u=e.mqtt_ctx.mqtt_stream();{let t={mqtt:e};i((e=>r(u.decode(e),t)),a)}s=await s,o.a((async(t,e,r)=>{let o=void 0===r||n(r);return await s(u.encode_pkt(t,e)),o}))}});return a.ready=p(),a;async function p(){s=x({}),u(0),o.set(),i.set();try{return e._send0=await Promise.race([o.p,s.p]),e._send=await Promise.race([i.p,s.p]),!0}catch(t){return!1}}}const E={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)}},$={sess_stg:globalThis.sessionStorage};const S="0.6.7-web",A=u(class extends q{constructor(t){t={...$,...t},super(),this.with(t),this.sess_stg=t.sess_stg,this.conn=T(t,this,this._init_dispatch(t))}with(t){for(let[e,r]of Object.entries(t))o(r)&&(this[e]=r);return this}static mqtt_ctx(t,e,r=E){let n=class extends(this){};return n.prototype.mqtt_ctx=function(t,e,r=e.pkt_ctx){let n,s=e=>({__proto__:e,get hdr(){return 15&this.b0},get id(){return this.b0>>>4},get type(){return b[this.b0>>>4]},mqtt_level:t}),o=[],i={};for(n of e.encode_fns)n(i,e.mqtt_writer);for(n of e.decode_fns)n(o,e.mqtt_reader);return{pkt_api:r,pkt_ctx:s(r),encode_pkt:(e,r)=>i[e](t,r),decode_pkt(t,e){if(t.map)return d(this)(t)[0];let r=o[t>>>4]||o[0];return r?.({__proto__:this.pkt_ctx,b0:t},e)},mqtt_stream(t=this.pkt_api){let e={__proto__:this,pkt_ctx:s(t)};return e.decode=d(e),e}}}(t,e,r),n}async conn_emit(t,e,r){this.log_conn?.(t,e,r);try{let n=this[await t];if(n)await n.call(this,this,e,r);else if(r)throw r}catch(e){this.on_error(e,t)}}on_error(t,e){console.warn("[[u8-mqtt error: %s]]",e,t)}log_conn(t,e,r){console.info("[[u8-mqtt conn: %s]]",t,e,r)}init_client_id(t=["u8-mqtt--",""]){let e,r=this.sess_stg,n=r?.getItem(e=t.join(" "));return n||(n=t.join(Math.random().toString(36).slice(2)),r?.setItem(e,n)),n}on_live(t,e){if(e)return t.connect()}on_disconnect(t,e,r){if(!e)return t.on_reconnect?.()}_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,t.jitter).then(this.reconnect).then(t.reconnect,t.error)}})}delay(t,e=.2*t){return new Promise((r=>setTimeout(r,0|t+e*Math.random())))}with_async_iter(t,e){return this.conn.setup(t,e,(async(e,r)=>{try{t=await t;for await(let r of t)e(r);r.reset()}catch(t){r.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,r=t.readyState;if(1!==r){if(0!==r)throw new Error("WS readyState");e=new Promise((e=>t.onopen=e))}return this.conn.setup(e,(e=>t.send(e)),((e,r)=>{t.onmessage=t=>e(new Uint8Array(t.data)),t.onerror=t=>{r.reset(new Error("websocket error"))},t.onclose=t=>{if(!t.wasClean){var e=new Error("websocket close");e.code=t.code,e.reason=t.reason}r.reset(e)}})),this}}.mqtt_ctx(4,s)),L=t=>new A(t);export{A as MQTTClient,A as MQTTClient_v4,L as default,L as mqtt,L as mqtt_v4,S as version};
Binary file
Binary file
package/esm/web/v5.js CHANGED
@@ -693,7 +693,7 @@ function parse(input, loose) {
693
693
 
694
694
  return {
695
695
  keys: keys,
696
- pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
696
+ pattern: new RegExp('^' + pattern + ('\/?$'), 'i')
697
697
  };
698
698
  }
699
699
 
@@ -719,6 +719,7 @@ class AbstractTopicRouter ::
719
719
  async invoke(pkt, ctx) ::
720
720
  add(topic_route, ...args) ::
721
721
  remove(topic_route, priority) ::
722
+ count(topic_route) ::
722
723
  clear(priority) ::
723
724
  find(topic) :: // optional
724
725
  mqtt_topic(topic_route)
@@ -758,6 +759,8 @@ const with_topic_router = mqtt_topic_router =>
758
759
 
759
760
  let fn = args.at(-1)?.call ? args.pop() : null;
760
761
  router.remove(topic_route, true, fn);
762
+ if (0 !== router.count(topic_route) ) {
763
+ return null}
761
764
 
762
765
  let topic = router.mqtt_topic(topic_route);
763
766
  return this.unsubscribe(topic, ...args ) }// topic_prefix
@@ -826,6 +829,17 @@ function mqtt_topic_path_router() {
826
829
  query ={topic: query, tgt: args.pop()}; }
827
830
  return _route_remove(lst, query)}
828
831
 
832
+ , count(topic_route) {
833
+ if (! topic_route) {
834
+ return pri_lsts.reduce((r,l) => r+l.length, 0)}
835
+
836
+ let count = 0;
837
+ for (let lst of pri_lsts) {
838
+ for (let route of lst) {
839
+ if (topic_route === route.topic) {
840
+ count++;} } }
841
+ return count}
842
+
829
843
  , clear(priority) {
830
844
  if (null == priority) {
831
845
  pri_lsts = [[],[]]; }// null clears both lists
@@ -869,21 +883,21 @@ function * _routes_iter(all_route_lists, topic) {
869
883
 
870
884
 
871
885
  function _route_remove(all_route_lists, query) {
872
- let ans = false;
886
+ let n_removed = 0;
873
887
  for (let lst of all_route_lists) {
874
888
  let idx_tip = 0;
875
889
  for (let route of lst) {
876
- // skip matching routes to remove from compacted list
877
- let skip = route === query;
878
- if (!skip && route.topic === query.topic)
879
- skip = (null == query.tgt) || (route.tgt === query.tgt);
890
+ if (route.topic === query.topic) {
891
+ if (null == query.tgt || route.tgt === query.tgt) {
892
+ // skip matching routes to remove from compacted list
893
+ n_removed++;
894
+ continue} }
880
895
 
881
- if (!skip) lst[idx_tip++] = route;}
896
+ lst[idx_tip++] = route;}
882
897
 
883
898
  // truncate remaining list
884
899
  lst.length = idx_tip;}
885
-
886
- return ans}
900
+ return n_removed}
887
901
 
888
902
  function decode_varint(u8, i0=0, invalid) {
889
903
  let shift=0, i=i0, b=u8[i++], n=(b & 0x7f);
@@ -1093,8 +1107,9 @@ class MQTTBase {
1093
1107
  return this.conn.on_conn(pkt, response)}
1094
1108
 
1095
1109
  async disconnect(pkt={}) {
1096
- let response = await this._send0('disconnect', pkt);
1097
- return this.conn.on_dis(pkt, response)}
1110
+ let response = this._send0('disconnect', pkt);
1111
+ await this.conn.on_dis(pkt, response);
1112
+ return await response}
1098
1113
 
1099
1114
  async auth(pkt={}) {
1100
1115
  let response = await this._send0('auth', pkt, 'auth');
@@ -1259,11 +1274,12 @@ function _mqtt_conn(opt, client, [on_mqtt, pkt_future]) {
1259
1274
  _dfn_send0.e(err); }// send error to uses of _send0 (connect, auth)
1260
1275
  _abort.e(err); // abort in-progress connections
1261
1276
 
1262
- delete conn.is_set;
1263
- conn.ready = handshake();
1264
- client.conn_emit('on_disconnect', false===err, err);}
1277
+ if (conn.is_set) {
1278
+ delete conn.is_set;
1279
+ conn.ready = handshake();
1280
+ client.conn_emit('on_disconnect', false===err, err);} }
1265
1281
 
1266
- , abort() {
1282
+ , abort(err) {
1267
1283
  _dfn_ready.e(err); // abort all messages awaiting ready state
1268
1284
  return conn.reset(err)}
1269
1285
 
@@ -1377,7 +1393,7 @@ class MQTTCore extends MQTTBase {
1377
1393
 
1378
1394
  // on_ready(client) ::
1379
1395
  // on_reconnect(client) ::
1380
- on_disconnect(client, intentional) {
1396
+ on_disconnect(client, intentional, err) {
1381
1397
  if (! intentional) {
1382
1398
  return client.on_reconnect?.()} }
1383
1399
 
@@ -1387,12 +1403,12 @@ class MQTTCore extends MQTTBase {
1387
1403
  if (opt.toFixed) {opt ={delay: opt};}
1388
1404
  return this.with({
1389
1405
  on_reconnect() {
1390
- this.delay(opt.delay || 2000)
1406
+ this.delay(opt.delay || 2000, opt.jitter)
1391
1407
  .then(this.reconnect)
1392
1408
  .then(opt.reconnect, opt.error);} }) }
1393
1409
 
1394
- delay(ms) {
1395
- return new Promise(done => setTimeout(done, ms)) }
1410
+ delay(ms, ms_jitter=0.2*ms) {
1411
+ return new Promise(done => setTimeout(done, 0 | (ms + ms_jitter*Math.random()))) }
1396
1412
 
1397
1413
  with_async_iter(async_iter, write_u8_pkt) {
1398
1414
  this.conn.setup(async_iter,
@@ -1488,6 +1504,9 @@ class MQTTCore extends MQTTBase {
1488
1504
  websock.onmessage = evt =>(
1489
1505
  on_mqtt_chunk(new Uint8Array(evt.data)) );
1490
1506
 
1507
+ websock.onerror = evt => {
1508
+ conn.reset(new Error('websocket error'));};
1509
+
1491
1510
  websock.onclose = evt => {
1492
1511
  if (! evt.wasClean) {
1493
1512
  var err = new Error('websocket close');
@@ -1498,7 +1517,7 @@ class MQTTCore extends MQTTBase {
1498
1517
 
1499
1518
  return this} }
1500
1519
 
1501
- const version = '0.6.5-web';
1520
+ const version = '0.6.7-web';
1502
1521
 
1503
1522
  const MQTTClient_v4 = /* #__PURE__ */
1504
1523
  with_topic_path_router(