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