u8-mqtt 0.5.2 → 0.6.0

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 (116) hide show
  1. package/README.md +23 -6
  2. package/cjs/basic-v4.cjs +293 -284
  3. package/cjs/basic-v4.cjs.map +1 -1
  4. package/cjs/basic-v5.cjs +307 -288
  5. package/cjs/basic-v5.cjs.map +1 -1
  6. package/cjs/full-v4.cjs +1538 -0
  7. package/cjs/full-v4.cjs.map +1 -0
  8. package/cjs/full-v5.cjs +1812 -0
  9. package/cjs/full-v5.cjs.map +1 -0
  10. package/cjs/index.cjs +320 -302
  11. package/cjs/index.cjs.map +1 -1
  12. package/cjs/v4.cjs +305 -296
  13. package/cjs/v4.cjs.map +1 -1
  14. package/cjs/v5.cjs +319 -300
  15. package/cjs/v5.cjs.map +1 -1
  16. package/code/_cmdid_dispatch.jsy +45 -69
  17. package/code/_conn.jsy +96 -72
  18. package/code/_dispatch.jsy +36 -28
  19. package/code/_utils.jsy +17 -0
  20. package/code/base.jsy +35 -63
  21. package/code/core.jsy +78 -56
  22. package/code/full-v4.js +20 -0
  23. package/code/full-v5.js +29 -0
  24. package/code/router_path.jsy +2 -1
  25. package/esm/basic-v4.js +293 -284
  26. package/esm/basic-v4.js.map +1 -1
  27. package/esm/basic-v5.js +307 -288
  28. package/esm/basic-v5.js.map +1 -1
  29. package/esm/deno/basic-v4.js +297 -288
  30. package/esm/deno/basic-v4.js.map +1 -1
  31. package/esm/deno/basic-v5.js +311 -292
  32. package/esm/deno/basic-v5.js.map +1 -1
  33. package/esm/deno/full-v4.js +1526 -0
  34. package/esm/deno/full-v4.js.map +1 -0
  35. package/esm/deno/full-v5.js +1798 -0
  36. package/esm/deno/full-v5.js.map +1 -0
  37. package/esm/deno/index.js +324 -305
  38. package/esm/deno/index.js.map +1 -1
  39. package/esm/deno/v4.js +309 -300
  40. package/esm/deno/v4.js.map +1 -1
  41. package/esm/deno/v5.js +323 -304
  42. package/esm/deno/v5.js.map +1 -1
  43. package/esm/full-v4.js +1526 -0
  44. package/esm/full-v4.js.map +1 -0
  45. package/esm/full-v5.js +1798 -0
  46. package/esm/full-v5.js.map +1 -0
  47. package/esm/index.js +320 -301
  48. package/esm/index.js.map +1 -1
  49. package/esm/node/basic-v4.js +293 -284
  50. package/esm/node/basic-v4.js.map +1 -1
  51. package/esm/node/basic-v4.mjs +293 -284
  52. package/esm/node/basic-v4.mjs.map +1 -1
  53. package/esm/node/basic-v5.js +307 -288
  54. package/esm/node/basic-v5.js.map +1 -1
  55. package/esm/node/basic-v5.mjs +307 -288
  56. package/esm/node/basic-v5.mjs.map +1 -1
  57. package/esm/node/full-v4.js +1529 -0
  58. package/esm/node/full-v4.js.map +1 -0
  59. package/esm/node/full-v4.mjs +1529 -0
  60. package/esm/node/full-v4.mjs.map +1 -0
  61. package/esm/node/full-v5.js +1801 -0
  62. package/esm/node/full-v5.js.map +1 -0
  63. package/esm/node/full-v5.mjs +1801 -0
  64. package/esm/node/full-v5.mjs.map +1 -0
  65. package/esm/node/index.js +320 -301
  66. package/esm/node/index.js.map +1 -1
  67. package/esm/node/index.mjs +320 -301
  68. package/esm/node/index.mjs.map +1 -1
  69. package/esm/node/v4.js +305 -296
  70. package/esm/node/v4.js.map +1 -1
  71. package/esm/node/v4.mjs +305 -296
  72. package/esm/node/v4.mjs.map +1 -1
  73. package/esm/node/v5.js +319 -300
  74. package/esm/node/v5.js.map +1 -1
  75. package/esm/node/v5.mjs +319 -300
  76. package/esm/node/v5.mjs.map +1 -1
  77. package/esm/v4.js +305 -296
  78. package/esm/v4.js.map +1 -1
  79. package/esm/v5.js +319 -300
  80. package/esm/v5.js.map +1 -1
  81. package/esm/web/basic-v4.js +293 -284
  82. package/esm/web/basic-v4.js.map +1 -1
  83. package/esm/web/basic-v4.min.js +1 -1
  84. package/esm/web/basic-v4.min.js.br +0 -0
  85. package/esm/web/basic-v4.min.js.gz +0 -0
  86. package/esm/web/basic-v5.js +307 -288
  87. package/esm/web/basic-v5.js.map +1 -1
  88. package/esm/web/basic-v5.min.js +1 -1
  89. package/esm/web/basic-v5.min.js.br +0 -0
  90. package/esm/web/basic-v5.min.js.gz +0 -0
  91. package/esm/web/full-v4.js +1526 -0
  92. package/esm/web/full-v4.js.map +1 -0
  93. package/esm/web/full-v4.min.js +1 -0
  94. package/esm/web/full-v4.min.js.br +0 -0
  95. package/esm/web/full-v4.min.js.gz +0 -0
  96. package/esm/web/full-v5.js +1798 -0
  97. package/esm/web/full-v5.js.map +1 -0
  98. package/esm/web/full-v5.min.js +1 -0
  99. package/esm/web/full-v5.min.js.br +0 -0
  100. package/esm/web/full-v5.min.js.gz +0 -0
  101. package/esm/web/index.js +320 -301
  102. package/esm/web/index.js.map +1 -1
  103. package/esm/web/index.min.js +1 -1
  104. package/esm/web/index.min.js.br +0 -0
  105. package/esm/web/index.min.js.gz +0 -0
  106. package/esm/web/v4.js +305 -296
  107. package/esm/web/v4.js.map +1 -1
  108. package/esm/web/v4.min.js +1 -1
  109. package/esm/web/v4.min.js.br +0 -0
  110. package/esm/web/v4.min.js.gz +0 -0
  111. package/esm/web/v5.js +319 -300
  112. package/esm/web/v5.js.map +1 -1
  113. package/esm/web/v5.min.js +1 -1
  114. package/esm/web/v5.min.js.br +0 -0
  115. package/esm/web/v5.min.js.gz +0 -0
  116. package/package.json +7 -8
