u8-mqtt 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +23 -6
  2. package/cjs/basic-v4.cjs +11 -8
  3. package/cjs/basic-v4.cjs.map +1 -1
  4. package/cjs/basic-v5.cjs +11 -8
  5. package/cjs/basic-v5.cjs.map +1 -1
  6. package/cjs/full-v4.cjs +1532 -0
  7. package/cjs/full-v4.cjs.map +1 -0
  8. package/cjs/full-v5.cjs +1796 -0
  9. package/cjs/full-v5.cjs.map +1 -0
  10. package/cjs/index.cjs +11 -8
  11. package/cjs/index.cjs.map +1 -1
  12. package/cjs/v4.cjs +11 -8
  13. package/cjs/v4.cjs.map +1 -1
  14. package/cjs/v5.cjs +11 -8
  15. package/cjs/v5.cjs.map +1 -1
  16. package/code/base.jsy +2 -2
  17. package/code/core.jsy +5 -5
  18. package/code/full-v4.js +20 -0
  19. package/code/full-v5.js +29 -0
  20. package/esm/basic-v4.js +11 -8
  21. package/esm/basic-v4.js.map +1 -1
  22. package/esm/basic-v5.js +11 -8
  23. package/esm/basic-v5.js.map +1 -1
  24. package/esm/deno/basic-v4.js +11 -8
  25. package/esm/deno/basic-v4.js.map +1 -1
  26. package/esm/deno/basic-v5.js +11 -8
  27. package/esm/deno/basic-v5.js.map +1 -1
  28. package/esm/deno/full-v4.js +1520 -0
  29. package/esm/deno/full-v4.js.map +1 -0
  30. package/esm/deno/full-v5.js +1782 -0
  31. package/esm/deno/full-v5.js.map +1 -0
  32. package/esm/deno/index.js +11 -8
  33. package/esm/deno/index.js.map +1 -1
  34. package/esm/deno/v4.js +11 -8
  35. package/esm/deno/v4.js.map +1 -1
  36. package/esm/deno/v5.js +11 -8
  37. package/esm/deno/v5.js.map +1 -1
  38. package/esm/full-v4.js +1520 -0
  39. package/esm/full-v4.js.map +1 -0
  40. package/esm/full-v5.js +1782 -0
  41. package/esm/full-v5.js.map +1 -0
  42. package/esm/index.js +11 -8
  43. package/esm/index.js.map +1 -1
  44. package/esm/node/basic-v4.js +11 -8
  45. package/esm/node/basic-v4.js.map +1 -1
  46. package/esm/node/basic-v4.mjs +11 -8
  47. package/esm/node/basic-v4.mjs.map +1 -1
  48. package/esm/node/basic-v5.js +11 -8
  49. package/esm/node/basic-v5.js.map +1 -1
  50. package/esm/node/basic-v5.mjs +11 -8
  51. package/esm/node/basic-v5.mjs.map +1 -1
  52. package/esm/node/full-v4.js +1523 -0
  53. package/esm/node/full-v4.js.map +1 -0
  54. package/esm/node/full-v4.mjs +1523 -0
  55. package/esm/node/full-v4.mjs.map +1 -0
  56. package/esm/node/full-v5.js +1785 -0
  57. package/esm/node/full-v5.js.map +1 -0
  58. package/esm/node/full-v5.mjs +1785 -0
  59. package/esm/node/full-v5.mjs.map +1 -0
  60. package/esm/node/index.js +11 -8
  61. package/esm/node/index.js.map +1 -1
  62. package/esm/node/index.mjs +11 -8
  63. package/esm/node/index.mjs.map +1 -1
  64. package/esm/node/v4.js +11 -8
  65. package/esm/node/v4.js.map +1 -1
  66. package/esm/node/v4.mjs +11 -8
  67. package/esm/node/v4.mjs.map +1 -1
  68. package/esm/node/v5.js +11 -8
  69. package/esm/node/v5.js.map +1 -1
  70. package/esm/node/v5.mjs +11 -8
  71. package/esm/node/v5.mjs.map +1 -1
  72. package/esm/v4.js +11 -8
  73. package/esm/v4.js.map +1 -1
  74. package/esm/v5.js +11 -8
  75. package/esm/v5.js.map +1 -1
  76. package/esm/web/basic-v4.js +11 -8
  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 +11 -8
  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 +1520 -0
  87. package/esm/web/full-v4.js.map +1 -0
  88. package/esm/web/full-v4.min.js +1 -0
  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 +1782 -0
  92. package/esm/web/full-v5.js.map +1 -0
  93. package/esm/web/full-v5.min.js +1 -0
  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 +11 -8
  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 +11 -8
  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 +11 -8
  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 +3 -3
