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,1526 @@
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
+ const _isfn = v => typeof v === 'function';
725
+ const _isstr = v => typeof v === 'string';
726
+
727
+ function _interval(fn_callback) {
728
+ let tid;
729
+ return (( td ) => {
730
+ tid = clearInterval(tid);
731
+ if (td) {
732
+ tid = setInterval(fn_callback, 1000 * td);
733
+
734
+ // ensure the interval allows the Deno event loop to exit
735
+ Deno.unrefTimer(tid);
736
+
737
+
738
+
739
+ return true} }) }
740
+
741
+ /*
742
+ class AbstractTopicRouter ::
743
+ async invoke(pkt, ctx) ::
744
+ add(topic_route, ...args) ::
745
+ remove(topic_route, priority) ::
746
+ clear(priority) ::
747
+ find(topic) :: // optional
748
+ mqtt_topic(topic_route)
749
+ */
750
+
751
+ const with_topic_router = mqtt_topic_router =>
752
+ MQTTKlass => class extends MQTTKlass {
753
+ static _aliases() {
754
+ return super._aliases() +
755
+ ' sub_topic:subscribe_topic unsub_topic:unsubscribe_topic'}
756
+
757
+ _init_router(opt, self, target) {
758
+ this._subs = [];
759
+ let router = this.router = target.router =
760
+ mqtt_topic_router(opt, this, target);
761
+ return router?.invoke}
762
+
763
+ on_sub(suback, pkt) {
764
+ suback.pkt = pkt;
765
+ this._subs.push(suback);
766
+ return suback}
767
+ subs_settled() {
768
+ return Promise.allSettled(
769
+ this._subs.splice(0,Infinity)) }
770
+
771
+ // alias: sub_topic
772
+ subscribe_topic(topic_route, ...args) {
773
+ let router = this.router;
774
+ router.add(topic_route, true, args.pop() );// handler
775
+ let topic = router.mqtt_topic(topic_route);
776
+ this.subscribe(topic, ...args );// ex, topic_prefix
777
+ return this }// fluent api -- return this and track side effects
778
+
779
+ // alias: unsub_topic
780
+ unsubscribe_topic(topic_route, ...args) {
781
+ let router = this.router;
782
+ router.remove(topic_route, true);
783
+ let topic = router.mqtt_topic(topic_route);
784
+ return this.unsubscribe(topic, ...args ) }// topic_prefix
785
+
786
+ // add topic handlers without corresponding subscribe packet
787
+ on_topic(...args) {
788
+ this.router.add(...args);
789
+ return this} };
790
+
791
+ // Use [regexparam][] for url-like topic parsing
792
+ // [regexparam]: https://github.com/lukeed/regexparam
793
+
794
+
795
+ const with_topic_path_router = /* #__PURE__ */
796
+ with_topic_router(mqtt_topic_path_router);
797
+
798
+
799
+ const mqtt_topic = topic_route =>
800
+ topic_route
801
+ .replace(/[*].*$/, '#')
802
+ .replace(/:\w[^\/]*/g, '+');
803
+
804
+ /* From the [MQTT v5 Spec](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Topic_Names_and)
805
+ 4.7.1.2 Multi-level wildcard -- (‘#’ U+0023)
806
+ ... MUST be specified either on its own or following a topic level separator.
807
+ In either case it MUST be the last character specified in the Topic Filter
808
+
809
+ 4.7.1.3 Single-level wildcard -- (‘+’ U+002B)
810
+ ...it MUST occupy an entire level of the filter.
811
+ */
812
+
813
+ const as_topic_path = (topic_route, id) =>(
814
+ id=1,
815
+ topic_route
816
+ .replace(/#$/, '*' )// replace MQTT '#' multi-level wildcard at end
817
+ .replace(/\+/g, () => `:$${id++}` ) );// replace MQTT '+' single-level wildcards
818
+
819
+ function _ignore(pkt, params, ctx) {ctx.done = true;}
820
+
821
+ function mqtt_topic_path_router() {
822
+ let pri_lsts = [[],[]], rm = Symbol();
823
+ let find = topic => _routes_iter(pri_lsts, topic);
824
+
825
+ // return duck-type compatible with AbstractTopicRouter in ./with_topic_router
826
+ return {find, mqtt_topic,
827
+ add(topic_route, ...args) {
828
+ let fn = args.pop();
829
+ let priority = args.pop();
830
+
831
+ if (! _isfn(fn)) {
832
+ if (fn) {throw new TypeError()}
833
+ fn = _ignore;}
834
+
835
+ let rte = parse(as_topic_path(topic_route));
836
+
837
+ rte.key = topic_route;
838
+ rte.tgt = fn;
839
+ pri_lsts[priority ? 0 : 1].push(rte);
840
+ return this}
841
+
842
+ , remove(topic_route, priority) {
843
+ let lst = pri_lsts[priority ? 0 : 1];
844
+ return _route_remove([lst], topic_route)}
845
+
846
+ , clear(priority) {
847
+ pri_lsts[priority ? 0 : 1] = [];
848
+ if (null == priority) {
849
+ pri_lsts[1] = []; } }// null clears both lists
850
+
851
+ , async invoke(pkt, ctx) {
852
+ ctx.idx = 0;
853
+ ctx.rm = rm;
854
+
855
+ for (let [fn, params] of find(pkt.topic)) {
856
+ let res = await fn(pkt, params, ctx);
857
+
858
+ if (rm === res) {
859
+ _route_remove(pri_lsts, fn);}
860
+
861
+ if (ctx.done) {
862
+ break}
863
+ else ctx.idx++;}
864
+
865
+ if (1 === pkt.qos) {
866
+ await ctx.mqtt.puback(pkt);} } } }
867
+
868
+
869
+ function * _routes_iter(all_route_lists, topic) {
870
+ topic = topic.replace(/^[\/]*/, '/'); // ensure '/' prefix for regexparam library
871
+ for (let route_list of all_route_lists) {
872
+ for (let {keys, pattern, tgt} of route_list) {
873
+ let match = pattern.exec(topic);
874
+ if (match) {
875
+ let params = keys
876
+ ? keys.reduce(
877
+ (o, k, i) => (o[k] = match[1+i], o)
878
+ , {})
879
+ : match.groups ?? match;
880
+ yield [tgt, params];} } } }
881
+
882
+
883
+ function _route_remove(all_route_lists, query) {
884
+ let fn_match = route =>(
885
+ route===query
886
+ || route.tgt===query
887
+ || route.key===query);
888
+ for (let lst of all_route_lists) {
889
+ let i = lst.findIndex(fn_match);
890
+ if (0 <= i) {
891
+ lst.splice(i,1);
892
+ return true} }
893
+ return false}
894
+
895
+ /*
896
+ export function decode_varint_loop(u8, i=0) {
897
+ let i0 = i
898
+ let shift = 0, n = (u8[i] & 0x7f)
899
+ while ( 0x80 & u8[i++] )
900
+ n |= (u8[i] & 0x7f) << (shift += 7)
901
+
902
+ return [n, i, i0]
903
+ }
904
+ */
905
+
906
+
907
+ function decode_varint(u8, i=0) {
908
+ let i0 = i;
909
+ // unrolled for a max of 4 chains
910
+ let n = (u8[i] & 0x7f) << 0;
911
+ if ( 0x80 & u8[i++] ) {
912
+ n |= (u8[i] & 0x7f) << 7;
913
+ if ( 0x80 & u8[i++] ) {
914
+ n |= (u8[i] & 0x7f) << 14;
915
+ if ( 0x80 & u8[i++] ) {
916
+ n |= (u8[i] & 0x7f) << 21;
917
+ }
918
+ }
919
+ }
920
+ return [n, i, i0]
921
+ }
922
+
923
+ function mqtt_raw_dispatch(opt) {
924
+ let u8 = new Uint8Array(0);
925
+ return u8_buf => {
926
+ u8 = 0 === u8.byteLength
927
+ ? u8_buf : _u8_join(u8, u8_buf);
928
+
929
+ let res = [];
930
+ while (1) {
931
+ let [len_body, len_vh] = decode_varint(u8, 1);
932
+ let len_pkt = len_body + len_vh;
933
+
934
+ if ( u8.byteLength < len_pkt )
935
+ return res
936
+
937
+ let b0 = u8[0];
938
+ let u8_body = 0 === len_body ? null
939
+ : u8.subarray(len_vh, len_pkt);
940
+
941
+ u8 = u8.subarray(len_pkt);
942
+
943
+ let pkt = opt.decode_pkt(b0, u8_body, opt);
944
+ if (null != pkt)
945
+ res.push( pkt );
946
+ }
947
+ }
948
+ }
949
+
950
+ function _u8_join(a, b) {
951
+ let alen = a.byteLength, r = new Uint8Array(alen + b.byteLength);
952
+ r.set(a, 0);
953
+ r.set(b, alen);
954
+ return r
955
+ }
956
+
957
+ const _pkt_types = ['~', 'connect', 'connack', 'publish', 'puback', 'pubrec', 'pubrel', 'pubcomp', 'subscribe', 'suback', 'unsubscribe', 'unsuback', 'pingreq', 'pingresp', 'disconnect', 'auth'];
958
+
959
+ function mqtt_pkt_ctx(mqtt_level, opts, pkt_ctx) {
960
+ pkt_ctx = {
961
+ __proto__: pkt_ctx || opts.pkt_ctx,
962
+ mqtt_level,
963
+ get hdr() { return this.b0 & 0xf },
964
+ get id() { return this.b0 >>> 4 },
965
+ get type() { return _pkt_types[this.b0 >>> 4] },
966
+ };
967
+
968
+ let op, _decode_by_id=[], _encode_by_type={};
969
+ for (op of opts.encode_fns)
970
+ op(_encode_by_type, opts.mqtt_writer);
971
+ for (op of opts.decode_fns)
972
+ op(_decode_by_id, opts.mqtt_reader);
973
+
974
+ return {
975
+ pkt_ctx,
976
+
977
+ encode_pkt(type, pkt) {
978
+ return _encode_by_type[type]( mqtt_level, pkt ) },
979
+
980
+ decode_pkt(b0, u8_body) {
981
+ if (b0.map) // Uint8Array in first arg
982
+ return mqtt_raw_dispatch(this)(b0)[0]
983
+
984
+ let fn_decode = _decode_by_id[b0>>>4] || _decode_by_id[0];
985
+ return fn_decode?.({__proto__: this.pkt_ctx, b0}, u8_body) },
986
+
987
+ mqtt_stream() {
988
+ let self = { __proto__: this, pkt_ctx: { __proto__: pkt_ctx } };
989
+ self.pkt_ctx._base_ = self.pkt_ctx;
990
+ self.decode = mqtt_raw_dispatch(self);
991
+ return self
992
+ },
993
+ }
994
+ }
995
+
996
+ async function _mqtt_cmd_evt(target, answer, pkt, ctx) {
997
+ /* target : on_mqtt_type = {
998
+ mqtt_pkt(pkt, ctx) {}, // generic
999
+
1000
+ mqtt_auth(pkt, ctx) {},
1001
+ mqtt_connect(pkt, ctx) {},
1002
+ mqtt_connack(pkt, ctx) {},
1003
+ mqtt_disconnect(pkt, ctx) {},
1004
+
1005
+ mqtt_publish(pkt, ctx) {},
1006
+ mqtt_subscribe(pkt, ctx) {},
1007
+ mqtt_unsubscribe(pkt, ctx) {},
1008
+
1009
+ mqtt_pingreq(pkt, ctx) {},
1010
+ mqtt_pingresp(pkt, ctx) {},
1011
+ } */
1012
+
1013
+ let pkt_fn = target[`mqtt_${pkt.type}`] || target.mqtt_pkt;
1014
+ await pkt_fn?.call(target, pkt, ctx);}
1015
+
1016
+ function _mqtt_cmd_type(target, answer, pkt, ctx) {
1017
+ answer(pkt.type, pkt);
1018
+ _mqtt_cmd_evt(target, answer, pkt, ctx);}
1019
+
1020
+ function _mqtt_cmd_id(target, answer, pkt) {
1021
+ answer(pkt.pkt_id, pkt);}
1022
+
1023
+
1024
+ const _mqtt_cmdids =[
1025
+ _ => {} // 0x0 reserved
1026
+ , _mqtt_cmd_evt // 0x1 connect
1027
+ , _mqtt_cmd_type // 0x2 connack
1028
+ , _mqtt_cmd_evt // 0x3 publish
1029
+ , _mqtt_cmd_id // 0x4 puback
1030
+ , _mqtt_cmd_id // 0x5 pubrec
1031
+ , _mqtt_cmd_id // 0x6 pubrel
1032
+ , _mqtt_cmd_id // 0x7 pubcomp
1033
+ , _mqtt_cmd_evt // 0x8 subscribe
1034
+ , _mqtt_cmd_id // 0x9 suback
1035
+ , _mqtt_cmd_evt // 0xa unsubscribe
1036
+ , _mqtt_cmd_id // 0xb unsuback
1037
+ , _mqtt_cmd_type // 0xc pingreq
1038
+ , _mqtt_cmd_type // 0xd pingresp
1039
+ , _mqtt_cmd_evt // 0xe disconnect
1040
+ , _mqtt_cmd_type ];// 0xf auth
1041
+
1042
+ function _mqtt_dispatch(opt, target) {
1043
+ let hashbelt=[], rotate_ts=0;
1044
+ // default rotate at 1s across 5 buckets
1045
+ let { td: rotate_td=1000, n: rotate_n=5 } = opt?.rotate || {};
1046
+
1047
+ // Promise / future scaffolding
1048
+ let _pkt_id=100, _ftr_key; // use _ftr_key to reuse _by_key closure
1049
+ let _ftr_by_key = fn_answer => hashbelt[0].set(_ftr_key, fn_answer);
1050
+
1051
+ on_mqtt([]); // init hashbelt and rotate_ts
1052
+ return [on_mqtt, pkt_future]
1053
+
1054
+
1055
+ function pkt_future(pkt_or_key) {
1056
+ if (! _isstr(pkt_or_key)) {
1057
+ _pkt_id = (_pkt_id + 1) & 0xffff; // 16-bit unsigned short
1058
+ _ftr_key = pkt_or_key.pkt_id = _pkt_id;}
1059
+ else _ftr_key = pkt_or_key;
1060
+
1061
+ return new Promise(_ftr_by_key)}
1062
+
1063
+ function answer(key, pkt) {
1064
+ for (let map of hashbelt) {
1065
+ let fn_answer = map.get(key);
1066
+ if (fn_answer) {
1067
+ map.delete(key);
1068
+
1069
+ fn_answer([pkt, /*err*/]); // option/maybe monad
1070
+ return true} }
1071
+ return false}
1072
+
1073
+ function on_mqtt(pkt_list, ctx) {
1074
+ for (let pkt of pkt_list) {
1075
+ _mqtt_cmdids[pkt.id](target, answer, pkt, ctx);}
1076
+
1077
+ // rotate after rotate_ts
1078
+ let now = Date.now();
1079
+ if (now > rotate_ts) {
1080
+ rotate_ts = rotate_td + now;
1081
+ hashbelt.unshift(new Map());
1082
+ while (hashbelt.length > rotate_n) {
1083
+ for (let fn_answer of hashbelt.pop().values()) {
1084
+ fn_answer([/*pkt*/, 'expired']); } } } } }// option/maybe monad
1085
+
1086
+ class MQTTError extends Error {
1087
+ constructor(mqtt_pkt, reason=mqtt_pkt.reason) {
1088
+ // use hex-encoded reasons to match MQTT spec documentation
1089
+ super(`[0x${reason.toString(16)}] ${reason.reason}`);
1090
+ this.mqtt_pkt = mqtt_pkt;
1091
+ this.reason = reason;} }
1092
+
1093
+ class MQTTBase {
1094
+ // Handshaking Packets
1095
+ async connect(pkt={}) {
1096
+ let cid = pkt.client_id;
1097
+ if (! _isstr(cid)) {
1098
+ // see init_client_id implementation in core.jsy
1099
+ pkt.client_id = cid = this.client_id || this.init_client_id(cid);}
1100
+ this.client_id = cid;
1101
+
1102
+ if (null == pkt.keep_alive) {
1103
+ pkt.keep_alive = 60;}
1104
+
1105
+ let response = await this._send0('connect', pkt, 'connack');
1106
+ if (0 != response[0].reason) {// compare to 0 to coerce to number
1107
+ throw new this.MQTTError(response[0])}
1108
+ return this.conn.on_conn(pkt, response)}
1109
+
1110
+ async disconnect(pkt={}) {
1111
+ let response = await this._send0('disconnect', pkt);
1112
+ return this.conn.on_dis(pkt, response)}
1113
+
1114
+ async auth(pkt={}) {
1115
+ let response = await this._send0('auth', pkt, 'auth');
1116
+ if (response[0].reason) {
1117
+ throw new this.MQTTError(response[0])}
1118
+ return this.conn.on_auth(pkt, response)}
1119
+
1120
+ ping() {return this._send('pingreq', null, 'pingresp')}
1121
+ puback({pkt_id}) {return this._send('puback', {pkt_id})}
1122
+
1123
+ // alias: sub
1124
+ subscribe(pkt, ex, topic_prefix) {
1125
+ pkt = _as_topics(pkt, ex, topic_prefix);
1126
+ let suback = this._send('subscribe', pkt, pkt);
1127
+ return this.on_sub?.(suback, pkt) ?? suback}
1128
+
1129
+ // alias: unsub
1130
+ unsubscribe(pkt, ex, topic_prefix) {
1131
+ pkt = _as_topics(pkt, ex, topic_prefix);
1132
+ return this._send('unsubscribe', pkt, pkt)}
1133
+
1134
+
1135
+ post(topic, payload, pub_opt) {// qos:0
1136
+ return this.pub({topic, payload, qos:0}, pub_opt)}
1137
+ send(topic, payload, pub_opt) {// qos:1
1138
+ return this.pub({topic, payload, qos:1}, pub_opt)}
1139
+ store(topic, payload, pub_opt) {// qos:1, retain: 1
1140
+ return this.pub({topic, payload, qos:1, retain: 1}, pub_opt)}
1141
+
1142
+ // alias: json_post
1143
+ obj_post(topic, msg, pub_opt) {// qos:0
1144
+ return this.pub({topic, msg, arg: 'msg', qos:0}, pub_opt)}
1145
+ // alias: json_send
1146
+ obj_send(topic, msg, pub_opt) {// qos:1
1147
+ return this.pub({topic, msg, arg: 'msg', qos:1}, pub_opt)}
1148
+ // alias: json_store
1149
+ obj_store(topic, msg, pub_opt) {// qos:1, retain: 1
1150
+ return this.pub({topic, msg, arg: 'msg', qos:1, retain: 1}, pub_opt)}
1151
+
1152
+ // alias: publish -- because 'pub' is shorter for semantic aliases above
1153
+ async pub(pkt, pub_opt) {
1154
+ if (undefined === pkt.payload) {
1155
+ if (_isfn(pub_opt)) {
1156
+ // pub_opt as a function is fn_encode value
1157
+ pub_opt = {fn_encode: pub_opt};}
1158
+
1159
+ let msg = pkt.msg, fn_encode = pub_opt?.fn_encode;
1160
+ if (null == msg || _isfn(msg)) {
1161
+ // when msg is a function, return closure using fn_encode
1162
+ if (msg) {pub_opt = {...pub_opt, fn_encode: msg};}
1163
+ // return a single-value closure to publish packets
1164
+ return v => this.pub({...pkt, [pkt.arg || 'payload']: v}, pub_opt)}
1165
+
1166
+ // Encode payload from msg; fn_encode allows alternative to JSON.stringify
1167
+ pkt.payload = fn_encode
1168
+ ? await fn_encode(msg)
1169
+ : JSON.stringify(msg);}
1170
+
1171
+ if (pub_opt) {
1172
+ if (pub_opt.props) {
1173
+ pkt.props = pub_opt.props;}
1174
+ if (pub_opt.xform) {
1175
+ pkt = pub_opt.xform(pkt) || pkt;} }
1176
+
1177
+ return this._send('publish', pkt,
1178
+ pkt.qos ? pkt : null ) }// key
1179
+
1180
+
1181
+ // Internal API
1182
+
1183
+ /* async _send0(type, pkt) -- provided by conn and transport */
1184
+ /* async _send(type, pkt) -- provided by conn and transport */
1185
+
1186
+ _init_dispatch(opt) {
1187
+ this.constructor?._once_();
1188
+ let target ={__proto__: opt.on_mqtt_type};
1189
+ target.mqtt_publish ||=
1190
+ this._init_router?.(opt, this, target);
1191
+ return _mqtt_dispatch(opt, target)}
1192
+
1193
+ static _aliases() {
1194
+ return ' publish:pub sub:subscribe unsub:unsubscribe json_post:obj_post json_send:obj_send json_store:obj_store'}
1195
+
1196
+ static _once_(klass=this) {
1197
+ klass._once_ = _=>0;
1198
+ var alias, name, p = klass.prototype;
1199
+ p.MQTTError = MQTTError;
1200
+ for (alias of klass._aliases().split(/\s+/)) {
1201
+ [alias, name] = alias.split(':');
1202
+ p[alias] = p[name];} } }
1203
+
1204
+
1205
+ function _as_topics(pkt, ex, topic_prefix) {
1206
+ if (ex?.trim) {// string
1207
+ topic_prefix = ex;
1208
+ ex = null;}
1209
+
1210
+ pkt =(
1211
+ pkt.trim // string
1212
+ ? {topics:[pkt], ... ex}
1213
+ : pkt[Symbol.iterator]
1214
+ ? {topics:[... pkt], ... ex}
1215
+ : ex ? {...pkt, ...ex}
1216
+ : pkt);
1217
+
1218
+ if (topic_prefix) {
1219
+ // particularly useful with shared queues, e.g.
1220
+ // topic_prefix = '$share/some-queue-name/'
1221
+ let _prefix_topics = v =>
1222
+ v.trim ? topic_prefix+v : v.map(_prefix_topics);
1223
+
1224
+ pkt.topics = pkt.topics.map(_prefix_topics);}
1225
+ return pkt}
1226
+
1227
+ const _defer_obj = o =>(
1228
+ o.p = new Promise((a,e) => { o.a=a; o.e=e; })
1229
+ , o);
1230
+
1231
+ function _dfn_reset(client, attr, fn_after) {
1232
+ // a resetable deferred for a function
1233
+ let self = {set}, afn = async (...args) => (await self.p)(...args);
1234
+ return set()
1235
+
1236
+ function set() {
1237
+ if (afn !== client[attr]) {
1238
+ _defer_obj(self).p.then(fn_after, _=>0);
1239
+ client[attr] = afn;}
1240
+ return self} }
1241
+
1242
+ function _mqtt_conn(opt, client, [on_mqtt, pkt_future]) {
1243
+ let _abort;
1244
+ let _dfn_send0 = _dfn_reset(client, '_send0', // client._send0 getter/setter
1245
+ _=> client.conn_emit('on_live', conn.has_connected));
1246
+ let _dfn_ready = _dfn_reset(client, '_send', // client._send getter/setter
1247
+ _=> client.conn_emit('on_ready'));
1248
+ let _keep_alive_ival = _interval (() =>client._send0('pingreq') );// resettable interval for keep_alive ping
1249
+
1250
+ let conn = Object.create({
1251
+ ping: (td=conn.keep_alive) => _keep_alive_ival(td)
1252
+
1253
+ , on_conn(pkt, response) {
1254
+ conn.has_connected = true;
1255
+ conn.keep_alive = opt.keep_alive || response[0].props?.server_keep_alive || pkt.keep_alive;
1256
+ client.conn_emit('on_conn');
1257
+ return opt.use_auth
1258
+ ? response // wait on enhanced authentication step
1259
+ : conn.on_auth(null, response) }// otherwise, connect is also auth
1260
+
1261
+ , on_auth(pkt, response) {
1262
+ _dfn_ready.a(_dfn_send0.p);
1263
+ if (0 != opt.keep_alive) {
1264
+ conn.ping();}
1265
+ client.conn_emit('on_auth', !pkt);
1266
+ return response}
1267
+
1268
+ , on_dis(pkt, response) {
1269
+ conn.reset(false);
1270
+ return response}
1271
+
1272
+ , reset(err) {
1273
+ if (err) {
1274
+ _dfn_send0.e(err); }// send error to uses of _send0 (connect, auth)
1275
+ _abort.e(err); // abort in-progress connections
1276
+
1277
+ delete conn.is_set;
1278
+ conn.ready = handshake();
1279
+ client.conn_emit('on_disconnect', false===err, err);}
1280
+
1281
+ , abort() {
1282
+ _dfn_ready.e(err); // abort all messages awaiting ready state
1283
+ return conn.reset(err)}
1284
+
1285
+ , async setup(gate, send_u8_pkt, init_msg_loop) {
1286
+ if (conn.is_set) {
1287
+ throw new Error() }// already in-progress
1288
+
1289
+ conn.is_set = true;
1290
+ await gate;
1291
+
1292
+ // setup send/recv MQTT parsing context
1293
+ let mqtt_ctx = client.mqtt_ctx.mqtt_stream();
1294
+
1295
+ {// setup inbound message loop
1296
+ let sess_ctx = {mqtt: client}; // mutable session context
1297
+ let on_mqtt_chunk = u8 => on_mqtt(mqtt_ctx.decode(u8), sess_ctx);
1298
+ init_msg_loop(on_mqtt_chunk, conn);}
1299
+
1300
+ // setup outbound message path and transport connection
1301
+ send_u8_pkt = await send_u8_pkt;
1302
+ _dfn_send0.a(
1303
+ async (type, pkt, key) => {
1304
+ let res = undefined !== key
1305
+ ? pkt_future(key) : true;
1306
+
1307
+ await send_u8_pkt(
1308
+ mqtt_ctx.encode_pkt(type, pkt));
1309
+ return res} ); } });
1310
+
1311
+ conn.ready = handshake();
1312
+ return conn
1313
+
1314
+ async function handshake() {
1315
+ _abort = _defer_obj({});
1316
+
1317
+ _keep_alive_ival(0); // clearInterval on keep alive ping
1318
+ _dfn_send0.set(); // reset client._send0 if necessary
1319
+ _dfn_ready.set(); // reset client._send if necessary
1320
+
1321
+ try {
1322
+ // set client._send0 as passtrhough after transport connection
1323
+ client._send0 = await Promise.race([_dfn_send0.p, _abort.p]);
1324
+
1325
+ // set client._send as passtrhough after ready
1326
+ client._send = await Promise.race([_dfn_ready.p, _abort.p]);
1327
+ return true}
1328
+ catch (err) {
1329
+ return false} } }
1330
+
1331
+ const pkt_api ={
1332
+ utf8(u8) {return new TextDecoder('utf-8').decode(u8 || this.payload )}
1333
+ , json(u8) {return JSON.parse( this.utf8(u8) || null )}
1334
+ , text(u8) {return this.utf8(u8)} };
1335
+
1336
+ const opt_default ={
1337
+ sess_stg: globalThis.sessionStorage};
1338
+
1339
+ class MQTTCore extends MQTTBase {
1340
+ constructor(opt) {
1341
+ super();
1342
+ this.with(opt);
1343
+ opt ={...opt_default, ...opt};
1344
+ // settings for MQTTCore
1345
+ this.sess_stg = opt.sess_stg;
1346
+ // setup connection and dispatch
1347
+ this.conn = _mqtt_conn(opt, this,
1348
+ this._init_dispatch(opt)); }
1349
+
1350
+ with(fns_ns) {
1351
+ for (let [k,v] of Object.entries(fns_ns)) {
1352
+ if (_isfn(v)) {this[k] = v;} }
1353
+ return this}
1354
+
1355
+
1356
+ static mqtt_ctx(mqtt_level, mqtt_opts, pkt_ctx=pkt_api) {
1357
+ let klass = class extends this {};
1358
+ klass.prototype.mqtt_ctx =
1359
+ mqtt_pkt_ctx(mqtt_level, mqtt_opts, pkt_ctx);
1360
+ return klass}
1361
+
1362
+
1363
+ async conn_emit(evt, arg, err_arg) {
1364
+ this.log_conn?.(evt, arg, err_arg);
1365
+ try {
1366
+ let fn_evt = this[await evt]; // microtask break using `await evt`
1367
+ if (fn_evt) {
1368
+ await fn_evt.call(this, this, arg, err_arg);}
1369
+ else if (err_arg) {throw err_arg} }
1370
+ catch (err) {
1371
+ this.on_error(err, evt);} }
1372
+
1373
+ on_error(err, evt) {
1374
+ console.warn('[[u8-mqtt error: %s]]', evt, err); }
1375
+ log_conn(evt, arg, err_arg) {
1376
+ console.info('[[u8-mqtt conn: %s]]', evt, arg, err_arg); }
1377
+
1378
+
1379
+ // automatic Client Id for connect()
1380
+ init_client_id(parts=['u8-mqtt--','']) {
1381
+ let sess_stg = this.sess_stg;
1382
+ let key, cid = sess_stg?.getItem(key=parts.join(' '));
1383
+ if (! cid) {
1384
+ cid = parts.join(Math.random().toString(36).slice(2));
1385
+ sess_stg?.setItem(key, cid);}
1386
+ return cid}
1387
+
1388
+
1389
+ on_live(client, is_reconnect) {
1390
+ if (is_reconnect) {
1391
+ return client.connect()} }
1392
+
1393
+ // on_ready(client) ::
1394
+ // on_reconnect(client) ::
1395
+ on_disconnect(client, intentional) {
1396
+ if (! intentional) {
1397
+ return client.on_reconnect?.()} }
1398
+
1399
+ _use_conn(fn_reconnect) {
1400
+ return (this.reconnect = fn_reconnect)?.()}
1401
+ with_autoreconnect(opt=2000) {
1402
+ if (opt.toFixed) {opt ={delay: opt};}
1403
+ return this.with({
1404
+ on_reconnect() {
1405
+ this.delay(opt.delay || 2000)
1406
+ .then(this.reconnect)
1407
+ .then(opt.reconnect, opt.error);} }) }
1408
+
1409
+ delay(ms) {
1410
+ return new Promise(done => setTimeout(done, ms)) }
1411
+
1412
+ with_async_iter(async_iter, write_u8_pkt) {
1413
+ this.conn.setup(async_iter,
1414
+ write_u8_pkt,
1415
+ async (on_mqtt_chunk, conn) => {
1416
+ try {
1417
+ async_iter = await async_iter;
1418
+ for await (let chunk of async_iter)
1419
+ on_mqtt_chunk(chunk);
1420
+ conn.reset();}
1421
+ catch (err) {
1422
+ conn.reset(err);} } );
1423
+ return this}
1424
+
1425
+
1426
+
1427
+
1428
+ with_tcp(...opt) {
1429
+ opt = this._conn_opt(opt);
1430
+ opt.transport = 'tcp';
1431
+ return this._use_conn (() =>
1432
+ this.with_deno_iter(
1433
+ Deno.connect(opt)) ) }
1434
+
1435
+ with_tls(...opt) {
1436
+ opt = this._conn_opt(opt);
1437
+ return this._use_conn (() =>
1438
+ this.with_deno_iter(
1439
+ Deno.connectTls(opt)) ) }
1440
+
1441
+ with_deno_iter(transport) {
1442
+ return this.with_async_iter(
1443
+ transport.then(Deno.iter),
1444
+ transport.then(write_stream =>
1445
+ u8_pkt => write_stream.write(u8_pkt)) ) }
1446
+
1447
+ _conn_opt([a0, a1, a2]) {
1448
+ // (port, hostname, options) or (url, options)
1449
+ if (Number.isFinite(a0)) {
1450
+ return {...a2, port: a0, hostname: a1}}
1451
+
1452
+ a0 = new URL(a0);
1453
+ return {...a1, port: a0.port, hostname: a0.hostname}}
1454
+
1455
+
1456
+
1457
+
1458
+
1459
+
1460
+
1461
+
1462
+
1463
+
1464
+
1465
+
1466
+
1467
+
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+ with_stream(read_stream, write_stream) {
1477
+ if (undefined === write_stream) {
1478
+ write_stream = read_stream;}
1479
+
1480
+ return this.with_async_iter(read_stream,
1481
+ u8_pkt => write_stream.write(u8_pkt)) }
1482
+
1483
+
1484
+ with_websock(websock) {
1485
+ if (! websock?.send) {
1486
+ websock = new URL(websock || 'ws://127.0.0.1:9001');
1487
+ return this._use_conn (() =>
1488
+ this.with_websock(
1489
+ new WebSocket(websock, ['mqtt'])) ) }
1490
+
1491
+ websock.binaryType = 'arraybuffer';
1492
+
1493
+ let ws_ready, readyState = websock.readyState;
1494
+ if (1 !== readyState) {
1495
+ if (0 !== readyState) {
1496
+ throw new Error('WS readyState') }
1497
+
1498
+ ws_ready = new Promise(ready => websock.onopen = ready); }
1499
+
1500
+ this.conn.setup(ws_ready,
1501
+ u8_pkt => websock.send(u8_pkt),
1502
+ (on_mqtt_chunk, conn) => {
1503
+ websock.onmessage = evt =>(
1504
+ on_mqtt_chunk(new Uint8Array(evt.data)) );
1505
+
1506
+ websock.onclose = evt => {
1507
+ if (! evt.wasClean) {
1508
+ var err = new Error('websocket close');
1509
+ err.code = evt.code;
1510
+ err.reason = evt.reason;}
1511
+
1512
+ conn.reset(err);}; } );
1513
+
1514
+ return this} }
1515
+
1516
+ const version = '0.6.0-deno';
1517
+
1518
+ const MQTTClient_v4 = /* #__PURE__ */
1519
+ with_topic_path_router(
1520
+ MQTTCore.mqtt_ctx(4, mqtt_opts_v4) );
1521
+
1522
+ const mqtt_v4 = opt =>
1523
+ new MQTTClient_v4(opt);
1524
+
1525
+ export { MQTTClient_v4 as MQTTClient, MQTTClient_v4, mqtt_v4 as default, mqtt_v4 as mqtt, mqtt_v4, version };
1526
+ //# sourceMappingURL=full-v4.js.map