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