@@ -0,0 +1,1520 @@
1
+ function encode_varint(n, a=[]) {
2
+ do {
3
+ const ni = n & 0x7f;
4
+ n >>>= 7;
5
+ a.push( ni | (0===n ? 0 : 0x80) );
6
+ } while (n > 0)
7
+ return a
8
+ }
9
+
10
+
11
+ /*
12
+ export function decode_varint_loop(u8, i=0) {
13
+ let i0 = i
14
+ let shift = 0, n = (u8[i] & 0x7f)
15
+ while ( 0x80 & u8[i++] )
16
+ n |= (u8[i] & 0x7f) << (shift += 7)
17
+
18
+ return [n, i, i0]
19
+ }
20
+ */
21
+
22
+
23
+ function decode_varint$1(u8, i=0) {
24
+ let i0 = i;
25
+ // unrolled for a max of 4 chains
26
+ let n = (u8[i] & 0x7f) << 0;
27
+ if ( 0x80 & u8[i++] ) {
28
+ n |= (u8[i] & 0x7f) << 7;
29
+ if ( 0x80 & u8[i++] ) {
30
+ n |= (u8[i] & 0x7f) << 14;
31
+ if ( 0x80 & u8[i++] ) {
32
+ n |= (u8[i] & 0x7f) << 21;
33
+ }
34
+ }
35
+ }
36
+ return [n, i, i0]
37
+ }
38
+
39
+ class U8_Reason extends Number {
40
+ static of(v, pkt_kind, by_kind) {
41
+ let self = new this(v);
42
+ self.reason = by_kind?.[pkt_kind]?.get(v) || pkt_kind;
43
+ return self
44
+ }
45
+ }
46
+
47
+ let mqtt_reader_v4$1 = class mqtt_reader_v4 {
48
+ static of(buf) { return this.prototype.of(buf) }
49
+ of(buf) {
50
+ let step = (width, k) => (k=0|step.k, step.k=k+width, k);
51
+ return {__proto__: this, buf, step}
52
+ }
53
+
54
+ has_more() {
55
+ return this.buf.byteLength > (this.step.k|0)
56
+ }
57
+
58
+ u8() {
59
+ return this.buf[this.step(1)]
60
+ }
61
+
62
+ u16() {
63
+ let {buf, step} = this, i = step(2);
64
+ return (buf[i]<<8) | buf[i+1]
65
+ }
66
+
67
+ u32() {
68
+ let {buf, step} = this, i = step(4);
69
+ return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3]
70
+ }
71
+
72
+ vint() {
73
+ let {buf, step} = this;
74
+ let [n, vi, vi0] = decode_varint$1(buf, step.k|0);
75
+ step(vi - vi0);
76
+ return n
77
+ }
78
+
79
+ bin() {
80
+ let {buf, step} = this, i = step(2);
81
+ let len = (buf[i]<<8) | buf[i+1];
82
+ i = step(len);
83
+ return buf.subarray(i, i+len)
84
+ }
85
+
86
+ utf8() { return new TextDecoder('utf-8').decode(this.bin()) }
87
+ pair() { return [ this.utf8(), this.utf8() ] }
88
+
89
+ flags(FlagsType) { return new FlagsType(this.buf[this.step(1)]) }
90
+
91
+ reason(pkt_kind) {
92
+ let v = this.buf[this.step(1)];
93
+ if (null != v)
94
+ return U8_Reason.of(v, pkt_kind, this._reasons_by)
95
+ }
96
+
97
+ flush() {
98
+ let {buf, step} = this;
99
+ this.step = this.buf = null;
100
+ return buf.subarray(step.k|0)
101
+ }
102
+
103
+ };
104
+
105
+ function mqtt_reader_info(mqtt_reader, ... info_fn_list) {
106
+ mqtt_reader = class extends mqtt_reader {
107
+ static reasons(pkt_type, ...reason_entries) {
108
+ let proto = this.prototype;
109
+ proto._reasons_by = {... proto._reasons_by};
110
+
111
+ let lut = (proto._reasons_by[pkt_type] ||= new Map());
112
+ for (let [u8, reason] of reason_entries)
113
+ lut.set( u8, reason );
114
+
115
+ return this
116
+ }
117
+ };
118
+
119
+ for (let fn_info of info_fn_list)
120
+ fn_info(mqtt_reader);
121
+
122
+ return mqtt_reader
123
+ }
124
+
125
+ class mqtt_writer_v4 {
126
+ static of() { return this.prototype.of() }
127
+ of() { return {__proto__: this, $:[]} }
128
+
129
+ static init() { return this }
130
+
131
+ as_pkt(pkt_id) { return this.pack([pkt_id]) }
132
+
133
+ push(...z) { this.$.push(...z); }
134
+ pack(hdr) {
135
+ let z, i, n=0, parts = this.$;
136
+ this.$ = false;
137
+ for (z of parts) n += z.length;
138
+
139
+ hdr = encode_varint(n, hdr);
140
+ i = hdr.length;
141
+
142
+ let pkt = new Uint8Array(i + n);
143
+ pkt.set(hdr, 0);
144
+ for (z of parts) {
145
+ pkt.set(z, i);
146
+ i += z.length;
147
+ }
148
+ return pkt
149
+ }
150
+
151
+ u8(v) { this.push([ v & 0xff ]); }
152
+ u16(v) { this.push([ (v>>>8) & 0xff, v & 0xff ]); }
153
+ u32(v) { this.push([ (v>>>24) & 0xff, (v>>>16) & 0xff, (v>>>8) & 0xff, v & 0xff ]); }
154
+ vint(v) { this.push( encode_varint(v) );}
155
+
156
+ bin(u8_buf) {
157
+ if (! u8_buf) return this.u16(0)
158
+ if ('string' === typeof u8_buf)
159
+ return this.utf8(u8_buf)
160
+
161
+ if (u8_buf.length !== u8_buf.byteLength)
162
+ u8_buf = new Uint8Array(u8_buf);
163
+
164
+ this.u16(u8_buf.byteLength);
165
+ this.push(u8_buf);
166
+ }
167
+
168
+ utf8(v) {
169
+ let u8_buf = new TextEncoder('utf-8').encode(v);
170
+ this.u16(u8_buf.byteLength);
171
+ this.push(u8_buf);
172
+ }
173
+ pair(k,v) { this.utf8(k); this.utf8(v); }
174
+
175
+ flags(v, enc_flags, b0=0) {
176
+ if (undefined !== v && isNaN(+v))
177
+ v = enc_flags(v, 0);
178
+
179
+ v |= b0;
180
+ this.push([v]);
181
+ return v
182
+ }
183
+
184
+ reason(v) { this.push([v | 0]); }
185
+
186
+ flush(buf) {
187
+ if (null != buf)
188
+ this.push(
189
+ 'string' === typeof buf
190
+ ? new TextEncoder('utf-8').encode(buf)
191
+ : buf );
192
+
193
+ this.push = false;
194
+ }
195
+ }
196
+
197
+ function mqtt_decode_connect(ns, mqtt_reader) {
198
+ class _connect_flags_ extends Number {
199
+ get reserved() { return this & 0x01 !== 0 }
200
+ get clean_start() { return this & 0x02 !== 0 }
201
+ get will_flag() { return this & 0x04 !== 0 }
202
+ get will_qos() { return (this >>> 3) & 0x3 }
203
+ get will_retain() { return this & 0x20 !== 0 }
204
+ get password() { return this & 0x40 !== 0 }
205
+ get username() { return this & 0x80 !== 0 }
206
+ }
207
+
208
+ return ns[0x1] = (pkt, u8_body) => {
209
+ let rdr = mqtt_reader.of(u8_body);
210
+ if ('MQTT' !== rdr.utf8())
211
+ throw new Error('Invalid mqtt_connect packet')
212
+
213
+ pkt._base_.mqtt_level = pkt.mqtt_level = rdr.u8();
214
+
215
+ let flags = pkt.flags =
216
+ rdr.flags(_connect_flags_);
217
+
218
+ pkt.keep_alive = rdr.u16();
219
+
220
+ if (5 <= pkt.mqtt_level)
221
+ pkt.props = rdr.props();
222
+
223
+
224
+
225
+ pkt.client_id = rdr.utf8();
226
+ if (flags.will_flag) {
227
+ let will = pkt.will = {};
228
+ if (5 <= pkt.mqtt_level)
229
+ will.props = rdr.props();
230
+
231
+ will.topic = rdr.utf8();
232
+ will.payload = rdr.bin();
233
+ will.qos = flags.will_qos;
234
+ will.retain = flags.will_retain;
235
+ }
236
+
237
+ if (flags.username)
238
+ pkt.username = rdr.utf8();
239
+
240
+ if (flags.password)
241
+ pkt.password = rdr.bin();
242
+ return pkt }
243
+ }
244
+
245
+ function mqtt_decode_connack(ns, mqtt_reader) {
246
+ class _connack_flags_ extends Number {
247
+ get session_present() { return this & 0x01 !== 0 }
248
+ }
249
+
250
+ return ns[0x2] = (pkt, u8_body) => {
251
+ let rdr = mqtt_reader.of(u8_body);
252
+
253
+ pkt.flags =
254
+ rdr.flags(_connack_flags_);
255
+
256
+ pkt.reason = rdr.reason(pkt.type);
257
+ if (5 <= pkt.mqtt_level)
258
+ pkt.props = rdr.props();
259
+ return pkt }
260
+ }
261
+
262
+
263
+ function _connack_v4(mqtt_reader) {
264
+ mqtt_reader.reasons('connack',
265
+ // MQTT 3.1.1
266
+ [ 0x00, 'Success'],
267
+ [ 0x01, 'Connection refused, unacceptable protocol version'],
268
+ [ 0x02, 'Connection refused, identifier rejected'],
269
+ [ 0x03, 'Connection refused, server unavailable'],
270
+ [ 0x04, 'Connection refused, bad user name or password'],
271
+ [ 0x05, 'Connection refused, not authorized'],
272
+ );
273
+ }
274
+
275
+ function mqtt_decode_publish(ns, mqtt_reader) {
276
+ return ns[0x3] = (pkt, u8_body) => {
277
+ let {hdr} = pkt;
278
+ pkt.dup = Boolean(hdr & 0x8);
279
+ pkt.retain = Boolean(hdr & 0x1);
280
+ let qos = pkt.qos = (hdr>>1) & 0x3;
281
+
282
+ let rdr = mqtt_reader.of(u8_body);
283
+ pkt.topic = rdr.utf8();
284
+ if (0 !== qos)
285
+ pkt.pkt_id = rdr.u16();
286
+
287
+ if (5 <= pkt.mqtt_level)
288
+ pkt.props = rdr.props();
289
+
290
+ pkt.payload = rdr.flush();
291
+ return pkt }
292
+ }
293
+
294
+ function mqtt_decode_puback(ns, mqtt_reader) {
295
+ return ns[0x4] = (pkt, u8_body) => {
296
+ let rdr = mqtt_reader.of(u8_body);
297
+
298
+ pkt.pkt_id = rdr.u16();
299
+ if (5 <= pkt.mqtt_level) {
300
+ pkt.reason = rdr.reason(pkt.type);
301
+ pkt.props = rdr.props();
302
+ }
303
+
304
+ return pkt }
305
+ }
306
+
307
+ function mqtt_decode_pubxxx(ns, mqtt_reader) {
308
+ return ns[0x5] = ns[0x6] = ns[0x7] = (pkt, u8_body) => {
309
+ let rdr = mqtt_reader.of(u8_body);
310
+
311
+ pkt.pkt_id = rdr.u16();
312
+ pkt.reason = rdr.reason('pubxxx', mqtt_reader);
313
+ if (5 <= pkt.mqtt_level)
314
+ pkt.props = rdr.props();
315
+ return pkt }
316
+ }
317
+
318
+ function _pubxxx_v4(mqtt_reader) {
319
+ mqtt_reader.reasons('pubxxx',
320
+ // MQTT 3.1.1
321
+ [ 0x00, 'Success' ],
322
+ [ 0x92, 'Packet Identifier not found' ],
323
+ );
324
+ }
325
+
326
+ function mqtt_decode_subscribe(ns, mqtt_reader) {
327
+ class _subscription_options_ extends Number {
328
+ get qos() { return this & 0x3 }
329
+ get retain() { return this & 0x4 !== 0 }
330
+ get retain_handling() { return (this >> 2) & 0x3 }
331
+ }
332
+
333
+ return ns[0x8] = (pkt, u8_body) => {
334
+ let rdr = mqtt_reader.of(u8_body);
335
+
336
+ pkt.pkt_id = rdr.u16();
337
+ if (5 <= pkt.mqtt_level)
338
+ pkt.props = rdr.props();
339
+
340
+ let topic, opts, topic_list = pkt.topics = [];
341
+ while (rdr.has_more()) {
342
+ topic = rdr.utf8();
343
+ opts = rdr.flags(_subscription_options_);
344
+ topic_list.push({topic, opts});
345
+ }
346
+
347
+ return pkt }
348
+ }
349
+
350
+ function _mqtt_decode_suback(mqtt_reader) {
351
+ return (pkt, u8_body) => {
352
+ let rdr = mqtt_reader.of(u8_body);
353
+
354
+ pkt.pkt_id = rdr.u16();
355
+ if (5 <= pkt.mqtt_level)
356
+ pkt.props = rdr.props();
357
+
358
+ let answers = pkt.answers = [];
359
+ while (rdr.has_more())
360
+ answers.push(
361
+ rdr.reason(pkt.type) );
362
+
363
+ return pkt }
364
+ }
365
+
366
+ function mqtt_decode_suback(ns, mqtt_reader) {
367
+ return ns[0x9] = _mqtt_decode_suback(mqtt_reader)
368
+ }
369
+
370
+ function _suback_v4(mqtt_reader) {
371
+ mqtt_reader.reasons('suback',
372
+ // MQTT 3.1.1
373
+ [ 0x00, 'Granted QoS 0'],
374
+ [ 0x01, 'Granted QoS 1'],
375
+ [ 0x02, 'Granted QoS 2'],
376
+ );
377
+ }
378
+
379
+ function mqtt_decode_unsubscribe(ns, mqtt_reader) {
380
+ return ns[0xa] = (pkt, u8_body) => {
381
+ let rdr = mqtt_reader.of(u8_body);
382
+
383
+ pkt.pkt_id = rdr.u16();
384
+ if (5 <= pkt.mqtt_level)
385
+ pkt.props = rdr.props();
386
+
387
+ let topic_list = pkt.topics = [];
388
+ while (rdr.has_more())
389
+ topic_list.push(rdr.utf8());
390
+
391
+ return pkt }
392
+ }
393
+
394
+ function mqtt_decode_unsuback(ns, mqtt_reader) {
395
+ return ns[0xb] = _mqtt_decode_suback(mqtt_reader)
396
+ }
397
+
398
+ function _unsuback_v4(mqtt_reader) {
399
+ mqtt_reader.reasons('unsuback',
400
+ // MQTT 3.1.1
401
+ [ 0x00, 'Success'],
402
+ [ 0x11, 'No subscription existed'],
403
+ [ 0x80, 'Unspecified error'],
404
+ [ 0x83, 'Implementation specific error'],
405
+ [ 0x87, 'Not authorized'],
406
+ [ 0x8F, 'Topic Filter invalid'],
407
+ [ 0x91, 'Packet Identifier in use'],
408
+ );
409
+ }
410
+
411
+ function mqtt_decode_pingxxx(ns) {
412
+ return ns[0xc] = ns[0xd] = pkt => pkt
413
+ }
414
+
415
+ function mqtt_decode_disconnect(ns, mqtt_reader) {
416
+ return ns[0xe] = (pkt, u8_body) => {
417
+ if (u8_body && 5 <= pkt.mqtt_level) {
418
+ let rdr = mqtt_reader.of(u8_body);
419
+ pkt.reason = rdr.reason(pkt.type);
420
+ pkt.props = rdr.props();
421
+ }
422
+ return pkt }
423
+ }
424
+
425
+ function mqtt_encode_connect(ns, mqtt_writer) {
426
+ const _c_mqtt_proto = new Uint8Array([
427
+ 0, 4, 0x4d, 0x51, 0x54, 0x54 ]);
428
+
429
+ const _enc_flags_connect = flags => 0
430
+ | ( flags.reserved ? 0x01 : 0 )
431
+ | ( (flags.will_qos & 0x3) << 3 )
432
+ | ( flags.clean_start ? 0x02 : 0 )
433
+ | ( flags.will_flag ? 0x04 : 0 )
434
+ | ( flags.will_retain ? 0x20 : 0 )
435
+ | ( flags.password ? 0x40 : 0 )
436
+ | ( flags.username ? 0x80 : 0 );
437
+
438
+ const _enc_flags_will = will => 0x4
439
+ | ( (will.qos & 0x3) << 3 )
440
+ | ( will.retain ? 0x20 : 0 );
441
+
442
+ return ns.connect = ( mqtt_level, pkt ) => {
443
+ let wrt = mqtt_writer.of(pkt);
444
+
445
+ wrt.push(_c_mqtt_proto);
446
+ wrt.u8( mqtt_level );
447
+
448
+ let {will, username, password} = pkt;
449
+ let flags = wrt.flags(
450
+ pkt.flags,
451
+ _enc_flags_connect,
452
+ 0 | (username ? 0x80 : 0)
453
+ | (password ? 0x40 : 0)
454
+ | (will ? _enc_flags_will(will) : 0) );
455
+
456
+ wrt.u16(pkt.keep_alive);
457
+
458
+ if (5 <= mqtt_level)
459
+ wrt.props(pkt.props);
460
+
461
+
462
+ wrt.utf8(pkt.client_id);
463
+ if (flags & 0x04) { // .will_flag
464
+ if (5 <= mqtt_level)
465
+ wrt.props(will.props);
466
+
467
+ wrt.utf8(will.topic);
468
+ wrt.bin(will.payload);
469
+ }
470
+
471
+ if (flags & 0x80) // .username
472
+ wrt.utf8(username);
473
+
474
+ if (flags & 0x40) // .password
475
+ wrt.bin(password);
476
+
477
+ return wrt.as_pkt(0x10)
478
+ }
479
+ }
480
+
481
+ function mqtt_encode_connack(ns, mqtt_writer) {
482
+ const _enc_flags_connack = flags =>
483
+ flags.session_present ? 1 : 0;
484
+
485
+ return ns.connack = (mqtt_level, pkt) => {
486
+ let wrt = mqtt_writer.of(pkt);
487
+
488
+ wrt.flags( pkt.flags, _enc_flags_connack );
489
+
490
+ if (5 <= mqtt_level) {
491
+ wrt.reason( pkt.reason );
492
+ wrt.props( pkt.props );
493
+
494
+ } else {
495
+ wrt.reason( pkt.return_code || pkt.reason );
496
+ }
497
+
498
+ return wrt.as_pkt(0x20)
499
+ }
500
+ }
501
+
502
+ function mqtt_encode_publish(ns, mqtt_writer) {
503
+ return ns.publish = ( mqtt_level, pkt ) => {
504
+ let qos = (pkt.qos & 0x3) << 1;
505
+ let wrt = mqtt_writer.of(pkt);
506
+
507
+ wrt.utf8(pkt.topic);
508
+ if (0 !== qos)
509
+ wrt.u16(pkt.pkt_id);
510
+
511
+ if ( 5 <= mqtt_level) {
512
+ wrt.props(pkt.props);
513
+ wrt.flush(pkt.payload);
514
+ } else {
515
+ wrt.flush(pkt.payload);
516
+ }
517
+
518
+ return wrt.as_pkt(
519
+ 0x30 | qos | (pkt.dup ? 0x8 : 0) | (pkt.retain ? 0x1 : 0) )
520
+ }
521
+ }
522
+
523
+ function mqtt_encode_puback(ns, mqtt_writer) {
524
+ return ns.puback = ( mqtt_level, pkt ) => {
525
+ let wrt = mqtt_writer.of(pkt);
526
+
527
+ wrt.u16(pkt.pkt_id);
528
+ if (5 <= mqtt_level) {
529
+ wrt.reason(pkt.reason);
530
+ wrt.props(pkt.props);
531
+ }
532
+
533
+ return wrt.as_pkt(0x40)
534
+ }
535
+ }
536
+
537
+ function mqtt_encode_pubxxx(ns, mqtt_writer) {
538
+ ns.pubrec = _enc_pubxxx(0x50);
539
+ ns.pubrel = _enc_pubxxx(0x62);
540
+ ns.pubcomp = _enc_pubxxx(0x70);
541
+
542
+
543
+ function _enc_pubxxx(hdr) {
544
+ return ( mqtt_level, pkt ) => {
545
+ let wrt = mqtt_writer.of(pkt);
546
+
547
+ wrt.u16(pkt.pkt_id);
548
+ if (5 <= mqtt_level) {
549
+ wrt.props(pkt.props);
550
+ wrt.reason(pkt.reason);
551
+
552
+ } else {
553
+ wrt.reason( pkt.return_code || pkt.reason );
554
+ }
555
+
556
+ return wrt.as_pkt(hdr)
557
+ }
558
+ }
559
+ }
560
+
561
+ function mqtt_encode_subscribe(ns, mqtt_writer) {
562
+ const _enc_subscribe_flags = opts => 0
563
+ | ( opts.qos & 0x3 )
564
+ | ( opts.retain ? 0x4 : 0 )
565
+ | ( (opts.retain_handling & 0x3) << 2 );
566
+
567
+ return ns.subscribe = ( mqtt_level, pkt ) => {
568
+ let wrt = mqtt_writer.of(pkt);
569
+
570
+ wrt.u16(pkt.pkt_id);
571
+ if (5 <= mqtt_level)
572
+ wrt.props(pkt.props);
573
+
574
+ let f0 = _enc_subscribe_flags(pkt);
575
+ for (let each of pkt.topics) {
576
+ if ('string' === typeof each) {
577
+ wrt.utf8(each);
578
+ wrt.u8(f0);
579
+ } else {
580
+ let [topic, opts] =
581
+ Array.isArray(each) ? each
582
+ : [each.topic, each.opts];
583
+
584
+ wrt.utf8(topic);
585
+ if (undefined === opts) wrt.u8(f0);
586
+ else wrt.flags(opts, _enc_subscribe_flags);
587
+ }
588
+ }
589
+
590
+ return wrt.as_pkt(0x82)
591
+ }
592
+ }
593
+
594
+ function mqtt_encode_xxsuback(ns, mqtt_writer) {
595
+ ns.suback = _enc_xxsuback(0x90);
596
+ ns.unsuback = _enc_xxsuback(0xb0);
597
+
598
+
599
+ function _enc_xxsuback(hdr) {
600
+ return ( mqtt_level, pkt ) => {
601
+ let wrt = mqtt_writer.of(pkt);
602
+
603
+ wrt.u16(pkt.pkt_id);
604
+ if (5 <= mqtt_level)
605
+ wrt.props(pkt.props);
606
+
607
+ for (let ans of pkt.answers)
608
+ wrt.reason(ans);
609
+
610
+ return wrt.as_pkt(hdr)
611
+ }
612
+ }
613
+ }
614
+
615
+ function mqtt_encode_unsubscribe(ns, mqtt_writer) {
616
+ return ns.unsubscribe = ( mqtt_level, pkt ) => {
617
+ let wrt = mqtt_writer.of(pkt);
618
+
619
+ wrt.u16(pkt.pkt_id);
620
+ if (5 <= mqtt_level)
621
+ wrt.props(pkt.props);
622
+
623
+ for (let topic of pkt.topics)
624
+ wrt.utf8(topic);
625
+
626
+ return wrt.as_pkt(0xa2)
627
+ }
628
+ }
629
+
630
+ function mqtt_encode_pingxxx(ns) {
631
+ ns.pingreq = () => new Uint8Array([ 0xc0, 0 ]);
632
+ ns.pingresp = () => new Uint8Array([ 0xd0, 0 ]);
633
+ }
634
+
635
+ function mqtt_encode_disconnect(ns, mqtt_writer) {
636
+ return ns.disconnect = ( mqtt_level, pkt ) => {
637
+ let wrt = mqtt_writer.of(pkt);
638
+
639
+ if (pkt && 5 <= mqtt_level) {
640
+ if (pkt.reason || pkt.props) {
641
+ wrt.reason(pkt.reason);
642
+ wrt.props(pkt.props);
643
+ }
644
+ }
645
+
646
+ return wrt.as_pkt(0xe0)
647
+ }
648
+ }
649
+
650
+ // not a v4 packet: import { mqtt_encode_auth } from './encode/auth.js'
651
+
652
+
653
+ const mqtt_reader_v4 = /* #__PURE__ */
654
+ mqtt_reader_info(
655
+ mqtt_reader_v4$1,
656
+ _connack_v4,
657
+ _pubxxx_v4,
658
+ _suback_v4,
659
+ _unsuback_v4,
660
+ );
661
+
662
+ const mqtt_decode_v4 = [
663
+ mqtt_decode_connect,
664
+ mqtt_decode_connack,
665
+ mqtt_decode_publish,
666
+ mqtt_decode_puback,
667
+ mqtt_decode_pubxxx,
668
+ mqtt_decode_subscribe,
669
+ mqtt_decode_suback,
670
+ mqtt_decode_unsubscribe,
671
+ mqtt_decode_unsuback,
672
+ mqtt_decode_pingxxx,
673
+ mqtt_decode_disconnect,
674
+ ];
675
+
676
+
677
+ const mqtt_encode_v4 = [
678
+ mqtt_encode_connect,
679
+ mqtt_encode_connack,
680
+ mqtt_encode_publish,
681
+ mqtt_encode_puback,
682
+ mqtt_encode_pubxxx,
683
+ mqtt_encode_subscribe,
684
+ mqtt_encode_xxsuback,
685
+ mqtt_encode_unsubscribe,
686
+ mqtt_encode_pingxxx,
687
+ mqtt_encode_disconnect,
688
+ ];
689
+
690
+
691
+ const mqtt_opts_v4 =
692
+ { decode_fns: mqtt_decode_v4,
693
+ mqtt_reader: mqtt_reader_v4,
694
+ encode_fns: mqtt_encode_v4,
695
+ mqtt_writer: mqtt_writer_v4, };
696
+
697
+ function parse(str, loose) {
698
+ if (str instanceof RegExp) return { keys:false, pattern:str };
699
+ var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
700
+ arr[0] || arr.shift();
701
+
702
+ while (tmp = arr.shift()) {
703
+ c = tmp[0];
704
+ if (c === '*') {
705
+ keys.push('wild');
706
+ pattern += '/(.*)';
707
+ } else if (c === ':') {
708
+ o = tmp.indexOf('?', 1);
709
+ ext = tmp.indexOf('.', 1);
710
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
711
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
712
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
713
+ } else {
714
+ pattern += '/' + tmp;
715
+ }
716
+ }
717
+
718
+ return {
719
+ keys: keys,
720
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
721
+ };
722
+ }
723
+
724
+ /*
725
+ class AbstractTopicRouter ::
726
+ async invoke(pkt, ctx) ::
727
+ add(topic_route, ...args) ::
728
+ remove(topic_route, priority) ::
729
+ clear(priority) ::
730
+ find(topic) :: // optional
731
+ mqtt_topic(topic_route)
732
+ */
733
+
734
+ const with_topic_router = mqtt_topic_router =>
735
+ MQTTKlass => class extends MQTTKlass {
736
+ static _aliases() {
737
+ return super._aliases() +
738
+ ' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
739
+
740
+ _init_router(opt, self, target) {
741
+ this._subs = [];
742
+ let router = this.router = target.router =
743
+ mqtt_topic_router(opt, this, target);
744
+ return router?.invoke}
745
+
746
+ on_sub(suback, pkt) {
747
+ suback.pkt = pkt;
748
+ this._subs.push(suback);
749
+ return suback}
750
+ subs_settled() {
751
+ return Promise.allSettled(
752
+ this._subs.splice(0,Infinity)) }
753
+
754
+ // alias: sub_topic
755
+ subscribe_topic(topic_route, ...args) {
756
+ let router = this.router;
757
+ router.add(topic_route, true, args.pop() );// handler
758
+ let topic = router.mqtt_topic(topic_route);
759
+ this.subscribe(topic, ...args );// ex, topic_prefix
760
+ return this }// fluent api -- return this and track side effects
761
+
762
+ // alias: unsub_topic
763
+ unsubscribe_topic(topic_route, ...args) {
764
+ let router = this.router;
765
+ router.remove(topic_route, true);
766
+ let topic = router.mqtt_topic(topic_route);
767
+ return this.unsubscribe(topic, ...args ) }// topic_prefix
768
+
769
+ // add topic handlers without corresponding subscribe packet
770
+ on_topic(...args) {
771
+ this.router.add(...args);
772
+ return this} };
773
+
774
+ // Use [regexparam][] for url-like topic parsing
775
+ // [regexparam]: https://github.com/lukeed/regexparam
776
+
777
+
778
+ const with_topic_path_router = /* #__PURE__ */
779
+ with_topic_router(mqtt_topic_path_router);
780
+
781
+
782
+ const mqtt_topic = topic_route =>
783
+ topic_route
784
+ .replace(/[*].*$/, '#')
785
+ .replace(/:\w[^\/]*/g, '+');
786
+
787
+ /* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
788
+ 4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
789
+ ... MUST be specified either on its own or following a topic level separator.
790
+ In either case it MUST be the last character specified in the Topic Filter
791
+
792
+ 4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
793
+ ...it MUST occupy an entire level of the filter.
794
+ */
795
+
796
+ const as_topic_path = (topic_route, id) =>(
797
+ id=1,
798
+ topic_route
799
+ .replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
800
+ .replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
801
+
802
+ function _ignore(pkt, params, ctx) {ctx.done = true;}
803
+
804
+ function mqtt_topic_path_router() {
805
+ let pri_lsts = [[],[]], rm = Symbol();
806
+ let find = topic => _routes_iter(pri_lsts, topic);
807
+
808
+ // return duck-type compatible with AbstractTopicRouter in ./with_topic_router
809
+ return {find, mqtt_topic,
810
+ add(topic_route, ...args) {
811
+ let fn = args.pop();
812
+ let priority = args.pop();
813
+
814
+ if ('function' !== typeof fn) {
815
+ if (fn) {throw new TypeError()}
816
+ fn = _ignore;}
817
+
818
+ let rte = parse(as_topic_path(topic_route));
819
+
820
+ rte.key = topic_route;
821
+ rte.tgt = fn;
822
+ pri_lsts[priority ? 0 : 1].push(rte);
823
+ return this}
824
+
825
+ , remove(topic_route, priority) {
826
+ let lst = pri_lsts[priority ? 0 : 1];
827
+ return _route_remove([lst], topic_route)}
828
+
829
+ , clear(priority) {
830
+ pri_lsts[priority ? 0 : 1] = [];
831
+ if (null == priority) {
832
+ pri_lsts[1] = []; } }// null clears both lists
833
+
834
+ , async invoke(pkt, ctx) {
835
+ ctx.idx = 0;
836
+ ctx.rm = rm;
837
+
838
+ for (let [fn, params] of find(pkt.topic)) {
839
+ let res = await fn(pkt, params, ctx);
840
+
841
+ if (rm === res) {
842
+ _route_remove(pri_lsts, fn);}
843
+
844
+ if (ctx.done) {
845
+ break}
846
+ else ctx.idx++;}
847
+
848
+ if (1 === pkt.qos) {
849
+ await ctx.mqtt.puback(pkt);} } } }
850
+
851
+
852
+ function * _routes_iter(all_route_lists, topic) {
853
+ topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
854
+ for (let route_list of all_route_lists) {
855
+ for (let {keys, pattern, tgt} of route_list) {
856
+ let match = pattern.exec(topic);
857
+ if (match) {
858
+ let params = keys
859
+ ? keys.reduce(
860
+ (o, k, i) => (o[k] = match[1+i], o)
861
+ , {})
862
+ : match.groups ?? match;
863
+ yield [tgt, params];} } } }
864
+
865
+
866
+ function _route_remove(all_route_lists, query) {
867
+ let fn_match = route =>(
868
+ route===query
869
+ || route.tgt===query
870
+ || route.key===query);
871
+ for (let lst of all_route_lists) {
872
+ let i = lst.findIndex(fn_match);
873
+ if (0 <= i) {
874
+ lst.splice(i,1);
875
+ return true} }
876
+ return false}
877
+
878
+ /*
879
+ export function decode_varint_loop(u8, i=0) {
880
+ let i0 = i
881
+ let shift = 0, n = (u8[i] & 0x7f)
882
+ while ( 0x80 & u8[i++] )
883
+ n |= (u8[i] & 0x7f) << (shift += 7)
884
+
885
+ return [n, i, i0]
886
+ }
887
+ */
888
+
889
+
890
+ function decode_varint(u8, i=0) {
891
+ let i0 = i;
892
+ // unrolled for a max of 4 chains
893
+ let n = (u8[i] & 0x7f) << 0;
894
+ if ( 0x80 & u8[i++] ) {
895
+ n |= (u8[i] & 0x7f) << 7;
896
+ if ( 0x80 & u8[i++] ) {
897
+ n |= (u8[i] & 0x7f) << 14;
898
+ if ( 0x80 & u8[i++] ) {
899
+ n |= (u8[i] & 0x7f) << 21;
900
+ }
901
+ }
902
+ }
903
+ return [n, i, i0]
904
+ }
905
+
906
+ function mqtt_raw_dispatch(opt) {
907
+ let u8 = new Uint8Array(0);
908
+ return u8_buf => {
909
+ u8 = 0 === u8.byteLength
910
+ ? u8_buf : _u8_join(u8, u8_buf);
911
+
912
+ let res = [];
913
+ while (1) {
914
+ let [len_body, len_vh] = decode_varint(u8, 1);
915
+ let len_pkt = len_body + len_vh;
916
+
917
+ if ( u8.byteLength < len_pkt )
918
+ return res
919
+
920
+ let b0 = u8[0];
921
+ let u8_body = 0 === len_body ? null
922
+ : u8.subarray(len_vh, len_pkt);
923
+
924
+ u8 = u8.subarray(len_pkt);
925
+
926
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
927
+ if (null != pkt)
928
+ res.push( pkt );
929
+ }
930
+ }
931
+ }
932
+
933
+ function _u8_join(a, b) {
934
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
935
+ r.set(a, 0);
936
+ r.set(b, alen);
937
+ return r
938
+ }
939
+
940
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
941
+
942
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
943
+ pkt_ctx = {
944
+ __proto__: pkt_ctx || opts.pkt_ctx,
945
+ mqtt_level,
946
+ get hdr() { return this.b0 & 0xf },
947
+ get id() { return this.b0 >>> 4 },
948
+ get type() { return _pkt_types[this.b0 >>> 4] },
949
+ };
950
+
951
+ let op, _decode_by_id=[], _encode_by_type={};
952
+ for (op of opts.encode_fns)
953
+ op(_encode_by_type, opts.mqtt_writer);
954
+ for (op of opts.decode_fns)
955
+ op(_decode_by_id, opts.mqtt_reader);
956
+
957
+ return {
958
+ pkt_ctx,
959
+
960
+ encode_pkt(type, pkt) {
961
+ return _encode_by_type[type]( mqtt_level, pkt ) },
962
+
963
+ decode_pkt(b0, u8_body) {
964
+ if (b0.map) // Uint8Array in first arg
965
+ return mqtt_raw_dispatch(this)(b0)[0]
966
+
967
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
968
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
969
+
970
+ mqtt_stream() {
971
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
972
+ self.pkt_ctx._base_ = self.pkt_ctx;
973
+ self.decode = mqtt_raw_dispatch(self);
974
+ return self
975
+ },
976
+ }
977
+ }
978
+
979
+ function ao_defer_ctx(as_res = (...args) => args) {
980
+ let y,n,_pset = (a,b) => { y=a, n=b; };
981
+ return p =>(
982
+ p = new Promise(_pset)
983
+ , as_res(p, y, n)) }
984
+
985
+ const ao_defer_v = /* #__PURE__ */
986
+ ao_defer_ctx();
987
+
988
+ Promise.resolve({type:'init'});
989
+
990
+ function _mqtt_conn(client, [on_mqtt, pkt_future]) {
991
+ let _q_init = ao_defer_v(), _q_ready = ao_defer_v();
992
+ let _send_ready = async (...args) => (await _q_ready[0])(...args);
993
+ let _send_mqtt_pkt, _has_connected;
994
+ client._send = _send_ready;
995
+
996
+ return {
997
+ async when_ready() {await _q_ready[0];}
998
+
999
+ , ping: _ping_interval (() =>_send_mqtt_pkt?.('pingreq'))
1000
+
1001
+ , reset(err) {
1002
+ if (! _send_mqtt_pkt) {return}
1003
+
1004
+ if (err) {
1005
+ _q_init[2](err);}
1006
+
1007
+ _send_mqtt_pkt = null;
1008
+ _q_init = ao_defer_v();
1009
+ client._send = _send_ready;
1010
+
1011
+ // call client.on_conn_reset in next promise microtask
1012
+ client.conn_emit('on_disconnect', false===err, err);}
1013
+
1014
+ , async send_connect(... args) {
1015
+ if (! _send_mqtt_pkt) {
1016
+ await _q_init[0]; }// _send_mqtt_pkt is set before fulfilled
1017
+
1018
+ // await connack response
1019
+ let res = await _send_mqtt_pkt(...args);
1020
+ if (0 == res[0].reason) {
1021
+ _has_connected = true;
1022
+ // resolve _q_ready[0] with _send_mqtt_pkt closure
1023
+ _q_ready[1](client._send = _send_mqtt_pkt);
1024
+ _q_ready = ao_defer_v();
1025
+ client.conn_emit('on_ready');}
1026
+
1027
+ return res}
1028
+
1029
+ , is_set: (() =>!! _send_mqtt_pkt)
1030
+ , set(mqtt_ctx, send_u8_pkt) {
1031
+ if (_send_mqtt_pkt) {
1032
+ throw new Error('Already connected')}
1033
+
1034
+ mqtt_ctx = mqtt_ctx.mqtt_stream();
1035
+ let sess_ctx = {mqtt: client};
1036
+ let on_mqtt_chunk = u8_buf =>
1037
+ on_mqtt(mqtt_ctx.decode(u8_buf), sess_ctx);
1038
+
1039
+ _send_mqtt_pkt = async (type, pkt, key) => {
1040
+ let res = undefined !== key
1041
+ ? pkt_future(key) : true;
1042
+
1043
+ await send_u8_pkt(
1044
+ mqtt_ctx.encode_pkt(type, pkt));
1045
+
1046
+ return res};
1047
+
1048
+ _q_init[1](_send_mqtt_pkt); // resolve _q_init with _send_mqtt_pkt closure
1049
+
1050
+ // call client.on_live in next promise microtask
1051
+ client.conn_emit('on_live', _has_connected);
1052
+ return on_mqtt_chunk} } }
1053
+
1054
+
1055
+ function _ping_interval(send_ping) {
1056
+ let tid;
1057
+ return (( td ) => {
1058
+ tid = clearInterval(tid);
1059
+ if (td) {
1060
+ tid = setInterval(send_ping, 1000 * td);
1061
+
1062
+
1063
+
1064
+
1065
+ // ensure the interval allows the NodeJS event loop to exit
1066
+ tid.unref?.();
1067
+ return true} }) }
1068
+
1069
+ const _mqtt_cmdid_dispatch ={
1070
+ create(target) {
1071
+ return {__proto__: this, target, hashbelt: [new Map()]} }
1072
+
1073
+ , bind_pkt_future(_pkt_id=100) {
1074
+ let {hashbelt} = this;
1075
+
1076
+ let _tmp_; // use _tmp_ to reuse _by_key closure
1077
+ let _by_key = answer_monad =>
1078
+ hashbelt[0].set(_tmp_, answer_monad);
1079
+
1080
+ return (( pkt_or_key ) => {
1081
+ if ('string' === typeof pkt_or_key) {
1082
+ _tmp_ = pkt_or_key;}
1083
+ else {
1084
+ _pkt_id = (_pkt_id + 1) & 0xffff;
1085
+ _tmp_ = pkt_or_key.pkt_id = _pkt_id;}
1086
+
1087
+ return new Promise(_by_key)}) }
1088
+
1089
+ , answer(key, pkt) {
1090
+ for (let map of this.hashbelt) {
1091
+ let answer_monad = map.get(key);
1092
+ if (undefined !== answer_monad) {
1093
+ map.delete(key);
1094
+
1095
+ answer_monad([pkt, /*err*/]); // option/maybe monad
1096
+ return true} }
1097
+ return false}
1098
+
1099
+ , rotate_belt(n) {
1100
+ let {hashbelt} = this;
1101
+ hashbelt.unshift(new Map());
1102
+ for (let old of hashbelt.splice(n || 5)) {
1103
+ for (let answer_monad of old.values()) {
1104
+ answer_monad([/*pkt*/, 'expired']); } } }// option/maybe monad
1105
+
1106
+ , cmdids: ((() => {
1107
+ return [
1108
+ (() =>{} )// 0x0 reserved
1109
+ , by_evt // 0x1 connect
1110
+ , by_type // 0x2 connack
1111
+ , by_evt // 0x3 publish
1112
+ , by_id // 0x4 puback
1113
+ , by_id // 0x5 pubrec
1114
+ , by_id // 0x6 pubrel
1115
+ , by_id // 0x7 pubcomp
1116
+ , by_evt // 0x8 subscribe
1117
+ , by_id // 0x9 suback
1118
+ , by_evt // 0xa unsubscribe
1119
+ , by_id // 0xb unsuback
1120
+ , by_type // 0xc pingreq
1121
+ , by_type // 0xd pingresp
1122
+ , by_evt // 0xe disconnect
1123
+ , by_type ]// 0xf auth
1124
+
1125
+
1126
+ function by_id(disp, pkt) {
1127
+ disp.answer(pkt.pkt_id, pkt); }
1128
+
1129
+ function by_type(disp, pkt, ctx) {
1130
+ disp.answer(pkt.type, pkt);
1131
+ by_evt(disp, pkt, ctx);}
1132
+
1133
+ async function by_evt({target}, pkt, ctx) {
1134
+ let fn = target[`mqtt_${pkt.type}`]
1135
+ || target.mqtt_pkt;
1136
+
1137
+ await fn?.call(target, pkt, ctx);} })()) };
1138
+
1139
+ /*
1140
+ on_mqtt_type = {
1141
+ mqtt_auth(pkt, ctx) ::
1142
+ mqtt_connect(pkt, ctx) ::
1143
+ mqtt_connack(pkt, ctx) ::
1144
+ mqtt_disconnect(pkt, ctx) ::
1145
+
1146
+ mqtt_publish(pkt, ctx)
1147
+ mqtt_subscribe(pkt, ctx) ::
1148
+ mqtt_unsubscribe(pkt, ctx) ::
1149
+
1150
+ mqtt_pingreq(pkt, ctx) ::
1151
+ mqtt_pingresp(pkt, ctx) ::
1152
+ }
1153
+ */
1154
+
1155
+ function _mqtt_dispatch(opt, target) {
1156
+ let _disp_ = _mqtt_cmdid_dispatch.create(target);
1157
+ let { cmdids } = _disp_;
1158
+
1159
+ // default rotate at 1s across 5 buckets
1160
+ let { td: rotate_td=1000, n: rotate_n=5 } =
1161
+ opt && opt.rotate || {};
1162
+
1163
+ let rotate_ts = rotate_td + Date.now();
1164
+
1165
+ return [on_mqtt,
1166
+ _disp_.bind_pkt_future()]
1167
+
1168
+ function on_mqtt(pkt_list, ctx) {
1169
+ for (let pkt of pkt_list) {
1170
+ cmdids[pkt.id](_disp_, pkt, ctx); }
1171
+
1172
+ if (Date.now() > rotate_ts) {
1173
+ _disp_.rotate_belt(rotate_n);
1174
+ rotate_ts = rotate_td + Date.now();} } }
1175
+
1176
+ class MQTTError extends Error {
1177
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
1178
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
1179
+ this.mqtt_pkt = mqtt_pkt;
1180
+ this.reason = reason;} }
1181
+
1182
+ class MQTTBase {
1183
+ constructor(opt={}) {
1184
+ this.with(opt);
1185
+ this._conn_ = _mqtt_conn(this,
1186
+ this._init_dispatch(opt, this)); }
1187
+
1188
+ with(fns_ns) {
1189
+ for (let [k,v] of Object.entries(fns_ns)) {
1190
+ if ('function' === typeof v) {this[k] = v;} }
1191
+ return this}
1192
+
1193
+ async conn_emit(evt, arg, err_arg) {
1194
+ this.log_conn?.(evt, arg, err_arg);
1195
+ try {
1196
+ let fn_evt = this[await evt]; // microtask break using `await evt`
1197
+ if (fn_evt) {
1198
+ await fn_evt.call(this, this, arg, err_arg);}
1199
+ else if (err_arg) {throw err_arg} }
1200
+ catch (err) {
1201
+ this.on_error(err, evt);} }
1202
+
1203
+ on_error(err, evt) {
1204
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
1205
+
1206
+ // Handshaking Packets
1207
+
1208
+ async connect(pkt={}) {
1209
+ let cid = pkt.client_id;
1210
+ if ('string' !== typeof cid) {
1211
+ // see init_client_id implementation in core.jsy
1212
+ pkt.client_id = cid = this.client_id || this.init_client_id(cid);}
1213
+ this.client_id = cid;
1214
+
1215
+ if (null == pkt.keep_alive) {
1216
+ pkt.keep_alive = 60;}
1217
+
1218
+ let res = await this._conn_
1219
+ .send_connect('connect', pkt, 'connack');
1220
+
1221
+ if (0 != res[0].reason) {
1222
+ throw new this.MQTTError(res[0])}
1223
+
1224
+ // TODO: merge with server's keep_alive frequency
1225
+ this._conn_.ping(pkt.keep_alive);
1226
+ return res}
1227
+
1228
+ async disconnect(pkt={}) {
1229
+ let res = await this._send('disconnect', pkt);
1230
+ this._conn_.reset(false);
1231
+ return res}
1232
+
1233
+ auth(pkt={}) {
1234
+ return this._send('auth', pkt, 'auth')}
1235
+
1236
+ ping() {return this._send('pingreq', null, 'pingresp')}
1237
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
1238
+
1239
+ // alias: sub
1240
+ subscribe(pkt, ex, topic_prefix) {
1241
+ pkt = _as_topics(pkt, ex, topic_prefix);
1242
+ let suback = this._send('subscribe', pkt, pkt);
1243
+ return this.on_sub?.(suback, pkt) ?? suback}
1244
+
1245
+ // alias: unsub
1246
+ unsubscribe(pkt, ex, topic_prefix) {
1247
+ pkt = _as_topics(pkt, ex, topic_prefix);
1248
+ return this._send('unsubscribe', pkt, pkt)}
1249
+
1250
+
1251
+ post(topic, payload, pub_opt) {// qos:0
1252
+ return this.pub({topic, payload, qos:0}, pub_opt)}
1253
+ send(topic, payload, pub_opt) {// qos:1
1254
+ return this.pub({topic, payload, qos:1}, pub_opt)}
1255
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
1256
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
1257
+
1258
+ // alias: json_post
1259
+ obj_post(topic, msg, pub_opt) {// qos:0
1260
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
1261
+ // alias: json_send
1262
+ obj_send(topic, msg, pub_opt) {// qos:1
1263
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
1264
+ // alias: json_store
1265
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
1266
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
1267
+
1268
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
1269
+ async pub(pkt, pub_opt) {
1270
+ if (undefined === pkt.payload) {
1271
+ if ('function' === typeof pub_opt) {
1272
+ pub_opt = {fn_encode: pub_opt};}
1273
+
1274
+ let {msg} = pkt;
1275
+ switch (typeof msg) {
1276
+ case 'function':
1277
+ pub_opt = {...pub_opt, fn_encode: msg};
1278
+ // flow into 'undefined' case
1279
+ case 'undefined':
1280
+ // return a single-value closure to publish packets
1281
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
1282
+
1283
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
1284
+ let {fn_encode} = pub_opt || {};
1285
+ pkt.payload = fn_encode
1286
+ ? await fn_encode(msg)
1287
+ : JSON.stringify(msg);}
1288
+
1289
+ if (pub_opt) {
1290
+ if (pub_opt.props) {
1291
+ pkt.props = pub_opt.props;}
1292
+ if (pub_opt.xform) {
1293
+ pkt = pub_opt.xform(pkt) || pkt;} }
1294
+
1295
+ return this._send('publish', pkt,
1296
+ pkt.qos ? pkt : void 0 ) }// key
1297
+
1298
+
1299
+ // Internal API
1300
+
1301
+ /* async _send(type, pkt) -- provided by _conn_ and transport */
1302
+
1303
+ _init_dispatch(opt) {
1304
+ this.constructor?._once_();
1305
+ let target ={__proto__: opt.on_mqtt_type};
1306
+ target.mqtt_publish ||=
1307
+ this._init_router?.(opt, this, target);
1308
+ return _mqtt_dispatch(this, target)}
1309
+
1310
+ static _aliases() {
1311
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
1312
+
1313
+ static _once_(self=this) {
1314
+ self._once_ = _=>0;
1315
+ let p = self.prototype;
1316
+ p.MQTTError = MQTTError;
1317
+ for (let alias of self._aliases().split(/\s+/)) {
1318
+ alias = alias.split(':');
1319
+ let fn = alias[1] && p[alias[1]];
1320
+ if (fn) {p[alias[0]] = fn;} } } }
1321
+
1322
+
1323
+ function _as_topics(pkt, ex, topic_prefix) {
1324
+ if (ex?.trim) {// string
1325
+ topic_prefix = ex;
1326
+ ex = null;}
1327
+
1328
+ pkt =(
1329
+ pkt.trim // string
1330
+ ? {topics:[pkt], ... ex}
1331
+ : pkt[Symbol.iterator]
1332
+ ? {topics:[... pkt], ... ex}
1333
+ : ex ? {...pkt, ...ex}
1334
+ : pkt);
1335
+
1336
+ if (topic_prefix) {
1337
+ // particularly useful with shared queues, e.g.
1338
+ // topic_prefix = '$share/some-queue-name/'
1339
+ let _prefix_topics = v =>
1340
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
1341
+
1342
+ pkt.topics = pkt.topics.map(_prefix_topics);}
1343
+ return pkt}
1344
+
1345
+ const pkt_api = {
1346
+ utf8(u8) { return new TextDecoder('utf-8').decode(u8 || this.payload ) },
1347
+ json(u8) { return JSON.parse( this.utf8(u8) || null ) },
1348
+ text(u8) { return this.utf8(u8) },
1349
+ };
1350
+
1351
+ class MQTTCore extends MQTTBase {
1352
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
1353
+ let self = class extends this {};
1354
+ self.prototype.mqtt_ctx =
1355
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
1356
+ return self}
1357
+
1358
+
1359
+ // automatic Client Id for connect()
1360
+ init_client_id(parts=['u8-mqtt--','']) {
1361
+ let sess_stg=this.sess_stg;
1362
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
1363
+ if (! cid) {
1364
+ cid = parts.join(Math.random().toString(36).slice(2));
1365
+ sess_stg?.setItem(key, cid);}
1366
+ return cid}
1367
+
1368
+ get sess_stg() {return globalThis.sessionStorage}
1369
+
1370
+
1371
+ //on_error(err, evt) ::
1372
+ // console.warn @ '[[u8-mqtt error: %s]]', evt, err
1373
+
1374
+ //log_conn(evt, arg, err_arg) ::
1375
+ // console.info @ '[[u8-mqtt log: %s]]', evt, arg, err_arg
1376
+
1377
+ on_live(client, is_reconnect) {
1378
+ if (is_reconnect) {
1379
+ return client.connect()} }
1380
+
1381
+ // on_ready(client) ::
1382
+ // on_reconnect(client) ::
1383
+ on_disconnect(client, intentional) {
1384
+ if (! intentional) {
1385
+ return client.on_reconnect?.()} }
1386
+
1387
+ _use_conn(fn_reconnect) {
1388
+ return (this.reconnect = fn_reconnect)?.()}
1389
+ with_autoreconnect(opt=2000) {
1390
+ if (opt.toFixed) {opt ={delay: opt};}
1391
+ return this.with({
1392
+ on_reconnect() {
1393
+ this.delay(opt.delay || 2000)
1394
+ .then(this.reconnect)
1395
+ .then(opt.reconnect, opt.error);} }) }
1396
+
1397
+ delay(ms) {
1398
+ return new Promise(done => setTimeout(done, ms)) }
1399
+
1400
+ with_async_iter(async_iter, write_u8_pkt) {
1401
+ let on_mqtt_chunk = this._conn_.set(
1402
+ this.mqtt_ctx,
1403
+ write_u8_pkt);
1404
+
1405
+ this._msg_loop = ((async () => {
1406
+ try {
1407
+ async_iter = await async_iter;
1408
+ for await (let chunk of async_iter)
1409
+ on_mqtt_chunk(chunk);
1410
+ this._conn_.reset();}
1411
+ catch (err) {
1412
+ this._conn_.reset(err);} })());
1413
+
1414
+ return this}
1415
+
1416
+
1417
+
1418
+
1419
+
1420
+
1421
+
1422
+
1423
+
1424
+
1425
+
1426
+
1427
+
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+
1446
+
1447
+
1448
+
1449
+
1450
+
1451
+
1452
+
1453
+
1454
+
1455
+
1456
+
1457
+
1458
+
1459
+
1460
+
1461
+
1462
+
1463
+
1464
+
1465
+
1466
+
1467
+ with_stream(read_stream, write_stream) {
1468
+ if (undefined === write_stream) {
1469
+ write_stream = read_stream;}
1470
+
1471
+ return this.with_async_iter(read_stream,
1472
+ u8_pkt => write_stream.write(u8_pkt)) }
1473
+
1474
+
1475
+ with_websock(websock) {
1476
+ if (! websock?.send) {
1477
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1478
+ return this._use_conn (() =>
1479
+ this.with_websock(
1480
+ new WebSocket(websock, ['mqtt'])) ) }
1481
+
1482
+ websock.binaryType = 'arraybuffer';
1483
+
1484
+ let ready, {readyState} = websock;
1485
+ if (1 !== readyState) {
1486
+ if (0 !== readyState) {
1487
+ throw new Error('Invalid WebSocket readyState') }
1488
+
1489
+ ready = new Promise(fn => websock.onopen = fn); }
1490
+
1491
+
1492
+ let {_conn_} = this;
1493
+ let on_mqtt_chunk = _conn_.set(
1494
+ this.mqtt_ctx,
1495
+ async u8_pkt =>(
1496
+ await ready
1497
+ , websock.send(u8_pkt)) );
1498
+
1499
+ websock.onmessage = evt =>(on_mqtt_chunk(new Uint8Array(evt.data)));
1500
+ websock.onclose = evt => {
1501
+ if (! evt.wasClean) {
1502
+ var err = new Error('websocket connection close');
1503
+ err.code = evt.code;
1504
+ err.reason = evt.reason;}
1505
+
1506
+ _conn_.reset(err);};
1507
+
1508
+ return this} }
1509
+
1510
+ const version = '0.5.3-web';
1511
+
1512
+ const MQTTClient_v4 = /* #__PURE__ */
1513
+ with_topic_path_router(
1514
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v4) );
1515
+
1516
+ const mqtt_v4 = opt =>
1517
+ new MQTTClient_v4(opt);
1518
+
1519
+ export { MQTTClient_v4 as MQTTClient, MQTTClient_v4, mqtt_v4 as default, mqtt_v4 as mqtt, mqtt_v4, version };
1520
+ //# sourceMappingURL=full-v4.js.map