@@ -0,0 +1,1801 @@
1
+ import { connect } from 'node:net';
2
+ import { connect as connect$1 } from 'node:tls';
3
+
4
+ function encode_varint(n, a=[]) {
5
+ do {
6
+ const ni = n & 0x7f;
7
+ n >>>= 7;
8
+ a.push( ni | (0===n ? 0 : 0x80) );
9
+ } while (n > 0)
10
+ return a
11
+ }
12
+
13
+
14
+ /*
15
+ export function decode_varint_loop(u8, i=0) {
16
+ let i0 = i
17
+ let shift = 0, n = (u8[i] & 0x7f)
18
+ while ( 0x80 & u8[i++] )
19
+ n |= (u8[i] & 0x7f) << (shift += 7)
20
+
21
+ return [n, i, i0]
22
+ }
23
+ */
24
+
25
+
26
+ function decode_varint$1(u8, i=0) {
27
+ let i0 = i;
28
+ // unrolled for a max of 4 chains
29
+ let n = (u8[i] & 0x7f) << 0;
30
+ if ( 0x80 & u8[i++] ) {
31
+ n |= (u8[i] & 0x7f) << 7;
32
+ if ( 0x80 & u8[i++] ) {
33
+ n |= (u8[i] & 0x7f) << 14;
34
+ if ( 0x80 & u8[i++] ) {
35
+ n |= (u8[i] & 0x7f) << 21;
36
+ }
37
+ }
38
+ }
39
+ return [n, i, i0]
40
+ }
41
+
42
+ const mqtt_props = /* #__PURE__ */
43
+ init_mqtt_props();
44
+
45
+ function init_mqtt_props() {
46
+ let mqtt_props = new Map();
47
+
48
+ let entries = [
49
+ [ 0x01, 'u8', 'payload_format_indicator'],
50
+ [ 0x02, 'u32', 'message_expiry_interval'],
51
+ [ 0x03, 'utf8', 'content_type'],
52
+ [ 0x08, 'utf8', 'response_topic'],
53
+ [ 0x09, 'bin', 'correlation_data'],
54
+ [ 0x0B, 'vint', 'subscription_identifier'],
55
+ [ 0x11, 'u32', 'session_expiry_interval'],
56
+ [ 0x12, 'utf8', 'assigned_client_identifier'],
57
+ [ 0x13, 'u16', 'server_keep_alive'],
58
+ [ 0x15, 'utf8', 'authentication_method'],
59
+ [ 0x16, 'bin', 'authentication_data'],
60
+ [ 0x17, 'u8', 'request_problem_information'],
61
+ [ 0x18, 'u32', 'will_delay_interval'],
62
+ [ 0x19, 'u8', 'request_response_information'],
63
+ [ 0x1A, 'utf8', 'response_information'],
64
+ [ 0x1C, 'utf8', 'server_reference'],
65
+ [ 0x1F, 'utf8', 'reason_string'],
66
+ [ 0x21, 'u16', 'receive_maximum'],
67
+ [ 0x22, 'u16', 'topic_alias_maximum'],
68
+ [ 0x23, 'u16', 'topic_alias'],
69
+ [ 0x24, 'u8', 'maximum_qos'],
70
+ [ 0x25, 'u8', 'retain_available'],
71
+ [ 0x26, 'pair', 'user_properties', {op: 'kv_obj'}],
72
+ [ 0x27, 'u32', 'maximum_packet_size'],
73
+ [ 0x28, 'u8', 'wildcard_subscription_available'],
74
+ [ 0x29, 'u8', 'subscription_identifiers_available', {op: 'u8_vec'}],
75
+ [ 0x2A, 'u8', 'shared_subscription_available'],
76
+ ];
77
+
78
+ for (let [id, type, name, extra] of entries) {
79
+ let prop_obj = {id, type, name, ...extra};
80
+ mqtt_props.set(prop_obj.id, prop_obj);
81
+ mqtt_props.set(prop_obj.name, prop_obj);
82
+ }
83
+
84
+ return mqtt_props
85
+ }
86
+
87
+ class U8_Reason extends Number {
88
+ static of(v, pkt_kind, by_kind) {
89
+ let self = new this(v);
90
+ self.reason = by_kind?.[pkt_kind]?.get(v) || pkt_kind;
91
+ return self
92
+ }
93
+ }
94
+
95
+ class mqtt_reader_v4 {
96
+ static of(buf) { return this.prototype.of(buf) }
97
+ of(buf) {
98
+ let step = (width, k) => (k=0|step.k, step.k=k+width, k);
99
+ return {__proto__: this, buf, step}
100
+ }
101
+
102
+ has_more() {
103
+ return this.buf.byteLength > (this.step.k|0)
104
+ }
105
+
106
+ u8() {
107
+ return this.buf[this.step(1)]
108
+ }
109
+
110
+ u16() {
111
+ let {buf, step} = this, i = step(2);
112
+ return (buf[i]<<8) | buf[i+1]
113
+ }
114
+
115
+ u32() {
116
+ let {buf, step} = this, i = step(4);
117
+ return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3]
118
+ }
119
+
120
+ vint() {
121
+ let {buf, step} = this;
122
+ let [n, vi, vi0] = decode_varint$1(buf, step.k|0);
123
+ step(vi - vi0);
124
+ return n
125
+ }
126
+
127
+ bin() {
128
+ let {buf, step} = this, i = step(2);
129
+ let len = (buf[i]<<8) | buf[i+1];
130
+ i = step(len);
131
+ return buf.subarray(i, i+len)
132
+ }
133
+
134
+ utf8() { return new TextDecoder('utf-8').decode(this.bin()) }
135
+ pair() { return [ this.utf8(), this.utf8() ] }
136
+
137
+ flags(FlagsType) { return new FlagsType(this.buf[this.step(1)]) }
138
+
139
+ reason(pkt_kind) {
140
+ let v = this.buf[this.step(1)];
141
+ if (null != v)
142
+ return U8_Reason.of(v, pkt_kind, this._reasons_by)
143
+ }
144
+
145
+ flush() {
146
+ let {buf, step} = this;
147
+ this.step = this.buf = null;
148
+ return buf.subarray(step.k|0)
149
+ }
150
+
151
+ }
152
+
153
+ let mqtt_reader_v5$1 = class mqtt_reader_v5 extends mqtt_reader_v4 {
154
+ props() {
155
+ let {buf, step} = this;
156
+ let [n, vi, vi0] = decode_varint$1(buf, step.k|0);
157
+ step(n + vi - vi0);
158
+ if (0 === n) return null
159
+
160
+ let res={}, fork = this.of(buf.subarray(vi, step.k|0));
161
+ while (fork.has_more()) {
162
+ let v, pk = fork.u8(), pt = mqtt_props.get( pk );
163
+
164
+ if (!pt) {
165
+ res.error = `Unknown mqtt_prop enum ${pk}`;
166
+ return res
167
+ }
168
+
169
+ v = fork[pt.type]();
170
+ if (pt.op) // accumulate operation
171
+ v = fork[pt.op](res[pt.name], v);
172
+
173
+ res[pt.name] = v;
174
+ }
175
+ return res
176
+ }
177
+
178
+ kv_obj(obj=Object.create(null), [k,v]) {
179
+ obj[k] = v;
180
+ return obj
181
+ }
182
+ u8_vec(vec=[], u8) {
183
+ vec.push(u8);
184
+ return vec
185
+ }
186
+
187
+ /*
188
+ vbuf() {
189
+ let {buf, step} = this
190
+ let [n, vi, vi0] = decode_varint(buf, step.k|0)
191
+ step(n + vi - vi0)
192
+ return 0 === n ? null
193
+ : buf.subarray(vi, step.k|0)
194
+ }
195
+ */
196
+ };
197
+
198
+ function mqtt_reader_info(mqtt_reader, ... info_fn_list) {
199
+ mqtt_reader = class extends mqtt_reader {
200
+ static reasons(pkt_type, ...reason_entries) {
201
+ let proto = this.prototype;
202
+ proto._reasons_by = {... proto._reasons_by};
203
+
204
+ let lut = (proto._reasons_by[pkt_type] ||= new Map());
205
+ for (let [u8, reason] of reason_entries)
206
+ lut.set( u8, reason );
207
+
208
+ return this
209
+ }
210
+ };
211
+
212
+ for (let fn_info of info_fn_list)
213
+ fn_info(mqtt_reader);
214
+
215
+ return mqtt_reader
216
+ }
217
+
218
+ class mqtt_writer_v4 {
219
+ static of() { return this.prototype.of() }
220
+ of() { return {__proto__: this, $:[]} }
221
+
222
+ static init() { return this }
223
+
224
+ as_pkt(pkt_id) { return this.pack([pkt_id]) }
225
+
226
+ push(...z) { this.$.push(...z); }
227
+ pack(hdr) {
228
+ let z, i, n=0, parts = this.$;
229
+ this.$ = false;
230
+ for (z of parts) n += z.length;
231
+
232
+ hdr = encode_varint(n, hdr);
233
+ i = hdr.length;
234
+
235
+ let pkt = new Uint8Array(i + n);
236
+ pkt.set(hdr, 0);
237
+ for (z of parts) {
238
+ pkt.set(z, i);
239
+ i += z.length;
240
+ }
241
+ return pkt
242
+ }
243
+
244
+ u8(v) { this.push([ v & 0xff ]); }
245
+ u16(v) { this.push([ (v>>>8) & 0xff, v & 0xff ]); }
246
+ u32(v) { this.push([ (v>>>24) & 0xff, (v>>>16) & 0xff, (v>>>8) & 0xff, v & 0xff ]); }
247
+ vint(v) { this.push( encode_varint(v) );}
248
+
249
+ bin(u8_buf) {
250
+ if (! u8_buf) return this.u16(0)
251
+ if ('string' === typeof u8_buf)
252
+ return this.utf8(u8_buf)
253
+
254
+ if (u8_buf.length !== u8_buf.byteLength)
255
+ u8_buf = new Uint8Array(u8_buf);
256
+
257
+ this.u16(u8_buf.byteLength);
258
+ this.push(u8_buf);
259
+ }
260
+
261
+ utf8(v) {
262
+ let u8_buf = new TextEncoder('utf-8').encode(v);
263
+ this.u16(u8_buf.byteLength);
264
+ this.push(u8_buf);
265
+ }
266
+ pair(k,v) { this.utf8(k); this.utf8(v); }
267
+
268
+ flags(v, enc_flags, b0=0) {
269
+ if (undefined !== v && isNaN(+v))
270
+ v = enc_flags(v, 0);
271
+
272
+ v |= b0;
273
+ this.push([v]);
274
+ return v
275
+ }
276
+
277
+ reason(v) { this.push([v | 0]); }
278
+
279
+ flush(buf) {
280
+ if (null != buf)
281
+ this.push(
282
+ 'string' === typeof buf
283
+ ? new TextEncoder('utf-8').encode(buf)
284
+ : buf );
285
+
286
+ this.push = false;
287
+ }
288
+ }
289
+
290
+
291
+ class mqtt_writer_v5 extends mqtt_writer_v4 {
292
+ props(props) {
293
+ if (! props)
294
+ return this.u8(0)
295
+
296
+ if (! Array.isArray(props))
297
+ props = props.entries
298
+ ? Array.from(props.entries())
299
+ : Object.entries(props);
300
+
301
+ if (0 === props.length)
302
+ return this.u8(0)
303
+
304
+ let fork = this.of();
305
+ for (let [name, value] of props) {
306
+ let pt = mqtt_props.get(name);
307
+ if (!pt)
308
+ throw new Error(`Unknown mqtt_prop "${name}"`)
309
+ fork[pt.op || 'one'](value, pt);
310
+ }
311
+ this.push(fork.pack());
312
+ }
313
+
314
+ one(value, pt) {
315
+ this.u8(pt.id);
316
+ this[pt.type](value);
317
+ }
318
+ kv_obj(obj, pt) {
319
+ for (let kv of Object.entries(obj)) {
320
+ this.u8(pt.id);
321
+ this.pair(kv);
322
+ }
323
+ }
324
+ u8_vec(vec, pt) {
325
+ for (let v of vec) {
326
+ this.u8(pt.id);
327
+ this.u8(v);
328
+ }
329
+ }
330
+ }
331
+
332
+ function mqtt_decode_connect(ns, mqtt_reader) {
333
+ class _connect_flags_ extends Number {
334
+ get reserved() { return this & 0x01 !== 0 }
335
+ get clean_start() { return this & 0x02 !== 0 }
336
+ get will_flag() { return this & 0x04 !== 0 }
337
+ get will_qos() { return (this >>> 3) & 0x3 }
338
+ get will_retain() { return this & 0x20 !== 0 }
339
+ get password() { return this & 0x40 !== 0 }
340
+ get username() { return this & 0x80 !== 0 }
341
+ }
342
+
343
+ return ns[0x1] = (pkt, u8_body) => {
344
+ let rdr = mqtt_reader.of(u8_body);
345
+ if ('MQTT' !== rdr.utf8())
346
+ throw new Error('Invalid mqtt_connect packet')
347
+
348
+ pkt._base_.mqtt_level = pkt.mqtt_level = rdr.u8();
349
+
350
+ let flags = pkt.flags =
351
+ rdr.flags(_connect_flags_);
352
+
353
+ pkt.keep_alive = rdr.u16();
354
+
355
+ if (5 <= pkt.mqtt_level)
356
+ pkt.props = rdr.props();
357
+
358
+
359
+
360
+ pkt.client_id = rdr.utf8();
361
+ if (flags.will_flag) {
362
+ let will = pkt.will = {};
363
+ if (5 <= pkt.mqtt_level)
364
+ will.props = rdr.props();
365
+
366
+ will.topic = rdr.utf8();
367
+ will.payload = rdr.bin();
368
+ will.qos = flags.will_qos;
369
+ will.retain = flags.will_retain;
370
+ }
371
+
372
+ if (flags.username)
373
+ pkt.username = rdr.utf8();
374
+
375
+ if (flags.password)
376
+ pkt.password = rdr.bin();
377
+ return pkt }
378
+ }
379
+
380
+ function mqtt_decode_connack(ns, mqtt_reader) {
381
+ class _connack_flags_ extends Number {
382
+ get session_present() { return this & 0x01 !== 0 }
383
+ }
384
+
385
+ return ns[0x2] = (pkt, u8_body) => {
386
+ let rdr = mqtt_reader.of(u8_body);
387
+
388
+ pkt.flags =
389
+ rdr.flags(_connack_flags_);
390
+
391
+ pkt.reason = rdr.reason(pkt.type);
392
+ if (5 <= pkt.mqtt_level)
393
+ pkt.props = rdr.props();
394
+ return pkt }
395
+ }
396
+
397
+
398
+ function _connack_v4(mqtt_reader) {
399
+ mqtt_reader.reasons('connack',
400
+ // MQTT 3.1.1
401
+ [ 0x00, 'Success'],
402
+ [ 0x01, 'Connection refused, unacceptable protocol version'],
403
+ [ 0x02, 'Connection refused, identifier rejected'],
404
+ [ 0x03, 'Connection refused, server unavailable'],
405
+ [ 0x04, 'Connection refused, bad user name or password'],
406
+ [ 0x05, 'Connection refused, not authorized'],
407
+ );
408
+ }
409
+
410
+ function _connack_v5(mqtt_reader) {
411
+ _connack_v4(mqtt_reader);
412
+
413
+ mqtt_reader.reasons('connack',
414
+ // MQTT 5.0
415
+ [ 0x81, 'Malformed Packet'],
416
+ [ 0x82, 'Protocol Error'],
417
+ [ 0x83, 'Implementation specific error'],
418
+ [ 0x84, 'Unsupported Protocol Version'],
419
+ [ 0x85, 'Client Identifier not valid'],
420
+ [ 0x86, 'Bad User Name or Password'],
421
+ [ 0x87, 'Not authorized'],
422
+ [ 0x88, 'Server unavailable'],
423
+ [ 0x89, 'Server busy'],
424
+ [ 0x8A, 'Banned'],
425
+ [ 0x8C, 'Bad authentication method'],
426
+ [ 0x90, 'Topic Name invalid'],
427
+ [ 0x95, 'Packet too large'],
428
+ [ 0x97, 'Quota exceeded'],
429
+ [ 0x99, 'Payload format invalid'],
430
+ [ 0x9A, 'Retain not supported'],
431
+ [ 0x9B, 'QoS not supported'],
432
+ [ 0x9C, 'Use another server'],
433
+ [ 0x9D, 'Server moved'],
434
+ [ 0x9F, 'Connection rate exceeded'],
435
+ );
436
+ }
437
+
438
+ function mqtt_decode_publish(ns, mqtt_reader) {
439
+ return ns[0x3] = (pkt, u8_body) => {
440
+ let {hdr} = pkt;
441
+ pkt.dup = Boolean(hdr & 0x8);
442
+ pkt.retain = Boolean(hdr & 0x1);
443
+ let qos = pkt.qos = (hdr>>1) & 0x3;
444
+
445
+ let rdr = mqtt_reader.of(u8_body);
446
+ pkt.topic = rdr.utf8();
447
+ if (0 !== qos)
448
+ pkt.pkt_id = rdr.u16();
449
+
450
+ if (5 <= pkt.mqtt_level)
451
+ pkt.props = rdr.props();
452
+
453
+ pkt.payload = rdr.flush();
454
+ return pkt }
455
+ }
456
+
457
+ function mqtt_decode_puback(ns, mqtt_reader) {
458
+ return ns[0x4] = (pkt, u8_body) => {
459
+ let rdr = mqtt_reader.of(u8_body);
460
+
461
+ pkt.pkt_id = rdr.u16();
462
+ if (5 <= pkt.mqtt_level) {
463
+ pkt.reason = rdr.reason(pkt.type);
464
+ pkt.props = rdr.props();
465
+ }
466
+
467
+ return pkt }
468
+ }
469
+
470
+
471
+ function _puback_v5(mqtt_reader) {
472
+ mqtt_reader.reasons('puback',
473
+ // MQTT 5.0
474
+ [ 0x00, 'Success'],
475
+ [ 0x10, 'No matching subscribers'],
476
+ [ 0x80, 'Unspecified error'],
477
+ [ 0x83, 'Implementation specific error'],
478
+ [ 0x87, 'Not authorized'],
479
+ [ 0x90, 'Topic Name invalid'],
480
+ [ 0x91, 'Packet identifier in use'],
481
+ [ 0x97, 'Quota exceeded'],
482
+ [ 0x99, 'Payload format invalid'],
483
+ );
484
+ }
485
+
486
+ function mqtt_decode_pubxxx(ns, mqtt_reader) {
487
+ return ns[0x5] = ns[0x6] = ns[0x7] = (pkt, u8_body) => {
488
+ let rdr = mqtt_reader.of(u8_body);
489
+
490
+ pkt.pkt_id = rdr.u16();
491
+ pkt.reason = rdr.reason('pubxxx', mqtt_reader);
492
+ if (5 <= pkt.mqtt_level)
493
+ pkt.props = rdr.props();
494
+ return pkt }
495
+ }
496
+
497
+ function _pubxxx_v4(mqtt_reader) {
498
+ mqtt_reader.reasons('pubxxx',
499
+ // MQTT 3.1.1
500
+ [ 0x00, 'Success' ],
501
+ [ 0x92, 'Packet Identifier not found' ],
502
+ );
503
+ }
504
+
505
+ function mqtt_decode_subscribe(ns, mqtt_reader) {
506
+ class _subscription_options_ extends Number {
507
+ get qos() { return this & 0x3 }
508
+ get retain() { return this & 0x4 !== 0 }
509
+ get retain_handling() { return (this >> 2) & 0x3 }
510
+ }
511
+
512
+ return ns[0x8] = (pkt, u8_body) => {
513
+ let rdr = mqtt_reader.of(u8_body);
514
+
515
+ pkt.pkt_id = rdr.u16();
516
+ if (5 <= pkt.mqtt_level)
517
+ pkt.props = rdr.props();
518
+
519
+ let topic, opts, topic_list = pkt.topics = [];
520
+ while (rdr.has_more()) {
521
+ topic = rdr.utf8();
522
+ opts = rdr.flags(_subscription_options_);
523
+ topic_list.push({topic, opts});
524
+ }
525
+
526
+ return pkt }
527
+ }
528
+
529
+ function _mqtt_decode_suback(mqtt_reader) {
530
+ return (pkt, u8_body) => {
531
+ let rdr = mqtt_reader.of(u8_body);
532
+
533
+ pkt.pkt_id = rdr.u16();
534
+ if (5 <= pkt.mqtt_level)
535
+ pkt.props = rdr.props();
536
+
537
+ let answers = pkt.answers = [];
538
+ while (rdr.has_more())
539
+ answers.push(
540
+ rdr.reason(pkt.type) );
541
+
542
+ return pkt }
543
+ }
544
+
545
+ function mqtt_decode_suback(ns, mqtt_reader) {
546
+ return ns[0x9] = _mqtt_decode_suback(mqtt_reader)
547
+ }
548
+
549
+ function _suback_v4(mqtt_reader) {
550
+ mqtt_reader.reasons('suback',
551
+ // MQTT 3.1.1
552
+ [ 0x00, 'Granted QoS 0'],
553
+ [ 0x01, 'Granted QoS 1'],
554
+ [ 0x02, 'Granted QoS 2'],
555
+ );
556
+ }
557
+
558
+ function _suback_v5(mqtt_reader) {
559
+ _suback_v4(mqtt_reader);
560
+
561
+ mqtt_reader.reasons('suback',
562
+ // MQTT 5.0
563
+ [ 0x80, 'Unspecified error'],
564
+ [ 0x83, 'Implementation specific error'],
565
+ [ 0x87, 'Not authorized'],
566
+ [ 0x8F, 'Topic Filter invalid'],
567
+ [ 0x91, 'Packet Identifier in use'],
568
+ [ 0x97, 'Quota exceeded'],
569
+ [ 0x9E, 'Shared Subscriptions not supported'],
570
+ [ 0xA1, 'Subscription Identifiers not supported'],
571
+ [ 0xA2, 'Wildcard Subscriptions not supported'],
572
+ );
573
+ }
574
+
575
+ function mqtt_decode_unsubscribe(ns, mqtt_reader) {
576
+ return ns[0xa] = (pkt, u8_body) => {
577
+ let rdr = mqtt_reader.of(u8_body);
578
+
579
+ pkt.pkt_id = rdr.u16();
580
+ if (5 <= pkt.mqtt_level)
581
+ pkt.props = rdr.props();
582
+
583
+ let topic_list = pkt.topics = [];
584
+ while (rdr.has_more())
585
+ topic_list.push(rdr.utf8());
586
+
587
+ return pkt }
588
+ }
589
+
590
+ function mqtt_decode_unsuback(ns, mqtt_reader) {
591
+ return ns[0xb] = _mqtt_decode_suback(mqtt_reader)
592
+ }
593
+
594
+ function _unsuback_v4(mqtt_reader) {
595
+ mqtt_reader.reasons('unsuback',
596
+ // MQTT 3.1.1
597
+ [ 0x00, 'Success'],
598
+ [ 0x11, 'No subscription existed'],
599
+ [ 0x80, 'Unspecified error'],
600
+ [ 0x83, 'Implementation specific error'],
601
+ [ 0x87, 'Not authorized'],
602
+ [ 0x8F, 'Topic Filter invalid'],
603
+ [ 0x91, 'Packet Identifier in use'],
604
+ );
605
+ }
606
+
607
+ function mqtt_decode_pingxxx(ns) {
608
+ return ns[0xc] = ns[0xd] = pkt => pkt
609
+ }
610
+
611
+ function mqtt_decode_disconnect(ns, mqtt_reader) {
612
+ return ns[0xe] = (pkt, u8_body) => {
613
+ if (u8_body && 5 <= pkt.mqtt_level) {
614
+ let rdr = mqtt_reader.of(u8_body);
615
+ pkt.reason = rdr.reason(pkt.type);
616
+ pkt.props = rdr.props();
617
+ }
618
+ return pkt }
619
+ }
620
+
621
+
622
+ function _disconnect_v5(mqtt_reader) {
623
+ mqtt_reader.reasons('disconnect',
624
+ // MQTT 5.0
625
+ [ 0x00, 'Normal disconnection'],
626
+ [ 0x04, 'Disconnect with Will Message'],
627
+ [ 0x80, 'Unspecified error'],
628
+ [ 0x81, 'Malformed Packet'],
629
+ [ 0x82, 'Protocol Error'],
630
+ [ 0x83, 'Implementation specific error'],
631
+ [ 0x87, 'Not authorized'],
632
+ [ 0x89, 'Server busy'],
633
+ [ 0x8B, 'Server shutting down'],
634
+ [ 0x8D, 'Keep Alive timeout'],
635
+ [ 0x8E, 'Session taken over'],
636
+ [ 0x8F, 'Topic Filter invalid'],
637
+ [ 0x90, 'Topic Name invalid'],
638
+ [ 0x93, 'Receive Maximum exceeded'],
639
+ [ 0x94, 'Topic Alias invalid'],
640
+ [ 0x95, 'Packet too large'],
641
+ [ 0x96, 'Message rate too high'],
642
+ [ 0x97, 'Quota exceeded'],
643
+ [ 0x98, 'Administrative action'],
644
+ [ 0x99, 'Payload format invalid'],
645
+ [ 0x9A, 'Retain not supported'],
646
+ [ 0x9B, 'QoS not supported'],
647
+ [ 0x9C, 'Use another server'],
648
+ [ 0x9D, 'Server moved'],
649
+ [ 0x9E, 'Shared Subscriptions not supported'],
650
+ [ 0x9F, 'Connection rate exceeded'],
651
+ [ 0xA0, 'Maximum connect time'],
652
+ [ 0xA1, 'Subscription Identifiers not supported'],
653
+ [ 0xA2, 'Wildcard Subscriptions not supported'],
654
+ );
655
+ }
656
+
657
+ function mqtt_decode_auth(ns, mqtt_reader) {
658
+ return ns[0xf] = (pkt, u8_body) => {
659
+ if ( 5 <= pkt.mqtt_level ) {
660
+ let rdr = mqtt_reader.of(u8_body);
661
+ pkt.reason = rdr.reason(pkt.type);
662
+ pkt.props = rdr.props();
663
+ }
664
+ return pkt }
665
+ }
666
+
667
+
668
+ function _auth_v5(mqtt_reader) {
669
+ mqtt_reader.reasons('auth',
670
+ // MQTT 5.0
671
+ [ 0x00, 'Success' ],
672
+ [ 0x18, 'Continue authentication' ],
673
+ [ 0x19, 'Re-authenticate' ],
674
+ );
675
+ }
676
+
677
+ function mqtt_encode_connect(ns, mqtt_writer) {
678
+ const _c_mqtt_proto = new Uint8Array([
679
+ 0, 4, 0x4d, 0x51, 0x54, 0x54 ]);
680
+
681
+ const _enc_flags_connect = flags => 0
682
+ | ( flags.reserved ? 0x01 : 0 )
683
+ | ( (flags.will_qos & 0x3) << 3 )
684
+ | ( flags.clean_start ? 0x02 : 0 )
685
+ | ( flags.will_flag ? 0x04 : 0 )
686
+ | ( flags.will_retain ? 0x20 : 0 )
687
+ | ( flags.password ? 0x40 : 0 )
688
+ | ( flags.username ? 0x80 : 0 );
689
+
690
+ const _enc_flags_will = will => 0x4
691
+ | ( (will.qos & 0x3) << 3 )
692
+ | ( will.retain ? 0x20 : 0 );
693
+
694
+ return ns.connect = ( mqtt_level, pkt ) => {
695
+ let wrt = mqtt_writer.of(pkt);
696
+
697
+ wrt.push(_c_mqtt_proto);
698
+ wrt.u8( mqtt_level );
699
+
700
+ let {will, username, password} = pkt;
701
+ let flags = wrt.flags(
702
+ pkt.flags,
703
+ _enc_flags_connect,
704
+ 0 | (username ? 0x80 : 0)
705
+ | (password ? 0x40 : 0)
706
+ | (will ? _enc_flags_will(will) : 0) );
707
+
708
+ wrt.u16(pkt.keep_alive);
709
+
710
+ if (5 <= mqtt_level)
711
+ wrt.props(pkt.props);
712
+
713
+
714
+ wrt.utf8(pkt.client_id);
715
+ if (flags & 0x04) { // .will_flag
716
+ if (5 <= mqtt_level)
717
+ wrt.props(will.props);
718
+
719
+ wrt.utf8(will.topic);
720
+ wrt.bin(will.payload);
721
+ }
722
+
723
+ if (flags & 0x80) // .username
724
+ wrt.utf8(username);
725
+
726
+ if (flags & 0x40) // .password
727
+ wrt.bin(password);
728
+
729
+ return wrt.as_pkt(0x10)
730
+ }
731
+ }
732
+
733
+ function mqtt_encode_connack(ns, mqtt_writer) {
734
+ const _enc_flags_connack = flags =>
735
+ flags.session_present ? 1 : 0;
736
+
737
+ return ns.connack = (mqtt_level, pkt) => {
738
+ let wrt = mqtt_writer.of(pkt);
739
+
740
+ wrt.flags( pkt.flags, _enc_flags_connack );
741
+
742
+ if (5 <= mqtt_level) {
743
+ wrt.reason( pkt.reason );
744
+ wrt.props( pkt.props );
745
+
746
+ } else {
747
+ wrt.reason( pkt.return_code || pkt.reason );
748
+ }
749
+
750
+ return wrt.as_pkt(0x20)
751
+ }
752
+ }
753
+
754
+ function mqtt_encode_publish(ns, mqtt_writer) {
755
+ return ns.publish = ( mqtt_level, pkt ) => {
756
+ let qos = (pkt.qos & 0x3) << 1;
757
+ let wrt = mqtt_writer.of(pkt);
758
+
759
+ wrt.utf8(pkt.topic);
760
+ if (0 !== qos)
761
+ wrt.u16(pkt.pkt_id);
762
+
763
+ if ( 5 <= mqtt_level) {
764
+ wrt.props(pkt.props);
765
+ wrt.flush(pkt.payload);
766
+ } else {
767
+ wrt.flush(pkt.payload);
768
+ }
769
+
770
+ return wrt.as_pkt(
771
+ 0x30 | qos | (pkt.dup ? 0x8 : 0) | (pkt.retain ? 0x1 : 0) )
772
+ }
773
+ }
774
+
775
+ function mqtt_encode_puback(ns, mqtt_writer) {
776
+ return ns.puback = ( mqtt_level, pkt ) => {
777
+ let wrt = mqtt_writer.of(pkt);
778
+
779
+ wrt.u16(pkt.pkt_id);
780
+ if (5 <= mqtt_level) {
781
+ wrt.reason(pkt.reason);
782
+ wrt.props(pkt.props);
783
+ }
784
+
785
+ return wrt.as_pkt(0x40)
786
+ }
787
+ }
788
+
789
+ function mqtt_encode_pubxxx(ns, mqtt_writer) {
790
+ ns.pubrec = _enc_pubxxx(0x50);
791
+ ns.pubrel = _enc_pubxxx(0x62);
792
+ ns.pubcomp = _enc_pubxxx(0x70);
793
+
794
+
795
+ function _enc_pubxxx(hdr) {
796
+ return ( mqtt_level, pkt ) => {
797
+ let wrt = mqtt_writer.of(pkt);
798
+
799
+ wrt.u16(pkt.pkt_id);
800
+ if (5 <= mqtt_level) {
801
+ wrt.props(pkt.props);
802
+ wrt.reason(pkt.reason);
803
+
804
+ } else {
805
+ wrt.reason( pkt.return_code || pkt.reason );
806
+ }
807
+
808
+ return wrt.as_pkt(hdr)
809
+ }
810
+ }
811
+ }
812
+
813
+ function mqtt_encode_subscribe(ns, mqtt_writer) {
814
+ const _enc_subscribe_flags = opts => 0
815
+ | ( opts.qos & 0x3 )
816
+ | ( opts.retain ? 0x4 : 0 )
817
+ | ( (opts.retain_handling & 0x3) << 2 );
818
+
819
+ return ns.subscribe = ( mqtt_level, pkt ) => {
820
+ let wrt = mqtt_writer.of(pkt);
821
+
822
+ wrt.u16(pkt.pkt_id);
823
+ if (5 <= mqtt_level)
824
+ wrt.props(pkt.props);
825
+
826
+ let f0 = _enc_subscribe_flags(pkt);
827
+ for (let each of pkt.topics) {
828
+ if ('string' === typeof each) {
829
+ wrt.utf8(each);
830
+ wrt.u8(f0);
831
+ } else {
832
+ let [topic, opts] =
833
+ Array.isArray(each) ? each
834
+ : [each.topic, each.opts];
835
+
836
+ wrt.utf8(topic);
837
+ if (undefined === opts) wrt.u8(f0);
838
+ else wrt.flags(opts, _enc_subscribe_flags);
839
+ }
840
+ }
841
+
842
+ return wrt.as_pkt(0x82)
843
+ }
844
+ }
845
+
846
+ function mqtt_encode_xxsuback(ns, mqtt_writer) {
847
+ ns.suback = _enc_xxsuback(0x90);
848
+ ns.unsuback = _enc_xxsuback(0xb0);
849
+
850
+
851
+ function _enc_xxsuback(hdr) {
852
+ return ( mqtt_level, pkt ) => {
853
+ let wrt = mqtt_writer.of(pkt);
854
+
855
+ wrt.u16(pkt.pkt_id);
856
+ if (5 <= mqtt_level)
857
+ wrt.props(pkt.props);
858
+
859
+ for (let ans of pkt.answers)
860
+ wrt.reason(ans);
861
+
862
+ return wrt.as_pkt(hdr)
863
+ }
864
+ }
865
+ }
866
+
867
+ function mqtt_encode_unsubscribe(ns, mqtt_writer) {
868
+ return ns.unsubscribe = ( mqtt_level, pkt ) => {
869
+ let wrt = mqtt_writer.of(pkt);
870
+
871
+ wrt.u16(pkt.pkt_id);
872
+ if (5 <= mqtt_level)
873
+ wrt.props(pkt.props);
874
+
875
+ for (let topic of pkt.topics)
876
+ wrt.utf8(topic);
877
+
878
+ return wrt.as_pkt(0xa2)
879
+ }
880
+ }
881
+
882
+ function mqtt_encode_pingxxx(ns) {
883
+ ns.pingreq = () => new Uint8Array([ 0xc0, 0 ]);
884
+ ns.pingresp = () => new Uint8Array([ 0xd0, 0 ]);
885
+ }
886
+
887
+ function mqtt_encode_disconnect(ns, mqtt_writer) {
888
+ return ns.disconnect = ( mqtt_level, pkt ) => {
889
+ let wrt = mqtt_writer.of(pkt);
890
+
891
+ if (pkt && 5 <= mqtt_level) {
892
+ if (pkt.reason || pkt.props) {
893
+ wrt.reason(pkt.reason);
894
+ wrt.props(pkt.props);
895
+ }
896
+ }
897
+
898
+ return wrt.as_pkt(0xe0)
899
+ }
900
+ }
901
+
902
+ function mqtt_encode_auth(ns, mqtt_writer) {
903
+ return ns.auth = ( mqtt_level, pkt ) => {
904
+ if (5 > mqtt_level)
905
+ throw new Error('Auth packets are only available after MQTT 5.x')
906
+
907
+ let wrt = mqtt_writer.of(pkt);
908
+
909
+ wrt.reason(pkt.reason);
910
+ wrt.props(pkt.props);
911
+
912
+ return wrt.as_pkt(0xf0)
913
+ }
914
+ }
915
+
916
+ const mqtt_reader_v5 = /* #__PURE__ */
917
+ mqtt_reader_info(
918
+ mqtt_reader_v5$1,
919
+ _connack_v5,
920
+ _puback_v5,
921
+ _pubxxx_v4,
922
+ _suback_v5,
923
+ _unsuback_v4,
924
+ _disconnect_v5,
925
+ _auth_v5,
926
+ );
927
+
928
+ const mqtt_decode_v5 = [
929
+ mqtt_decode_connect,
930
+ mqtt_decode_connack,
931
+ mqtt_decode_publish,
932
+ mqtt_decode_puback,
933
+ mqtt_decode_pubxxx,
934
+ mqtt_decode_subscribe,
935
+ mqtt_decode_suback,
936
+ mqtt_decode_unsubscribe,
937
+ mqtt_decode_unsuback,
938
+ mqtt_decode_pingxxx,
939
+ mqtt_decode_disconnect,
940
+ mqtt_decode_auth,
941
+ ];
942
+
943
+
944
+ const mqtt_encode_v5 = [
945
+ mqtt_encode_connect,
946
+ mqtt_encode_connack,
947
+ mqtt_encode_publish,
948
+ mqtt_encode_puback,
949
+ mqtt_encode_pubxxx,
950
+ mqtt_encode_subscribe,
951
+ mqtt_encode_xxsuback,
952
+ mqtt_encode_unsubscribe,
953
+ mqtt_encode_pingxxx,
954
+ mqtt_encode_disconnect,
955
+ mqtt_encode_auth,
956
+ ];
957
+
958
+
959
+ const mqtt_opts_v5 =
960
+ { decode_fns: mqtt_decode_v5,
961
+ mqtt_reader: mqtt_reader_v5,
962
+ encode_fns: mqtt_encode_v5,
963
+ mqtt_writer: mqtt_writer_v5, };
964
+
965
+ function parse(str, loose) {
966
+ if (str instanceof RegExp) return { keys:false, pattern:str };
967
+ var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
968
+ arr[0] || arr.shift();
969
+
970
+ while (tmp = arr.shift()) {
971
+ c = tmp[0];
972
+ if (c === '*') {
973
+ keys.push('wild');
974
+ pattern += '/(.*)';
975
+ } else if (c === ':') {
976
+ o = tmp.indexOf('?', 1);
977
+ ext = tmp.indexOf('.', 1);
978
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
979
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
980
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
981
+ } else {
982
+ pattern += '/' + tmp;
983
+ }
984
+ }
985
+
986
+ return {
987
+ keys: keys,
988
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
989
+ };
990
+ }
991
+
992
+ const _isfn = v => typeof v === 'function';
993
+ const _isstr = v => typeof v === 'string';
994
+
995
+ function _interval(fn_callback) {
996
+ let tid;
997
+ return (( td ) => {
998
+ tid = clearInterval(tid);
999
+ if (td) {
1000
+ tid = setInterval(fn_callback, 1000 * td);
1001
+
1002
+
1003
+
1004
+
1005
+ // ensure the interval allows the NodeJS event loop to exit
1006
+ tid.unref?.();
1007
+ return true} }) }
1008
+
1009
+ /*
1010
+ class AbstractTopicRouter ::
1011
+ async invoke(pkt, ctx) ::
1012
+ add(topic_route, ...args) ::
1013
+ remove(topic_route, priority) ::
1014
+ clear(priority) ::
1015
+ find(topic) :: // optional
1016
+ mqtt_topic(topic_route)
1017
+ */
1018
+
1019
+ const with_topic_router = mqtt_topic_router =>
1020
+ MQTTKlass => class extends MQTTKlass {
1021
+ static _aliases() {
1022
+ return super._aliases() +
1023
+ ' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
1024
+
1025
+ _init_router(opt, self, target) {
1026
+ this._subs = [];
1027
+ let router = this.router = target.router =
1028
+ mqtt_topic_router(opt, this, target);
1029
+ return router?.invoke}
1030
+
1031
+ on_sub(suback, pkt) {
1032
+ suback.pkt = pkt;
1033
+ this._subs.push(suback);
1034
+ return suback}
1035
+ subs_settled() {
1036
+ return Promise.allSettled(
1037
+ this._subs.splice(0,Infinity)) }
1038
+
1039
+ // alias: sub_topic
1040
+ subscribe_topic(topic_route, ...args) {
1041
+ let router = this.router;
1042
+ router.add(topic_route, true, args.pop() );// handler
1043
+ let topic = router.mqtt_topic(topic_route);
1044
+ this.subscribe(topic, ...args );// ex, topic_prefix
1045
+ return this }// fluent api -- return this and track side effects
1046
+
1047
+ // alias: unsub_topic
1048
+ unsubscribe_topic(topic_route, ...args) {
1049
+ let router = this.router;
1050
+ router.remove(topic_route, true);
1051
+ let topic = router.mqtt_topic(topic_route);
1052
+ return this.unsubscribe(topic, ...args ) }// topic_prefix
1053
+
1054
+ // add topic handlers without corresponding subscribe packet
1055
+ on_topic(...args) {
1056
+ this.router.add(...args);
1057
+ return this} };
1058
+
1059
+ // Use [regexparam][] for url-like topic parsing
1060
+ // [regexparam]: https://github.com/lukeed/regexparam
1061
+
1062
+
1063
+ const with_topic_path_router = /* #__PURE__ */
1064
+ with_topic_router(mqtt_topic_path_router);
1065
+
1066
+
1067
+ const mqtt_topic = topic_route =>
1068
+ topic_route
1069
+ .replace(/[*].*$/, '#')
1070
+ .replace(/:\w[^\/]*/g, '+');
1071
+
1072
+ /* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
1073
+ 4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
1074
+ ... MUST be specified either on its own or following a topic level separator.
1075
+ In either case it MUST be the last character specified in the Topic Filter
1076
+
1077
+ 4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
1078
+ ...it MUST occupy an entire level of the filter.
1079
+ */
1080
+
1081
+ const as_topic_path = (topic_route, id) =>(
1082
+ id=1,
1083
+ topic_route
1084
+ .replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
1085
+ .replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
1086
+
1087
+ function _ignore(pkt, params, ctx) {ctx.done = true;}
1088
+
1089
+ function mqtt_topic_path_router() {
1090
+ let pri_lsts = [[],[]], rm = Symbol();
1091
+ let find = topic => _routes_iter(pri_lsts, topic);
1092
+
1093
+ // return duck-type compatible with AbstractTopicRouter in ./with_topic_router
1094
+ return {find, mqtt_topic,
1095
+ add(topic_route, ...args) {
1096
+ let fn = args.pop();
1097
+ let priority = args.pop();
1098
+
1099
+ if (! _isfn(fn)) {
1100
+ if (fn) {throw new TypeError()}
1101
+ fn = _ignore;}
1102
+
1103
+ let rte = parse(as_topic_path(topic_route));
1104
+
1105
+ rte.key = topic_route;
1106
+ rte.tgt = fn;
1107
+ pri_lsts[priority ? 0 : 1].push(rte);
1108
+ return this}
1109
+
1110
+ , remove(topic_route, priority) {
1111
+ let lst = pri_lsts[priority ? 0 : 1];
1112
+ return _route_remove([lst], topic_route)}
1113
+
1114
+ , clear(priority) {
1115
+ pri_lsts[priority ? 0 : 1] = [];
1116
+ if (null == priority) {
1117
+ pri_lsts[1] = []; } }// null clears both lists
1118
+
1119
+ , async invoke(pkt, ctx) {
1120
+ ctx.idx = 0;
1121
+ ctx.rm = rm;
1122
+
1123
+ for (let [fn, params] of find(pkt.topic)) {
1124
+ let res = await fn(pkt, params, ctx);
1125
+
1126
+ if (rm === res) {
1127
+ _route_remove(pri_lsts, fn);}
1128
+
1129
+ if (ctx.done) {
1130
+ break}
1131
+ else ctx.idx++;}
1132
+
1133
+ if (1 === pkt.qos) {
1134
+ await ctx.mqtt.puback(pkt);} } } }
1135
+
1136
+
1137
+ function * _routes_iter(all_route_lists, topic) {
1138
+ topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
1139
+ for (let route_list of all_route_lists) {
1140
+ for (let {keys, pattern, tgt} of route_list) {
1141
+ let match = pattern.exec(topic);
1142
+ if (match) {
1143
+ let params = keys
1144
+ ? keys.reduce(
1145
+ (o, k, i) => (o[k] = match[1+i], o)
1146
+ , {})
1147
+ : match.groups ?? match;
1148
+ yield [tgt, params];} } } }
1149
+
1150
+
1151
+ function _route_remove(all_route_lists, query) {
1152
+ let fn_match = route =>(
1153
+ route===query
1154
+ || route.tgt===query
1155
+ || route.key===query);
1156
+ for (let lst of all_route_lists) {
1157
+ let i = lst.findIndex(fn_match);
1158
+ if (0 <= i) {
1159
+ lst.splice(i,1);
1160
+ return true} }
1161
+ return false}
1162
+
1163
+ /*
1164
+ export function decode_varint_loop(u8, i=0) {
1165
+ let i0 = i
1166
+ let shift = 0, n = (u8[i] & 0x7f)
1167
+ while ( 0x80 & u8[i++] )
1168
+ n |= (u8[i] & 0x7f) << (shift += 7)
1169
+
1170
+ return [n, i, i0]
1171
+ }
1172
+ */
1173
+
1174
+
1175
+ function decode_varint(u8, i=0) {
1176
+ let i0 = i;
1177
+ // unrolled for a max of 4 chains
1178
+ let n = (u8[i] & 0x7f) << 0;
1179
+ if ( 0x80 & u8[i++] ) {
1180
+ n |= (u8[i] & 0x7f) << 7;
1181
+ if ( 0x80 & u8[i++] ) {
1182
+ n |= (u8[i] & 0x7f) << 14;
1183
+ if ( 0x80 & u8[i++] ) {
1184
+ n |= (u8[i] & 0x7f) << 21;
1185
+ }
1186
+ }
1187
+ }
1188
+ return [n, i, i0]
1189
+ }
1190
+
1191
+ function mqtt_raw_dispatch(opt) {
1192
+ let u8 = new Uint8Array(0);
1193
+ return u8_buf => {
1194
+ u8 = 0 === u8.byteLength
1195
+ ? u8_buf : _u8_join(u8, u8_buf);
1196
+
1197
+ let res = [];
1198
+ while (1) {
1199
+ let [len_body, len_vh] = decode_varint(u8, 1);
1200
+ let len_pkt = len_body + len_vh;
1201
+
1202
+ if ( u8.byteLength < len_pkt )
1203
+ return res
1204
+
1205
+ let b0 = u8[0];
1206
+ let u8_body = 0 === len_body ? null
1207
+ : u8.subarray(len_vh, len_pkt);
1208
+
1209
+ u8 = u8.subarray(len_pkt);
1210
+
1211
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
1212
+ if (null != pkt)
1213
+ res.push( pkt );
1214
+ }
1215
+ }
1216
+ }
1217
+
1218
+ function _u8_join(a, b) {
1219
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
1220
+ r.set(a, 0);
1221
+ r.set(b, alen);
1222
+ return r
1223
+ }
1224
+
1225
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
1226
+
1227
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
1228
+ pkt_ctx = {
1229
+ __proto__: pkt_ctx || opts.pkt_ctx,
1230
+ mqtt_level,
1231
+ get hdr() { return this.b0 & 0xf },
1232
+ get id() { return this.b0 >>> 4 },
1233
+ get type() { return _pkt_types[this.b0 >>> 4] },
1234
+ };
1235
+
1236
+ let op, _decode_by_id=[], _encode_by_type={};
1237
+ for (op of opts.encode_fns)
1238
+ op(_encode_by_type, opts.mqtt_writer);
1239
+ for (op of opts.decode_fns)
1240
+ op(_decode_by_id, opts.mqtt_reader);
1241
+
1242
+ return {
1243
+ pkt_ctx,
1244
+
1245
+ encode_pkt(type, pkt) {
1246
+ return _encode_by_type[type]( mqtt_level, pkt ) },
1247
+
1248
+ decode_pkt(b0, u8_body) {
1249
+ if (b0.map) // Uint8Array in first arg
1250
+ return mqtt_raw_dispatch(this)(b0)[0]
1251
+
1252
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
1253
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
1254
+
1255
+ mqtt_stream() {
1256
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
1257
+ self.pkt_ctx._base_ = self.pkt_ctx;
1258
+ self.decode = mqtt_raw_dispatch(self);
1259
+ return self
1260
+ },
1261
+ }
1262
+ }
1263
+
1264
+ async function _mqtt_cmd_evt(target, answer, pkt, ctx) {
1265
+ /* target : on_mqtt_type = {
1266
+ mqtt_pkt(pkt, ctx) {}, // generic
1267
+
1268
+ mqtt_auth(pkt, ctx) {},
1269
+ mqtt_connect(pkt, ctx) {},
1270
+ mqtt_connack(pkt, ctx) {},
1271
+ mqtt_disconnect(pkt, ctx) {},
1272
+
1273
+ mqtt_publish(pkt, ctx) {},
1274
+ mqtt_subscribe(pkt, ctx) {},
1275
+ mqtt_unsubscribe(pkt, ctx) {},
1276
+
1277
+ mqtt_pingreq(pkt, ctx) {},
1278
+ mqtt_pingresp(pkt, ctx) {},
1279
+ } */
1280
+
1281
+ let pkt_fn = target[`mqtt_${pkt.type}`] || target.mqtt_pkt;
1282
+ await pkt_fn?.call(target, pkt, ctx);}
1283
+
1284
+ function _mqtt_cmd_type(target, answer, pkt, ctx) {
1285
+ answer(pkt.type, pkt);
1286
+ _mqtt_cmd_evt(target, answer, pkt, ctx);}
1287
+
1288
+ function _mqtt_cmd_id(target, answer, pkt) {
1289
+ answer(pkt.pkt_id, pkt);}
1290
+
1291
+
1292
+ const _mqtt_cmdids =[
1293
+ _ => {} // 0x0 reserved
1294
+ , _mqtt_cmd_evt // 0x1 connect
1295
+ , _mqtt_cmd_type // 0x2 connack
1296
+ , _mqtt_cmd_evt // 0x3 publish
1297
+ , _mqtt_cmd_id // 0x4 puback
1298
+ , _mqtt_cmd_id // 0x5 pubrec
1299
+ , _mqtt_cmd_id // 0x6 pubrel
1300
+ , _mqtt_cmd_id // 0x7 pubcomp
1301
+ , _mqtt_cmd_evt // 0x8 subscribe
1302
+ , _mqtt_cmd_id // 0x9 suback
1303
+ , _mqtt_cmd_evt // 0xa unsubscribe
1304
+ , _mqtt_cmd_id // 0xb unsuback
1305
+ , _mqtt_cmd_type // 0xc pingreq
1306
+ , _mqtt_cmd_type // 0xd pingresp
1307
+ , _mqtt_cmd_evt // 0xe disconnect
1308
+ , _mqtt_cmd_type ];// 0xf auth
1309
+
1310
+ function _mqtt_dispatch(opt, target) {
1311
+ let hashbelt=[], rotate_ts=0;
1312
+ // default rotate at 1s across 5 buckets
1313
+ let { td: rotate_td=1000, n: rotate_n=5 } = opt?.rotate || {};
1314
+
1315
+ // Promise / future scaffolding
1316
+ let _pkt_id=100, _ftr_key; // use _ftr_key to reuse _by_key closure
1317
+ let _ftr_by_key = fn_answer => hashbelt[0].set(_ftr_key, fn_answer);
1318
+
1319
+ on_mqtt([]); // init hashbelt and rotate_ts
1320
+ return [on_mqtt, pkt_future]
1321
+
1322
+
1323
+ function pkt_future(pkt_or_key) {
1324
+ if (! _isstr(pkt_or_key)) {
1325
+ _pkt_id = (_pkt_id + 1) & 0xffff; // 16-bit unsigned short
1326
+ _ftr_key = pkt_or_key.pkt_id = _pkt_id;}
1327
+ else _ftr_key = pkt_or_key;
1328
+
1329
+ return new Promise(_ftr_by_key)}
1330
+
1331
+ function answer(key, pkt) {
1332
+ for (let map of hashbelt) {
1333
+ let fn_answer = map.get(key);
1334
+ if (fn_answer) {
1335
+ map.delete(key);
1336
+
1337
+ fn_answer([pkt, /*err*/]); // option/maybe monad
1338
+ return true} }
1339
+ return false}
1340
+
1341
+ function on_mqtt(pkt_list, ctx) {
1342
+ for (let pkt of pkt_list) {
1343
+ _mqtt_cmdids[pkt.id](target, answer, pkt, ctx);}
1344
+
1345
+ // rotate after rotate_ts
1346
+ let now = Date.now();
1347
+ if (now > rotate_ts) {
1348
+ rotate_ts = rotate_td + now;
1349
+ hashbelt.unshift(new Map());
1350
+ while (hashbelt.length > rotate_n) {
1351
+ for (let fn_answer of hashbelt.pop().values()) {
1352
+ fn_answer([/*pkt*/, 'expired']); } } } } }// option/maybe monad
1353
+
1354
+ class MQTTError extends Error {
1355
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
1356
+ // use hex-encoded reasons to match MQTT spec documentation
1357
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
1358
+ this.mqtt_pkt = mqtt_pkt;
1359
+ this.reason = reason;} }
1360
+
1361
+ class MQTTBase {
1362
+ // Handshaking Packets
1363
+ async connect(pkt={}) {
1364
+ let cid = pkt.client_id;
1365
+ if (! _isstr(cid)) {
1366
+ // see init_client_id implementation in core.jsy
1367
+ pkt.client_id = cid = this.client_id || this.init_client_id(cid);}
1368
+ this.client_id = cid;
1369
+
1370
+ if (null == pkt.keep_alive) {
1371
+ pkt.keep_alive = 60;}
1372
+
1373
+ let response = await this._send0('connect', pkt, 'connack');
1374
+ if (0 != response[0].reason) {// compare to 0 to coerce to number
1375
+ throw new this.MQTTError(response[0])}
1376
+ return this.conn.on_conn(pkt, response)}
1377
+
1378
+ async disconnect(pkt={}) {
1379
+ let response = await this._send0('disconnect', pkt);
1380
+ return this.conn.on_dis(pkt, response)}
1381
+
1382
+ async auth(pkt={}) {
1383
+ let response = await this._send0('auth', pkt, 'auth');
1384
+ if (response[0].reason) {
1385
+ throw new this.MQTTError(response[0])}
1386
+ return this.conn.on_auth(pkt, response)}
1387
+
1388
+ ping() {return this._send('pingreq', null, 'pingresp')}
1389
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
1390
+
1391
+ // alias: sub
1392
+ subscribe(pkt, ex, topic_prefix) {
1393
+ pkt = _as_topics(pkt, ex, topic_prefix);
1394
+ let suback = this._send('subscribe', pkt, pkt);
1395
+ return this.on_sub?.(suback, pkt) ?? suback}
1396
+
1397
+ // alias: unsub
1398
+ unsubscribe(pkt, ex, topic_prefix) {
1399
+ pkt = _as_topics(pkt, ex, topic_prefix);
1400
+ return this._send('unsubscribe', pkt, pkt)}
1401
+
1402
+
1403
+ post(topic, payload, pub_opt) {// qos:0
1404
+ return this.pub({topic, payload, qos:0}, pub_opt)}
1405
+ send(topic, payload, pub_opt) {// qos:1
1406
+ return this.pub({topic, payload, qos:1}, pub_opt)}
1407
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
1408
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
1409
+
1410
+ // alias: json_post
1411
+ obj_post(topic, msg, pub_opt) {// qos:0
1412
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
1413
+ // alias: json_send
1414
+ obj_send(topic, msg, pub_opt) {// qos:1
1415
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
1416
+ // alias: json_store
1417
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
1418
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
1419
+
1420
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
1421
+ async pub(pkt, pub_opt) {
1422
+ if (undefined === pkt.payload) {
1423
+ if (_isfn(pub_opt)) {
1424
+ // pub_opt as a function is fn_encode value
1425
+ pub_opt = {fn_encode: pub_opt};}
1426
+
1427
+ let msg = pkt.msg, fn_encode = pub_opt?.fn_encode;
1428
+ if (null == msg || _isfn(msg)) {
1429
+ // when msg is a function, return closure using fn_encode
1430
+ if (msg) {pub_opt = {...pub_opt, fn_encode: msg};}
1431
+ // return a single-value closure to publish packets
1432
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
1433
+
1434
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
1435
+ pkt.payload = fn_encode
1436
+ ? await fn_encode(msg)
1437
+ : JSON.stringify(msg);}
1438
+
1439
+ if (pub_opt) {
1440
+ if (pub_opt.props) {
1441
+ pkt.props = pub_opt.props;}
1442
+ if (pub_opt.xform) {
1443
+ pkt = pub_opt.xform(pkt) || pkt;} }
1444
+
1445
+ return this._send('publish', pkt,
1446
+ pkt.qos ? pkt : null ) }// key
1447
+
1448
+
1449
+ // Internal API
1450
+
1451
+ /* async _send0(type, pkt) -- provided by conn and transport */
1452
+ /* async _send(type, pkt) -- provided by conn and transport */
1453
+
1454
+ _init_dispatch(opt) {
1455
+ this.constructor?._once_();
1456
+ let target ={__proto__: opt.on_mqtt_type};
1457
+ target.mqtt_publish ||=
1458
+ this._init_router?.(opt, this, target);
1459
+ return _mqtt_dispatch(opt, target)}
1460
+
1461
+ static _aliases() {
1462
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
1463
+
1464
+ static _once_(klass=this) {
1465
+ klass._once_ = _=>0;
1466
+ var alias, name, p = klass.prototype;
1467
+ p.MQTTError = MQTTError;
1468
+ for (alias of klass._aliases().split(/\s+/)) {
1469
+ [alias, name] = alias.split(':');
1470
+ p[alias] = p[name];} } }
1471
+
1472
+
1473
+ function _as_topics(pkt, ex, topic_prefix) {
1474
+ if (ex?.trim) {// string
1475
+ topic_prefix = ex;
1476
+ ex = null;}
1477
+
1478
+ pkt =(
1479
+ pkt.trim // string
1480
+ ? {topics:[pkt], ... ex}
1481
+ : pkt[Symbol.iterator]
1482
+ ? {topics:[... pkt], ... ex}
1483
+ : ex ? {...pkt, ...ex}
1484
+ : pkt);
1485
+
1486
+ if (topic_prefix) {
1487
+ // particularly useful with shared queues, e.g.
1488
+ // topic_prefix = '$share/some-queue-name/'
1489
+ let _prefix_topics = v =>
1490
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
1491
+
1492
+ pkt.topics = pkt.topics.map(_prefix_topics);}
1493
+ return pkt}
1494
+
1495
+ const _defer_obj = o =>(
1496
+ o.p = new Promise((a,e) => { o.a=a; o.e=e; })
1497
+ , o);
1498
+
1499
+ function _dfn_reset(client, attr, fn_after) {
1500
+ // a resetable deferred for a function
1501
+ let self = {set}, afn = async (...args) => (await self.p)(...args);
1502
+ return set()
1503
+
1504
+ function set() {
1505
+ if (afn !== client[attr]) {
1506
+ _defer_obj(self).p.then(fn_after, _=>0);
1507
+ client[attr] = afn;}
1508
+ return self} }
1509
+
1510
+ function _mqtt_conn(opt, client, [on_mqtt, pkt_future]) {
1511
+ let _abort;
1512
+ let _dfn_send0 = _dfn_reset(client, '_send0', // client._send0 getter/setter
1513
+ _=> client.conn_emit('on_live', conn.has_connected));
1514
+ let _dfn_ready = _dfn_reset(client, '_send', // client._send getter/setter
1515
+ _=> client.conn_emit('on_ready'));
1516
+ let _keep_alive_ival = _interval (() =>client._send0('pingreq') );// resettable interval for keep_alive ping
1517
+
1518
+ let conn = Object.create({
1519
+ ping: (td=conn.keep_alive) => _keep_alive_ival(td)
1520
+
1521
+ , on_conn(pkt, response) {
1522
+ conn.has_connected = true;
1523
+ conn.keep_alive = opt.keep_alive || response[0].props?.server_keep_alive || pkt.keep_alive;
1524
+ client.conn_emit('on_conn');
1525
+ return opt.use_auth
1526
+ ? response // wait on enhanced authentication step
1527
+ : conn.on_auth(null, response) }// otherwise, connect is also auth
1528
+
1529
+ , on_auth(pkt, response) {
1530
+ _dfn_ready.a(_dfn_send0.p);
1531
+ if (0 != opt.keep_alive) {
1532
+ conn.ping();}
1533
+ client.conn_emit('on_auth', !pkt);
1534
+ return response}
1535
+
1536
+ , on_dis(pkt, response) {
1537
+ conn.reset(false);
1538
+ return response}
1539
+
1540
+ , reset(err) {
1541
+ if (err) {
1542
+ _dfn_send0.e(err); }// send error to uses of _send0 (connect, auth)
1543
+ _abort.e(err); // abort in-progress connections
1544
+
1545
+ delete conn.is_set;
1546
+ conn.ready = handshake();
1547
+ client.conn_emit('on_disconnect', false===err, err);}
1548
+
1549
+ , abort() {
1550
+ _dfn_ready.e(err); // abort all messages awaiting ready state
1551
+ return conn.reset(err)}
1552
+
1553
+ , async setup(gate, send_u8_pkt, init_msg_loop) {
1554
+ if (conn.is_set) {
1555
+ throw new Error() }// already in-progress
1556
+
1557
+ conn.is_set = true;
1558
+ await gate;
1559
+
1560
+ // setup send/recv MQTT parsing context
1561
+ let mqtt_ctx = client.mqtt_ctx.mqtt_stream();
1562
+
1563
+ {// setup inbound message loop
1564
+ let sess_ctx = {mqtt: client}; // mutable session context
1565
+ let on_mqtt_chunk = u8 => on_mqtt(mqtt_ctx.decode(u8), sess_ctx);
1566
+ init_msg_loop(on_mqtt_chunk, conn);}
1567
+
1568
+ // setup outbound message path and transport connection
1569
+ send_u8_pkt = await send_u8_pkt;
1570
+ _dfn_send0.a(
1571
+ async (type, pkt, key) => {
1572
+ let res = undefined !== key
1573
+ ? pkt_future(key) : true;
1574
+
1575
+ await send_u8_pkt(
1576
+ mqtt_ctx.encode_pkt(type, pkt));
1577
+ return res} ); } });
1578
+
1579
+ conn.ready = handshake();
1580
+ return conn
1581
+
1582
+ async function handshake() {
1583
+ _abort = _defer_obj({});
1584
+
1585
+ _keep_alive_ival(0); // clearInterval on keep alive ping
1586
+ _dfn_send0.set(); // reset client._send0 if necessary
1587
+ _dfn_ready.set(); // reset client._send if necessary
1588
+
1589
+ try {
1590
+ // set client._send0 as passtrhough after transport connection
1591
+ client._send0 = await Promise.race([_dfn_send0.p, _abort.p]);
1592
+
1593
+ // set client._send as passtrhough after ready
1594
+ client._send = await Promise.race([_dfn_ready.p, _abort.p]);
1595
+ return true}
1596
+ catch (err) {
1597
+ return false} } }
1598
+
1599
+ const pkt_api ={
1600
+ utf8(u8) {return new TextDecoder('utf-8').decode(u8 || this.payload )}
1601
+ , json(u8) {return JSON.parse( this.utf8(u8) || null )}
1602
+ , text(u8) {return this.utf8(u8)} };
1603
+
1604
+ const opt_default ={
1605
+ sess_stg: globalThis.sessionStorage};
1606
+
1607
+ class MQTTCore extends MQTTBase {
1608
+ constructor(opt) {
1609
+ super();
1610
+ this.with(opt);
1611
+ opt ={...opt_default, ...opt};
1612
+ // settings for MQTTCore
1613
+ this.sess_stg = opt.sess_stg;
1614
+ // setup connection and dispatch
1615
+ this.conn = _mqtt_conn(opt, this,
1616
+ this._init_dispatch(opt)); }
1617
+
1618
+ with(fns_ns) {
1619
+ for (let [k,v] of Object.entries(fns_ns)) {
1620
+ if (_isfn(v)) {this[k] = v;} }
1621
+ return this}
1622
+
1623
+
1624
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
1625
+ let klass = class extends this {};
1626
+ klass.prototype.mqtt_ctx =
1627
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
1628
+ return klass}
1629
+
1630
+
1631
+ async conn_emit(evt, arg, err_arg) {
1632
+ this.log_conn?.(evt, arg, err_arg);
1633
+ try {
1634
+ let fn_evt = this[await evt]; // microtask break using `await evt`
1635
+ if (fn_evt) {
1636
+ await fn_evt.call(this, this, arg, err_arg);}
1637
+ else if (err_arg) {throw err_arg} }
1638
+ catch (err) {
1639
+ this.on_error(err, evt);} }
1640
+
1641
+ on_error(err, evt) {
1642
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
1643
+ log_conn(evt, arg, err_arg) {
1644
+ console.info('[[u8-mqtt conn: %s]]', evt, arg, err_arg); }
1645
+
1646
+
1647
+ // automatic Client Id for connect()
1648
+ init_client_id(parts=['u8-mqtt--','']) {
1649
+ let sess_stg = this.sess_stg;
1650
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
1651
+ if (! cid) {
1652
+ cid = parts.join(Math.random().toString(36).slice(2));
1653
+ sess_stg?.setItem(key, cid);}
1654
+ return cid}
1655
+
1656
+
1657
+ on_live(client, is_reconnect) {
1658
+ if (is_reconnect) {
1659
+ return client.connect()} }
1660
+
1661
+ // on_ready(client) ::
1662
+ // on_reconnect(client) ::
1663
+ on_disconnect(client, intentional) {
1664
+ if (! intentional) {
1665
+ return client.on_reconnect?.()} }
1666
+
1667
+ _use_conn(fn_reconnect) {
1668
+ return (this.reconnect = fn_reconnect)?.()}
1669
+ with_autoreconnect(opt=2000) {
1670
+ if (opt.toFixed) {opt ={delay: opt};}
1671
+ return this.with({
1672
+ on_reconnect() {
1673
+ this.delay(opt.delay || 2000)
1674
+ .then(this.reconnect)
1675
+ .then(opt.reconnect, opt.error);} }) }
1676
+
1677
+ delay(ms) {
1678
+ return new Promise(done => setTimeout(done, ms)) }
1679
+
1680
+ with_async_iter(async_iter, write_u8_pkt) {
1681
+ this.conn.setup(async_iter,
1682
+ write_u8_pkt,
1683
+ async (on_mqtt_chunk, conn) => {
1684
+ try {
1685
+ async_iter = await async_iter;
1686
+ for await (let chunk of async_iter)
1687
+ on_mqtt_chunk(chunk);
1688
+ conn.reset();}
1689
+ catch (err) {
1690
+ conn.reset(err);} } );
1691
+ return this}
1692
+
1693
+
1694
+
1695
+
1696
+
1697
+
1698
+
1699
+
1700
+
1701
+
1702
+
1703
+
1704
+
1705
+
1706
+
1707
+
1708
+
1709
+
1710
+
1711
+
1712
+
1713
+
1714
+
1715
+
1716
+
1717
+
1718
+
1719
+
1720
+
1721
+
1722
+
1723
+
1724
+ with_tcp(...opt) {
1725
+ opt = this._conn_opt(opt);
1726
+ return this._use_conn (() =>
1727
+ this.with_stream(
1728
+ connect(opt)) ) }
1729
+
1730
+ with_tls(...opt) {
1731
+ opt = this._conn_opt(opt);
1732
+ return this._use_conn (() =>
1733
+ this.with_stream(
1734
+ connect$1(opt)) ) }
1735
+
1736
+ _conn_opt([a0, a1, a2]) {
1737
+ // (port, hostname, options) or (url, options)
1738
+ if (Number.isFinite(a0)) {
1739
+ return {...a2, port: a0, host: a1}}
1740
+ a0 = new URL(a0);
1741
+ return {...a1, port: a0.port, host: a0.hostname}}
1742
+
1743
+
1744
+ with_stream(read_stream, write_stream) {
1745
+ if (undefined === write_stream) {
1746
+ write_stream = read_stream;}
1747
+
1748
+ return this.with_async_iter(read_stream,
1749
+ u8_pkt => write_stream.write(u8_pkt)) }
1750
+
1751
+
1752
+ with_websock(websock) {
1753
+ if (! websock?.send) {
1754
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1755
+ return this._use_conn (() =>
1756
+ this.with_websock(
1757
+ new WebSocket(websock, ['mqtt'])) ) }
1758
+
1759
+ websock.binaryType = 'arraybuffer';
1760
+
1761
+ let ws_ready, readyState = websock.readyState;
1762
+ if (1 !== readyState) {
1763
+ if (0 !== readyState) {
1764
+ throw new Error('WS readyState') }
1765
+
1766
+ ws_ready = new Promise(ready => websock.onopen = ready); }
1767
+
1768
+ this.conn.setup(ws_ready,
1769
+ u8_pkt => websock.send(u8_pkt),
1770
+ (on_mqtt_chunk, conn) => {
1771
+ websock.onmessage = evt =>(
1772
+ on_mqtt_chunk(new Uint8Array(evt.data)) );
1773
+
1774
+ websock.onclose = evt => {
1775
+ if (! evt.wasClean) {
1776
+ var err = new Error('websocket close');
1777
+ err.code = evt.code;
1778
+ err.reason = evt.reason;}
1779
+
1780
+ conn.reset(err);}; } );
1781
+
1782
+ return this} }
1783
+
1784
+ const version = '0.6.0-node';
1785
+
1786
+ const MQTTClient_v4 = /* #__PURE__ */
1787
+ with_topic_path_router(
1788
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v5) );
1789
+
1790
+ const MQTTClient_v5 = /* #__PURE__ */
1791
+ with_topic_path_router(
1792
+ MQTTCore.mqtt_ctx(5, mqtt_opts_v5) );
1793
+
1794
+ const mqtt_v4 = opt =>
1795
+ new MQTTClient_v4(opt);
1796
+
1797
+ const mqtt_v5 = opt =>
1798
+ new MQTTClient_v5(opt);
1799
+
1800
+ export { MQTTClient_v5 as MQTTClient, MQTTClient_v4, MQTTClient_v5, mqtt_v5 as default, mqtt_v5 as mqtt, mqtt_v4, mqtt_v5, version };
1801
+ //# sourceMappingURL=full-v5.js.map