@remix_labs/hub-client 1.1911.0-dev → 1.1913.0-dev

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 (2) hide show
  1. package/hub-worker.worker.js +1 -3036
  2. package/package.json +2 -2
@@ -1,3036 +1 @@
1
- /******/ (() => { // webpackBootstrap
2
- /******/ var __webpack_modules__ = ({
3
-
4
- /***/ 361:
5
- /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
6
-
7
- /*******************************************************************************
8
- * Copyright (c) 2013 IBM Corp.
9
- *
10
- * All rights reserved. This program and the accompanying materials
11
- * are made available under the terms of the Eclipse Public License v1.0
12
- * and Eclipse Distribution License v1.0 which accompany this distribution.
13
- *
14
- * The Eclipse Public License is available at
15
- * http://www.eclipse.org/legal/epl-v10.html
16
- * and the Eclipse Distribution License is available at
17
- * http://www.eclipse.org/org/documents/edl-v10.php.
18
- *
19
- * Contributors:
20
- * Andrew Banks - initial API and implementation and initial documentation
21
- *******************************************************************************/
22
-
23
-
24
- // Only expose a single object name in the global namespace.
25
- // Everything must go through this module. Global Paho module
26
- // only has a single public function, client, which returns
27
- // a Paho client object given connection details.
28
-
29
- /**
30
- * Send and receive messages using web browsers.
31
- * <p>
32
- * This programming interface lets a JavaScript client application use the MQTT V3.1 or
33
- * V3.1.1 protocol to connect to an MQTT-supporting messaging server.
34
- *
35
- * The function supported includes:
36
- * <ol>
37
- * <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number.
38
- * <li>Specifying options that relate to the communications link with the server,
39
- * for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required.
40
- * <li>Subscribing to and receiving messages from MQTT Topics.
41
- * <li>Publishing messages to MQTT Topics.
42
- * </ol>
43
- * <p>
44
- * The API consists of two main objects:
45
- * <dl>
46
- * <dt><b>{@link Paho.Client}</b></dt>
47
- * <dd>This contains methods that provide the functionality of the API,
48
- * including provision of callbacks that notify the application when a message
49
- * arrives from or is delivered to the messaging server,
50
- * or when the status of its connection to the messaging server changes.</dd>
51
- * <dt><b>{@link Paho.Message}</b></dt>
52
- * <dd>This encapsulates the payload of the message along with various attributes
53
- * associated with its delivery, in particular the destination to which it has
54
- * been (or is about to be) sent.</dd>
55
- * </dl>
56
- * <p>
57
- * The programming interface validates parameters passed to it, and will throw
58
- * an Error containing an error message intended for developer use, if it detects
59
- * an error with any parameter.
60
- * <p>
61
- * Example:
62
- *
63
- * <code><pre>
64
- var client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
65
- client.onConnectionLost = onConnectionLost;
66
- client.onMessageArrived = onMessageArrived;
67
- client.connect({onSuccess:onConnect});
68
-
69
- function onConnect() {
70
- // Once a connection has been made, make a subscription and send a message.
71
- console.log("onConnect");
72
- client.subscribe("/World");
73
- var message = new Paho.MQTT.Message("Hello");
74
- message.destinationName = "/World";
75
- client.send(message);
76
- };
77
- function onConnectionLost(responseObject) {
78
- if (responseObject.errorCode !== 0)
79
- console.log("onConnectionLost:"+responseObject.errorMessage);
80
- };
81
- function onMessageArrived(message) {
82
- console.log("onMessageArrived:"+message.payloadString);
83
- client.disconnect();
84
- };
85
- * </pre></code>
86
- * @namespace Paho
87
- */
88
-
89
- /* jshint shadow:true */
90
- (function ExportLibrary(root, factory) {
91
- if(true){
92
- module.exports = factory();
93
- } else {}
94
- })(this, function LibraryFactory(){
95
-
96
-
97
- var PahoMQTT = (function (global) {
98
-
99
- // Private variables below, these are only visible inside the function closure
100
- // which is used to define the module.
101
- var version = "@VERSION@-@BUILDLEVEL@";
102
-
103
- /**
104
- * @private
105
- */
106
- var localStorage = global.localStorage || (function () {
107
- var data = {};
108
-
109
- return {
110
- setItem: function (key, item) { data[key] = item; },
111
- getItem: function (key) { return data[key]; },
112
- removeItem: function (key) { delete data[key]; },
113
- };
114
- })();
115
-
116
- /**
117
- * Unique message type identifiers, with associated
118
- * associated integer values.
119
- * @private
120
- */
121
- var MESSAGE_TYPE = {
122
- CONNECT: 1,
123
- CONNACK: 2,
124
- PUBLISH: 3,
125
- PUBACK: 4,
126
- PUBREC: 5,
127
- PUBREL: 6,
128
- PUBCOMP: 7,
129
- SUBSCRIBE: 8,
130
- SUBACK: 9,
131
- UNSUBSCRIBE: 10,
132
- UNSUBACK: 11,
133
- PINGREQ: 12,
134
- PINGRESP: 13,
135
- DISCONNECT: 14
136
- };
137
-
138
- // Collection of utility methods used to simplify module code
139
- // and promote the DRY pattern.
140
-
141
- /**
142
- * Validate an object's parameter names to ensure they
143
- * match a list of expected variables name for this option
144
- * type. Used to ensure option object passed into the API don't
145
- * contain erroneous parameters.
146
- * @param {Object} obj - User options object
147
- * @param {Object} keys - valid keys and types that may exist in obj.
148
- * @throws {Error} Invalid option parameter found.
149
- * @private
150
- */
151
- var validate = function(obj, keys) {
152
- for (var key in obj) {
153
- if (obj.hasOwnProperty(key)) {
154
- if (keys.hasOwnProperty(key)) {
155
- if (typeof obj[key] !== keys[key])
156
- throw new Error(format(ERROR.INVALID_TYPE, [typeof obj[key], key]));
157
- } else {
158
- var errorStr = "Unknown property, " + key + ". Valid properties are:";
159
- for (var validKey in keys)
160
- if (keys.hasOwnProperty(validKey))
161
- errorStr = errorStr+" "+validKey;
162
- throw new Error(errorStr);
163
- }
164
- }
165
- }
166
- };
167
-
168
- /**
169
- * Return a new function which runs the user function bound
170
- * to a fixed scope.
171
- * @param {function} User function
172
- * @param {object} Function scope
173
- * @return {function} User function bound to another scope
174
- * @private
175
- */
176
- var scope = function (f, scope) {
177
- return function () {
178
- return f.apply(scope, arguments);
179
- };
180
- };
181
-
182
- /**
183
- * Unique message type identifiers, with associated
184
- * associated integer values.
185
- * @private
186
- */
187
- var ERROR = {
188
- OK: {code:0, text:"AMQJSC0000I OK."},
189
- CONNECT_TIMEOUT: {code:1, text:"AMQJSC0001E Connect timed out."},
190
- SUBSCRIBE_TIMEOUT: {code:2, text:"AMQJS0002E Subscribe timed out."},
191
- UNSUBSCRIBE_TIMEOUT: {code:3, text:"AMQJS0003E Unsubscribe timed out."},
192
- PING_TIMEOUT: {code:4, text:"AMQJS0004E Ping timed out."},
193
- INTERNAL_ERROR: {code:5, text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},
194
- CONNACK_RETURNCODE: {code:6, text:"AMQJS0006E Bad Connack return code:{0} {1}."},
195
- SOCKET_ERROR: {code:7, text:"AMQJS0007E Socket error:{0}."},
196
- SOCKET_CLOSE: {code:8, text:"AMQJS0008I Socket closed."},
197
- MALFORMED_UTF: {code:9, text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},
198
- UNSUPPORTED: {code:10, text:"AMQJS0010E {0} is not supported by this browser."},
199
- INVALID_STATE: {code:11, text:"AMQJS0011E Invalid state {0}."},
200
- INVALID_TYPE: {code:12, text:"AMQJS0012E Invalid type {0} for {1}."},
201
- INVALID_ARGUMENT: {code:13, text:"AMQJS0013E Invalid argument {0} for {1}."},
202
- UNSUPPORTED_OPERATION: {code:14, text:"AMQJS0014E Unsupported operation."},
203
- INVALID_STORED_DATA: {code:15, text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},
204
- INVALID_MQTT_MESSAGE_TYPE: {code:16, text:"AMQJS0016E Invalid MQTT message type {0}."},
205
- MALFORMED_UNICODE: {code:17, text:"AMQJS0017E Malformed Unicode string:{0} {1}."},
206
- BUFFER_FULL: {code:18, text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."},
207
- };
208
-
209
- /** CONNACK RC Meaning. */
210
- var CONNACK_RC = {
211
- 0:"Connection Accepted",
212
- 1:"Connection Refused: unacceptable protocol version",
213
- 2:"Connection Refused: identifier rejected",
214
- 3:"Connection Refused: server unavailable",
215
- 4:"Connection Refused: bad user name or password",
216
- 5:"Connection Refused: not authorized"
217
- };
218
-
219
- /**
220
- * Format an error message text.
221
- * @private
222
- * @param {error} ERROR value above.
223
- * @param {substitutions} [array] substituted into the text.
224
- * @return the text with the substitutions made.
225
- */
226
- var format = function(error, substitutions) {
227
- var text = error.text;
228
- if (substitutions) {
229
- var field,start;
230
- for (var i=0; i<substitutions.length; i++) {
231
- field = "{"+i+"}";
232
- start = text.indexOf(field);
233
- if(start > 0) {
234
- var part1 = text.substring(0,start);
235
- var part2 = text.substring(start+field.length);
236
- text = part1+substitutions[i]+part2;
237
- }
238
- }
239
- }
240
- return text;
241
- };
242
-
243
- //MQTT protocol and version 6 M Q I s d p 3
244
- var MqttProtoIdentifierv3 = [0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03];
245
- //MQTT proto/version for 311 4 M Q T T 4
246
- var MqttProtoIdentifierv4 = [0x00,0x04,0x4d,0x51,0x54,0x54,0x04];
247
-
248
- /**
249
- * Construct an MQTT wire protocol message.
250
- * @param type MQTT packet type.
251
- * @param options optional wire message attributes.
252
- *
253
- * Optional properties
254
- *
255
- * messageIdentifier: message ID in the range [0..65535]
256
- * payloadMessage: Application Message - PUBLISH only
257
- * connectStrings: array of 0 or more Strings to be put into the CONNECT payload
258
- * topics: array of strings (SUBSCRIBE, UNSUBSCRIBE)
259
- * requestQoS: array of QoS values [0..2]
260
- *
261
- * "Flag" properties
262
- * cleanSession: true if present / false if absent (CONNECT)
263
- * willMessage: true if present / false if absent (CONNECT)
264
- * isRetained: true if present / false if absent (CONNECT)
265
- * userName: true if present / false if absent (CONNECT)
266
- * password: true if present / false if absent (CONNECT)
267
- * keepAliveInterval: integer [0..65535] (CONNECT)
268
- *
269
- * @private
270
- * @ignore
271
- */
272
- var WireMessage = function (type, options) {
273
- this.type = type;
274
- for (var name in options) {
275
- if (options.hasOwnProperty(name)) {
276
- this[name] = options[name];
277
- }
278
- }
279
- };
280
-
281
- WireMessage.prototype.encode = function() {
282
- // Compute the first byte of the fixed header
283
- var first = ((this.type & 0x0f) << 4);
284
-
285
- /*
286
- * Now calculate the length of the variable header + payload by adding up the lengths
287
- * of all the component parts
288
- */
289
-
290
- var remLength = 0;
291
- var topicStrLength = [];
292
- var destinationNameLength = 0;
293
- var willMessagePayloadBytes;
294
-
295
- // if the message contains a messageIdentifier then we need two bytes for that
296
- if (this.messageIdentifier !== undefined)
297
- remLength += 2;
298
-
299
- switch(this.type) {
300
- // If this a Connect then we need to include 12 bytes for its header
301
- case MESSAGE_TYPE.CONNECT:
302
- switch(this.mqttVersion) {
303
- case 3:
304
- remLength += MqttProtoIdentifierv3.length + 3;
305
- break;
306
- case 4:
307
- remLength += MqttProtoIdentifierv4.length + 3;
308
- break;
309
- }
310
-
311
- remLength += UTF8Length(this.clientId) + 2;
312
- if (this.willMessage !== undefined) {
313
- remLength += UTF8Length(this.willMessage.destinationName) + 2;
314
- // Will message is always a string, sent as UTF-8 characters with a preceding length.
315
- willMessagePayloadBytes = this.willMessage.payloadBytes;
316
- if (!(willMessagePayloadBytes instanceof Uint8Array))
317
- willMessagePayloadBytes = new Uint8Array(payloadBytes);
318
- remLength += willMessagePayloadBytes.byteLength +2;
319
- }
320
- if (this.userName !== undefined)
321
- remLength += UTF8Length(this.userName) + 2;
322
- if (this.password !== undefined)
323
- remLength += UTF8Length(this.password) + 2;
324
- break;
325
-
326
- // Subscribe, Unsubscribe can both contain topic strings
327
- case MESSAGE_TYPE.SUBSCRIBE:
328
- first |= 0x02; // Qos = 1;
329
- for ( var i = 0; i < this.topics.length; i++) {
330
- topicStrLength[i] = UTF8Length(this.topics[i]);
331
- remLength += topicStrLength[i] + 2;
332
- }
333
- remLength += this.requestedQos.length; // 1 byte for each topic's Qos
334
- // QoS on Subscribe only
335
- break;
336
-
337
- case MESSAGE_TYPE.UNSUBSCRIBE:
338
- first |= 0x02; // Qos = 1;
339
- for ( var i = 0; i < this.topics.length; i++) {
340
- topicStrLength[i] = UTF8Length(this.topics[i]);
341
- remLength += topicStrLength[i] + 2;
342
- }
343
- break;
344
-
345
- case MESSAGE_TYPE.PUBREL:
346
- first |= 0x02; // Qos = 1;
347
- break;
348
-
349
- case MESSAGE_TYPE.PUBLISH:
350
- if (this.payloadMessage.duplicate) first |= 0x08;
351
- first = first |= (this.payloadMessage.qos << 1);
352
- if (this.payloadMessage.retained) first |= 0x01;
353
- destinationNameLength = UTF8Length(this.payloadMessage.destinationName);
354
- remLength += destinationNameLength + 2;
355
- var payloadBytes = this.payloadMessage.payloadBytes;
356
- remLength += payloadBytes.byteLength;
357
- if (payloadBytes instanceof ArrayBuffer)
358
- payloadBytes = new Uint8Array(payloadBytes);
359
- else if (!(payloadBytes instanceof Uint8Array))
360
- payloadBytes = new Uint8Array(payloadBytes.buffer);
361
- break;
362
-
363
- case MESSAGE_TYPE.DISCONNECT:
364
- break;
365
-
366
- default:
367
- break;
368
- }
369
-
370
- // Now we can allocate a buffer for the message
371
-
372
- var mbi = encodeMBI(remLength); // Convert the length to MQTT MBI format
373
- var pos = mbi.length + 1; // Offset of start of variable header
374
- var buffer = new ArrayBuffer(remLength + pos);
375
- var byteStream = new Uint8Array(buffer); // view it as a sequence of bytes
376
-
377
- //Write the fixed header into the buffer
378
- byteStream[0] = first;
379
- byteStream.set(mbi,1);
380
-
381
- // If this is a PUBLISH then the variable header starts with a topic
382
- if (this.type == MESSAGE_TYPE.PUBLISH)
383
- pos = writeString(this.payloadMessage.destinationName, destinationNameLength, byteStream, pos);
384
- // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time
385
-
386
- else if (this.type == MESSAGE_TYPE.CONNECT) {
387
- switch (this.mqttVersion) {
388
- case 3:
389
- byteStream.set(MqttProtoIdentifierv3, pos);
390
- pos += MqttProtoIdentifierv3.length;
391
- break;
392
- case 4:
393
- byteStream.set(MqttProtoIdentifierv4, pos);
394
- pos += MqttProtoIdentifierv4.length;
395
- break;
396
- }
397
- var connectFlags = 0;
398
- if (this.cleanSession)
399
- connectFlags = 0x02;
400
- if (this.willMessage !== undefined ) {
401
- connectFlags |= 0x04;
402
- connectFlags |= (this.willMessage.qos<<3);
403
- if (this.willMessage.retained) {
404
- connectFlags |= 0x20;
405
- }
406
- }
407
- if (this.userName !== undefined)
408
- connectFlags |= 0x80;
409
- if (this.password !== undefined)
410
- connectFlags |= 0x40;
411
- byteStream[pos++] = connectFlags;
412
- pos = writeUint16 (this.keepAliveInterval, byteStream, pos);
413
- }
414
-
415
- // Output the messageIdentifier - if there is one
416
- if (this.messageIdentifier !== undefined)
417
- pos = writeUint16 (this.messageIdentifier, byteStream, pos);
418
-
419
- switch(this.type) {
420
- case MESSAGE_TYPE.CONNECT:
421
- pos = writeString(this.clientId, UTF8Length(this.clientId), byteStream, pos);
422
- if (this.willMessage !== undefined) {
423
- pos = writeString(this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, pos);
424
- pos = writeUint16(willMessagePayloadBytes.byteLength, byteStream, pos);
425
- byteStream.set(willMessagePayloadBytes, pos);
426
- pos += willMessagePayloadBytes.byteLength;
427
-
428
- }
429
- if (this.userName !== undefined)
430
- pos = writeString(this.userName, UTF8Length(this.userName), byteStream, pos);
431
- if (this.password !== undefined)
432
- pos = writeString(this.password, UTF8Length(this.password), byteStream, pos);
433
- break;
434
-
435
- case MESSAGE_TYPE.PUBLISH:
436
- // PUBLISH has a text or binary payload, if text do not add a 2 byte length field, just the UTF characters.
437
- byteStream.set(payloadBytes, pos);
438
-
439
- break;
440
-
441
- // case MESSAGE_TYPE.PUBREC:
442
- // case MESSAGE_TYPE.PUBREL:
443
- // case MESSAGE_TYPE.PUBCOMP:
444
- // break;
445
-
446
- case MESSAGE_TYPE.SUBSCRIBE:
447
- // SUBSCRIBE has a list of topic strings and request QoS
448
- for (var i=0; i<this.topics.length; i++) {
449
- pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos);
450
- byteStream[pos++] = this.requestedQos[i];
451
- }
452
- break;
453
-
454
- case MESSAGE_TYPE.UNSUBSCRIBE:
455
- // UNSUBSCRIBE has a list of topic strings
456
- for (var i=0; i<this.topics.length; i++)
457
- pos = writeString(this.topics[i], topicStrLength[i], byteStream, pos);
458
- break;
459
-
460
- default:
461
- // Do nothing.
462
- }
463
-
464
- return buffer;
465
- };
466
-
467
- function decodeMessage(input,pos) {
468
- var startingPos = pos;
469
- var first = input[pos];
470
- var type = first >> 4;
471
- var messageInfo = first &= 0x0f;
472
- pos += 1;
473
-
474
-
475
- // Decode the remaining length (MBI format)
476
-
477
- var digit;
478
- var remLength = 0;
479
- var multiplier = 1;
480
- do {
481
- if (pos == input.length) {
482
- return [null,startingPos];
483
- }
484
- digit = input[pos++];
485
- remLength += ((digit & 0x7F) * multiplier);
486
- multiplier *= 128;
487
- } while ((digit & 0x80) !== 0);
488
-
489
- var endPos = pos+remLength;
490
- if (endPos > input.length) {
491
- return [null,startingPos];
492
- }
493
-
494
- var wireMessage = new WireMessage(type);
495
- switch(type) {
496
- case MESSAGE_TYPE.CONNACK:
497
- var connectAcknowledgeFlags = input[pos++];
498
- if (connectAcknowledgeFlags & 0x01)
499
- wireMessage.sessionPresent = true;
500
- wireMessage.returnCode = input[pos++];
501
- break;
502
-
503
- case MESSAGE_TYPE.PUBLISH:
504
- var qos = (messageInfo >> 1) & 0x03;
505
-
506
- var len = readUint16(input, pos);
507
- pos += 2;
508
- var topicName = parseUTF8(input, pos, len);
509
- pos += len;
510
- // If QoS 1 or 2 there will be a messageIdentifier
511
- if (qos > 0) {
512
- wireMessage.messageIdentifier = readUint16(input, pos);
513
- pos += 2;
514
- }
515
-
516
- var message = new Message(input.subarray(pos, endPos));
517
- if ((messageInfo & 0x01) == 0x01)
518
- message.retained = true;
519
- if ((messageInfo & 0x08) == 0x08)
520
- message.duplicate = true;
521
- message.qos = qos;
522
- message.destinationName = topicName;
523
- wireMessage.payloadMessage = message;
524
- break;
525
-
526
- case MESSAGE_TYPE.PUBACK:
527
- case MESSAGE_TYPE.PUBREC:
528
- case MESSAGE_TYPE.PUBREL:
529
- case MESSAGE_TYPE.PUBCOMP:
530
- case MESSAGE_TYPE.UNSUBACK:
531
- wireMessage.messageIdentifier = readUint16(input, pos);
532
- break;
533
-
534
- case MESSAGE_TYPE.SUBACK:
535
- wireMessage.messageIdentifier = readUint16(input, pos);
536
- pos += 2;
537
- wireMessage.returnCode = input.subarray(pos, endPos);
538
- break;
539
-
540
- default:
541
- break;
542
- }
543
-
544
- return [wireMessage,endPos];
545
- }
546
-
547
- function writeUint16(input, buffer, offset) {
548
- buffer[offset++] = input >> 8; //MSB
549
- buffer[offset++] = input % 256; //LSB
550
- return offset;
551
- }
552
-
553
- function writeString(input, utf8Length, buffer, offset) {
554
- offset = writeUint16(utf8Length, buffer, offset);
555
- stringToUTF8(input, buffer, offset);
556
- return offset + utf8Length;
557
- }
558
-
559
- function readUint16(buffer, offset) {
560
- return 256*buffer[offset] + buffer[offset+1];
561
- }
562
-
563
- /**
564
- * Encodes an MQTT Multi-Byte Integer
565
- * @private
566
- */
567
- function encodeMBI(number) {
568
- var output = new Array(1);
569
- var numBytes = 0;
570
-
571
- do {
572
- var digit = number % 128;
573
- number = number >> 7;
574
- if (number > 0) {
575
- digit |= 0x80;
576
- }
577
- output[numBytes++] = digit;
578
- } while ( (number > 0) && (numBytes<4) );
579
-
580
- return output;
581
- }
582
-
583
- /**
584
- * Takes a String and calculates its length in bytes when encoded in UTF8.
585
- * @private
586
- */
587
- function UTF8Length(input) {
588
- var output = 0;
589
- for (var i = 0; i<input.length; i++)
590
- {
591
- var charCode = input.charCodeAt(i);
592
- if (charCode > 0x7FF)
593
- {
594
- // Surrogate pair means its a 4 byte character
595
- if (0xD800 <= charCode && charCode <= 0xDBFF)
596
- {
597
- i++;
598
- output++;
599
- }
600
- output +=3;
601
- }
602
- else if (charCode > 0x7F)
603
- output +=2;
604
- else
605
- output++;
606
- }
607
- return output;
608
- }
609
-
610
- /**
611
- * Takes a String and writes it into an array as UTF8 encoded bytes.
612
- * @private
613
- */
614
- function stringToUTF8(input, output, start) {
615
- var pos = start;
616
- for (var i = 0; i<input.length; i++) {
617
- var charCode = input.charCodeAt(i);
618
-
619
- // Check for a surrogate pair.
620
- if (0xD800 <= charCode && charCode <= 0xDBFF) {
621
- var lowCharCode = input.charCodeAt(++i);
622
- if (isNaN(lowCharCode)) {
623
- throw new Error(format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode]));
624
- }
625
- charCode = ((charCode - 0xD800)<<10) + (lowCharCode - 0xDC00) + 0x10000;
626
-
627
- }
628
-
629
- if (charCode <= 0x7F) {
630
- output[pos++] = charCode;
631
- } else if (charCode <= 0x7FF) {
632
- output[pos++] = charCode>>6 & 0x1F | 0xC0;
633
- output[pos++] = charCode & 0x3F | 0x80;
634
- } else if (charCode <= 0xFFFF) {
635
- output[pos++] = charCode>>12 & 0x0F | 0xE0;
636
- output[pos++] = charCode>>6 & 0x3F | 0x80;
637
- output[pos++] = charCode & 0x3F | 0x80;
638
- } else {
639
- output[pos++] = charCode>>18 & 0x07 | 0xF0;
640
- output[pos++] = charCode>>12 & 0x3F | 0x80;
641
- output[pos++] = charCode>>6 & 0x3F | 0x80;
642
- output[pos++] = charCode & 0x3F | 0x80;
643
- }
644
- }
645
- return output;
646
- }
647
-
648
- function parseUTF8(input, offset, length) {
649
- var output = "";
650
- var utf16;
651
- var pos = offset;
652
-
653
- while (pos < offset+length)
654
- {
655
- var byte1 = input[pos++];
656
- if (byte1 < 128)
657
- utf16 = byte1;
658
- else
659
- {
660
- var byte2 = input[pos++]-128;
661
- if (byte2 < 0)
662
- throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16),""]));
663
- if (byte1 < 0xE0) // 2 byte character
664
- utf16 = 64*(byte1-0xC0) + byte2;
665
- else
666
- {
667
- var byte3 = input[pos++]-128;
668
- if (byte3 < 0)
669
- throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16)]));
670
- if (byte1 < 0xF0) // 3 byte character
671
- utf16 = 4096*(byte1-0xE0) + 64*byte2 + byte3;
672
- else
673
- {
674
- var byte4 = input[pos++]-128;
675
- if (byte4 < 0)
676
- throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)]));
677
- if (byte1 < 0xF8) // 4 byte character
678
- utf16 = 262144*(byte1-0xF0) + 4096*byte2 + 64*byte3 + byte4;
679
- else // longer encodings are not supported
680
- throw new Error(format(ERROR.MALFORMED_UTF, [byte1.toString(16), byte2.toString(16), byte3.toString(16), byte4.toString(16)]));
681
- }
682
- }
683
- }
684
-
685
- if (utf16 > 0xFFFF) // 4 byte character - express as a surrogate pair
686
- {
687
- utf16 -= 0x10000;
688
- output += String.fromCharCode(0xD800 + (utf16 >> 10)); // lead character
689
- utf16 = 0xDC00 + (utf16 & 0x3FF); // trail character
690
- }
691
- output += String.fromCharCode(utf16);
692
- }
693
- return output;
694
- }
695
-
696
- /**
697
- * Repeat keepalive requests, monitor responses.
698
- * @ignore
699
- */
700
- var Pinger = function(client, keepAliveInterval) {
701
- this._client = client;
702
- this._keepAliveInterval = keepAliveInterval*1000;
703
- this.isReset = false;
704
-
705
- var pingReq = new WireMessage(MESSAGE_TYPE.PINGREQ).encode();
706
-
707
- var doTimeout = function (pinger) {
708
- return function () {
709
- return doPing.apply(pinger);
710
- };
711
- };
712
-
713
- /** @ignore */
714
- var doPing = function() {
715
- if (!this.isReset) {
716
- this._client._trace("Pinger.doPing", "Timed out");
717
- this._client._disconnected( ERROR.PING_TIMEOUT.code , format(ERROR.PING_TIMEOUT));
718
- } else {
719
- this.isReset = false;
720
- this._client._trace("Pinger.doPing", "send PINGREQ");
721
- this._client.socket.send(pingReq);
722
- this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);
723
- }
724
- };
725
-
726
- this.reset = function() {
727
- this.isReset = true;
728
- clearTimeout(this.timeout);
729
- if (this._keepAliveInterval > 0)
730
- this.timeout = setTimeout(doTimeout(this), this._keepAliveInterval);
731
- };
732
-
733
- this.cancel = function() {
734
- clearTimeout(this.timeout);
735
- };
736
- };
737
-
738
- /**
739
- * Monitor request completion.
740
- * @ignore
741
- */
742
- var Timeout = function(client, timeoutSeconds, action, args) {
743
- if (!timeoutSeconds)
744
- timeoutSeconds = 30;
745
-
746
- var doTimeout = function (action, client, args) {
747
- return function () {
748
- return action.apply(client, args);
749
- };
750
- };
751
- this.timeout = setTimeout(doTimeout(action, client, args), timeoutSeconds * 1000);
752
-
753
- this.cancel = function() {
754
- clearTimeout(this.timeout);
755
- };
756
- };
757
-
758
- /**
759
- * Internal implementation of the Websockets MQTT V3.1 client.
760
- *
761
- * @name Paho.ClientImpl @constructor
762
- * @param {String} host the DNS nameof the webSocket host.
763
- * @param {Number} port the port number for that host.
764
- * @param {String} clientId the MQ client identifier.
765
- */
766
- var ClientImpl = function (uri, host, port, path, clientId) {
767
- // Check dependencies are satisfied in this browser.
768
- if (!("WebSocket" in global && global.WebSocket !== null)) {
769
- throw new Error(format(ERROR.UNSUPPORTED, ["WebSocket"]));
770
- }
771
- if (!("ArrayBuffer" in global && global.ArrayBuffer !== null)) {
772
- throw new Error(format(ERROR.UNSUPPORTED, ["ArrayBuffer"]));
773
- }
774
- this._trace("Paho.Client", uri, host, port, path, clientId);
775
-
776
- this.host = host;
777
- this.port = port;
778
- this.path = path;
779
- this.uri = uri;
780
- this.clientId = clientId;
781
- this._wsuri = null;
782
-
783
- // Local storagekeys are qualified with the following string.
784
- // The conditional inclusion of path in the key is for backward
785
- // compatibility to when the path was not configurable and assumed to
786
- // be /mqtt
787
- this._localKey=host+":"+port+(path!="/mqtt"?":"+path:"")+":"+clientId+":";
788
-
789
- // Create private instance-only message queue
790
- // Internal queue of messages to be sent, in sending order.
791
- this._msg_queue = [];
792
- this._buffered_msg_queue = [];
793
-
794
- // Messages we have sent and are expecting a response for, indexed by their respective message ids.
795
- this._sentMessages = {};
796
-
797
- // Messages we have received and acknowleged and are expecting a confirm message for
798
- // indexed by their respective message ids.
799
- this._receivedMessages = {};
800
-
801
- // Internal list of callbacks to be executed when messages
802
- // have been successfully sent over web socket, e.g. disconnect
803
- // when it doesn't have to wait for ACK, just message is dispatched.
804
- this._notify_msg_sent = {};
805
-
806
- // Unique identifier for SEND messages, incrementing
807
- // counter as messages are sent.
808
- this._message_identifier = 1;
809
-
810
- // Used to determine the transmission sequence of stored sent messages.
811
- this._sequence = 0;
812
-
813
-
814
- // Load the local state, if any, from the saved version, only restore state relevant to this client.
815
- for (var key in localStorage)
816
- if ( key.indexOf("Sent:"+this._localKey) === 0 || key.indexOf("Received:"+this._localKey) === 0)
817
- this.restore(key);
818
- };
819
-
820
- // Messaging Client public instance members.
821
- ClientImpl.prototype.host = null;
822
- ClientImpl.prototype.port = null;
823
- ClientImpl.prototype.path = null;
824
- ClientImpl.prototype.uri = null;
825
- ClientImpl.prototype.clientId = null;
826
-
827
- // Messaging Client private instance members.
828
- ClientImpl.prototype.socket = null;
829
- /* true once we have received an acknowledgement to a CONNECT packet. */
830
- ClientImpl.prototype.connected = false;
831
- /* The largest message identifier allowed, may not be larger than 2**16 but
832
- * if set smaller reduces the maximum number of outbound messages allowed.
833
- */
834
- ClientImpl.prototype.maxMessageIdentifier = 65536;
835
- ClientImpl.prototype.connectOptions = null;
836
- ClientImpl.prototype.hostIndex = null;
837
- ClientImpl.prototype.onConnected = null;
838
- ClientImpl.prototype.onConnectionLost = null;
839
- ClientImpl.prototype.onMessageDelivered = null;
840
- ClientImpl.prototype.onMessageArrived = null;
841
- ClientImpl.prototype.traceFunction = null;
842
- ClientImpl.prototype._msg_queue = null;
843
- ClientImpl.prototype._buffered_msg_queue = null;
844
- ClientImpl.prototype._connectTimeout = null;
845
- /* The sendPinger monitors how long we allow before we send data to prove to the server that we are alive. */
846
- ClientImpl.prototype.sendPinger = null;
847
- /* The receivePinger monitors how long we allow before we require evidence that the server is alive. */
848
- ClientImpl.prototype.receivePinger = null;
849
- ClientImpl.prototype._reconnectInterval = 1; // Reconnect Delay, starts at 1 second
850
- ClientImpl.prototype._reconnecting = false;
851
- ClientImpl.prototype._reconnectTimeout = null;
852
- ClientImpl.prototype.disconnectedPublishing = false;
853
- ClientImpl.prototype.disconnectedBufferSize = 5000;
854
-
855
- ClientImpl.prototype.receiveBuffer = null;
856
-
857
- ClientImpl.prototype._traceBuffer = null;
858
- ClientImpl.prototype._MAX_TRACE_ENTRIES = 100;
859
-
860
- ClientImpl.prototype.connect = function (connectOptions) {
861
- var connectOptionsMasked = this._traceMask(connectOptions, "password");
862
- this._trace("Client.connect", connectOptionsMasked, this.socket, this.connected);
863
-
864
- if (this.connected)
865
- throw new Error(format(ERROR.INVALID_STATE, ["already connected"]));
866
- if (this.socket)
867
- throw new Error(format(ERROR.INVALID_STATE, ["already connected"]));
868
-
869
- if (this._reconnecting) {
870
- // connect() function is called while reconnect is in progress.
871
- // Terminate the auto reconnect process to use new connect options.
872
- this._reconnectTimeout.cancel();
873
- this._reconnectTimeout = null;
874
- this._reconnecting = false;
875
- }
876
-
877
- this.connectOptions = connectOptions;
878
- this._reconnectInterval = 1;
879
- this._reconnecting = false;
880
- if (connectOptions.uris) {
881
- this.hostIndex = 0;
882
- this._doConnect(connectOptions.uris[0]);
883
- } else {
884
- this._doConnect(this.uri);
885
- }
886
-
887
- };
888
-
889
- ClientImpl.prototype.subscribe = function (filter, subscribeOptions) {
890
- this._trace("Client.subscribe", filter, subscribeOptions);
891
-
892
- if (!this.connected)
893
- throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
894
-
895
- var wireMessage = new WireMessage(MESSAGE_TYPE.SUBSCRIBE);
896
- wireMessage.topics = filter.constructor === Array ? filter : [filter];
897
- if (subscribeOptions.qos === undefined)
898
- subscribeOptions.qos = 0;
899
- wireMessage.requestedQos = [];
900
- for (var i = 0; i < wireMessage.topics.length; i++)
901
- wireMessage.requestedQos[i] = subscribeOptions.qos;
902
-
903
- if (subscribeOptions.onSuccess) {
904
- wireMessage.onSuccess = function(grantedQos) {subscribeOptions.onSuccess({invocationContext:subscribeOptions.invocationContext,grantedQos:grantedQos});};
905
- }
906
-
907
- if (subscribeOptions.onFailure) {
908
- wireMessage.onFailure = function(errorCode) {subscribeOptions.onFailure({invocationContext:subscribeOptions.invocationContext,errorCode:errorCode, errorMessage:format(errorCode)});};
909
- }
910
-
911
- if (subscribeOptions.timeout) {
912
- wireMessage.timeOut = new Timeout(this, subscribeOptions.timeout, subscribeOptions.onFailure,
913
- [{invocationContext:subscribeOptions.invocationContext,
914
- errorCode:ERROR.SUBSCRIBE_TIMEOUT.code,
915
- errorMessage:format(ERROR.SUBSCRIBE_TIMEOUT)}]);
916
- }
917
-
918
- // All subscriptions return a SUBACK.
919
- this._requires_ack(wireMessage);
920
- this._schedule_message(wireMessage);
921
- };
922
-
923
- /** @ignore */
924
- ClientImpl.prototype.unsubscribe = function(filter, unsubscribeOptions) {
925
- this._trace("Client.unsubscribe", filter, unsubscribeOptions);
926
-
927
- if (!this.connected)
928
- throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
929
-
930
- var wireMessage = new WireMessage(MESSAGE_TYPE.UNSUBSCRIBE);
931
- wireMessage.topics = filter.constructor === Array ? filter : [filter];
932
-
933
- if (unsubscribeOptions.onSuccess) {
934
- wireMessage.callback = function() {unsubscribeOptions.onSuccess({invocationContext:unsubscribeOptions.invocationContext});};
935
- }
936
- if (unsubscribeOptions.timeout) {
937
- wireMessage.timeOut = new Timeout(this, unsubscribeOptions.timeout, unsubscribeOptions.onFailure,
938
- [{invocationContext:unsubscribeOptions.invocationContext,
939
- errorCode:ERROR.UNSUBSCRIBE_TIMEOUT.code,
940
- errorMessage:format(ERROR.UNSUBSCRIBE_TIMEOUT)}]);
941
- }
942
-
943
- // All unsubscribes return a SUBACK.
944
- this._requires_ack(wireMessage);
945
- this._schedule_message(wireMessage);
946
- };
947
-
948
- ClientImpl.prototype.send = function (message) {
949
- this._trace("Client.send", message);
950
-
951
- var wireMessage = new WireMessage(MESSAGE_TYPE.PUBLISH);
952
- wireMessage.payloadMessage = message;
953
-
954
- if (this.connected) {
955
- // Mark qos 1 & 2 message as "ACK required"
956
- // For qos 0 message, invoke onMessageDelivered callback if there is one.
957
- // Then schedule the message.
958
- if (message.qos > 0) {
959
- this._requires_ack(wireMessage);
960
- } else if (this.onMessageDelivered) {
961
- this._notify_msg_sent[wireMessage] = this.onMessageDelivered(wireMessage.payloadMessage);
962
- }
963
- this._schedule_message(wireMessage);
964
- } else {
965
- // Currently disconnected, will not schedule this message
966
- // Check if reconnecting is in progress and disconnected publish is enabled.
967
- if (this._reconnecting && this.disconnectedPublishing) {
968
- // Check the limit which include the "required ACK" messages
969
- var messageCount = Object.keys(this._sentMessages).length + this._buffered_msg_queue.length;
970
- if (messageCount > this.disconnectedBufferSize) {
971
- throw new Error(format(ERROR.BUFFER_FULL, [this.disconnectedBufferSize]));
972
- } else {
973
- if (message.qos > 0) {
974
- // Mark this message as "ACK required"
975
- this._requires_ack(wireMessage);
976
- } else {
977
- wireMessage.sequence = ++this._sequence;
978
- // Add messages in fifo order to array, by adding to start
979
- this._buffered_msg_queue.unshift(wireMessage);
980
- }
981
- }
982
- } else {
983
- throw new Error(format(ERROR.INVALID_STATE, ["not connected"]));
984
- }
985
- }
986
- };
987
-
988
- ClientImpl.prototype.disconnect = function () {
989
- this._trace("Client.disconnect");
990
-
991
- if (this._reconnecting) {
992
- // disconnect() function is called while reconnect is in progress.
993
- // Terminate the auto reconnect process.
994
- this._reconnectTimeout.cancel();
995
- this._reconnectTimeout = null;
996
- this._reconnecting = false;
997
- }
998
-
999
- if (!this.socket)
1000
- throw new Error(format(ERROR.INVALID_STATE, ["not connecting or connected"]));
1001
-
1002
- var wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT);
1003
-
1004
- // Run the disconnected call back as soon as the message has been sent,
1005
- // in case of a failure later on in the disconnect processing.
1006
- // as a consequence, the _disconected call back may be run several times.
1007
- this._notify_msg_sent[wireMessage] = scope(this._disconnected, this);
1008
-
1009
- this._schedule_message(wireMessage);
1010
- };
1011
-
1012
- ClientImpl.prototype.getTraceLog = function () {
1013
- if ( this._traceBuffer !== null ) {
1014
- this._trace("Client.getTraceLog", new Date());
1015
- this._trace("Client.getTraceLog in flight messages", this._sentMessages.length);
1016
- for (var key in this._sentMessages)
1017
- this._trace("_sentMessages ",key, this._sentMessages[key]);
1018
- for (var key in this._receivedMessages)
1019
- this._trace("_receivedMessages ",key, this._receivedMessages[key]);
1020
-
1021
- return this._traceBuffer;
1022
- }
1023
- };
1024
-
1025
- ClientImpl.prototype.startTrace = function () {
1026
- if ( this._traceBuffer === null ) {
1027
- this._traceBuffer = [];
1028
- }
1029
- this._trace("Client.startTrace", new Date(), version);
1030
- };
1031
-
1032
- ClientImpl.prototype.stopTrace = function () {
1033
- delete this._traceBuffer;
1034
- };
1035
-
1036
- ClientImpl.prototype._doConnect = function (wsurl) {
1037
- // When the socket is open, this client will send the CONNECT WireMessage using the saved parameters.
1038
- if (this.connectOptions.useSSL) {
1039
- var uriParts = wsurl.split(":");
1040
- uriParts[0] = "wss";
1041
- wsurl = uriParts.join(":");
1042
- }
1043
- this._wsuri = wsurl;
1044
- this.connected = false;
1045
-
1046
-
1047
-
1048
- if (this.connectOptions.mqttVersion < 4) {
1049
- this.socket = new WebSocket(wsurl, ["mqttv3.1"]);
1050
- } else {
1051
- this.socket = new WebSocket(wsurl, ["mqtt"]);
1052
- }
1053
- this.socket.binaryType = "arraybuffer";
1054
- this.socket.onopen = scope(this._on_socket_open, this);
1055
- this.socket.onmessage = scope(this._on_socket_message, this);
1056
- this.socket.onerror = scope(this._on_socket_error, this);
1057
- this.socket.onclose = scope(this._on_socket_close, this);
1058
-
1059
- this.sendPinger = new Pinger(this, this.connectOptions.keepAliveInterval);
1060
- this.receivePinger = new Pinger(this, this.connectOptions.keepAliveInterval);
1061
- if (this._connectTimeout) {
1062
- this._connectTimeout.cancel();
1063
- this._connectTimeout = null;
1064
- }
1065
- this._connectTimeout = new Timeout(this, this.connectOptions.timeout, this._disconnected, [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)]);
1066
- };
1067
-
1068
-
1069
- // Schedule a new message to be sent over the WebSockets
1070
- // connection. CONNECT messages cause WebSocket connection
1071
- // to be started. All other messages are queued internally
1072
- // until this has happened. When WS connection starts, process
1073
- // all outstanding messages.
1074
- ClientImpl.prototype._schedule_message = function (message) {
1075
- // Add messages in fifo order to array, by adding to start
1076
- this._msg_queue.unshift(message);
1077
- // Process outstanding messages in the queue if we have an open socket, and have received CONNACK.
1078
- if (this.connected) {
1079
- this._process_queue();
1080
- }
1081
- };
1082
-
1083
- ClientImpl.prototype.store = function(prefix, wireMessage) {
1084
- var storedMessage = {type:wireMessage.type, messageIdentifier:wireMessage.messageIdentifier, version:1};
1085
-
1086
- switch(wireMessage.type) {
1087
- case MESSAGE_TYPE.PUBLISH:
1088
- if(wireMessage.pubRecReceived)
1089
- storedMessage.pubRecReceived = true;
1090
-
1091
- // Convert the payload to a hex string.
1092
- storedMessage.payloadMessage = {};
1093
- var hex = "";
1094
- var messageBytes = wireMessage.payloadMessage.payloadBytes;
1095
- for (var i=0; i<messageBytes.length; i++) {
1096
- if (messageBytes[i] <= 0xF)
1097
- hex = hex+"0"+messageBytes[i].toString(16);
1098
- else
1099
- hex = hex+messageBytes[i].toString(16);
1100
- }
1101
- storedMessage.payloadMessage.payloadHex = hex;
1102
-
1103
- storedMessage.payloadMessage.qos = wireMessage.payloadMessage.qos;
1104
- storedMessage.payloadMessage.destinationName = wireMessage.payloadMessage.destinationName;
1105
- if (wireMessage.payloadMessage.duplicate)
1106
- storedMessage.payloadMessage.duplicate = true;
1107
- if (wireMessage.payloadMessage.retained)
1108
- storedMessage.payloadMessage.retained = true;
1109
-
1110
- // Add a sequence number to sent messages.
1111
- if ( prefix.indexOf("Sent:") === 0 ) {
1112
- if ( wireMessage.sequence === undefined )
1113
- wireMessage.sequence = ++this._sequence;
1114
- storedMessage.sequence = wireMessage.sequence;
1115
- }
1116
- break;
1117
-
1118
- default:
1119
- throw Error(format(ERROR.INVALID_STORED_DATA, [prefix+this._localKey+wireMessage.messageIdentifier, storedMessage]));
1120
- }
1121
- localStorage.setItem(prefix+this._localKey+wireMessage.messageIdentifier, JSON.stringify(storedMessage));
1122
- };
1123
-
1124
- ClientImpl.prototype.restore = function(key) {
1125
- var value = localStorage.getItem(key);
1126
- var storedMessage = JSON.parse(value);
1127
-
1128
- var wireMessage = new WireMessage(storedMessage.type, storedMessage);
1129
-
1130
- switch(storedMessage.type) {
1131
- case MESSAGE_TYPE.PUBLISH:
1132
- // Replace the payload message with a Message object.
1133
- var hex = storedMessage.payloadMessage.payloadHex;
1134
- var buffer = new ArrayBuffer((hex.length)/2);
1135
- var byteStream = new Uint8Array(buffer);
1136
- var i = 0;
1137
- while (hex.length >= 2) {
1138
- var x = parseInt(hex.substring(0, 2), 16);
1139
- hex = hex.substring(2, hex.length);
1140
- byteStream[i++] = x;
1141
- }
1142
- var payloadMessage = new Message(byteStream);
1143
-
1144
- payloadMessage.qos = storedMessage.payloadMessage.qos;
1145
- payloadMessage.destinationName = storedMessage.payloadMessage.destinationName;
1146
- if (storedMessage.payloadMessage.duplicate)
1147
- payloadMessage.duplicate = true;
1148
- if (storedMessage.payloadMessage.retained)
1149
- payloadMessage.retained = true;
1150
- wireMessage.payloadMessage = payloadMessage;
1151
-
1152
- break;
1153
-
1154
- default:
1155
- throw Error(format(ERROR.INVALID_STORED_DATA, [key, value]));
1156
- }
1157
-
1158
- if (key.indexOf("Sent:"+this._localKey) === 0) {
1159
- wireMessage.payloadMessage.duplicate = true;
1160
- this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1161
- } else if (key.indexOf("Received:"+this._localKey) === 0) {
1162
- this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1163
- }
1164
- };
1165
-
1166
- ClientImpl.prototype._process_queue = function () {
1167
- var message = null;
1168
-
1169
- // Send all queued messages down socket connection
1170
- while ((message = this._msg_queue.pop())) {
1171
- this._socket_send(message);
1172
- // Notify listeners that message was successfully sent
1173
- if (this._notify_msg_sent[message]) {
1174
- this._notify_msg_sent[message]();
1175
- delete this._notify_msg_sent[message];
1176
- }
1177
- }
1178
- };
1179
-
1180
- /**
1181
- * Expect an ACK response for this message. Add message to the set of in progress
1182
- * messages and set an unused identifier in this message.
1183
- * @ignore
1184
- */
1185
- ClientImpl.prototype._requires_ack = function (wireMessage) {
1186
- var messageCount = Object.keys(this._sentMessages).length;
1187
- if (messageCount > this.maxMessageIdentifier)
1188
- throw Error ("Too many messages:"+messageCount);
1189
-
1190
- while(this._sentMessages[this._message_identifier] !== undefined) {
1191
- this._message_identifier++;
1192
- }
1193
- wireMessage.messageIdentifier = this._message_identifier;
1194
- this._sentMessages[wireMessage.messageIdentifier] = wireMessage;
1195
- if (wireMessage.type === MESSAGE_TYPE.PUBLISH) {
1196
- this.store("Sent:", wireMessage);
1197
- }
1198
- if (this._message_identifier === this.maxMessageIdentifier) {
1199
- this._message_identifier = 1;
1200
- }
1201
- };
1202
-
1203
- /**
1204
- * Called when the underlying websocket has been opened.
1205
- * @ignore
1206
- */
1207
- ClientImpl.prototype._on_socket_open = function () {
1208
- // Create the CONNECT message object.
1209
- var wireMessage = new WireMessage(MESSAGE_TYPE.CONNECT, this.connectOptions);
1210
- wireMessage.clientId = this.clientId;
1211
- this._socket_send(wireMessage);
1212
- };
1213
-
1214
- /**
1215
- * Called when the underlying websocket has received a complete packet.
1216
- * @ignore
1217
- */
1218
- ClientImpl.prototype._on_socket_message = function (event) {
1219
- this._trace("Client._on_socket_message", event.data);
1220
- var messages = this._deframeMessages(event.data);
1221
- for (var i = 0; i < messages.length; i+=1) {
1222
- this._handleMessage(messages[i]);
1223
- }
1224
- };
1225
-
1226
- ClientImpl.prototype._deframeMessages = function(data) {
1227
- var byteArray = new Uint8Array(data);
1228
- var messages = [];
1229
- if (this.receiveBuffer) {
1230
- var newData = new Uint8Array(this.receiveBuffer.length+byteArray.length);
1231
- newData.set(this.receiveBuffer);
1232
- newData.set(byteArray,this.receiveBuffer.length);
1233
- byteArray = newData;
1234
- delete this.receiveBuffer;
1235
- }
1236
- try {
1237
- var offset = 0;
1238
- while(offset < byteArray.length) {
1239
- var result = decodeMessage(byteArray,offset);
1240
- var wireMessage = result[0];
1241
- offset = result[1];
1242
- if (wireMessage !== null) {
1243
- messages.push(wireMessage);
1244
- } else {
1245
- break;
1246
- }
1247
- }
1248
- if (offset < byteArray.length) {
1249
- this.receiveBuffer = byteArray.subarray(offset);
1250
- }
1251
- } catch (error) {
1252
- var errorStack = ((error.hasOwnProperty("stack") == "undefined") ? error.stack.toString() : "No Error Stack Available");
1253
- this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,errorStack]));
1254
- return;
1255
- }
1256
- return messages;
1257
- };
1258
-
1259
- ClientImpl.prototype._handleMessage = function(wireMessage) {
1260
-
1261
- this._trace("Client._handleMessage", wireMessage);
1262
-
1263
- try {
1264
- switch(wireMessage.type) {
1265
- case MESSAGE_TYPE.CONNACK:
1266
- this._connectTimeout.cancel();
1267
- if (this._reconnectTimeout)
1268
- this._reconnectTimeout.cancel();
1269
-
1270
- // If we have started using clean session then clear up the local state.
1271
- if (this.connectOptions.cleanSession) {
1272
- for (var key in this._sentMessages) {
1273
- var sentMessage = this._sentMessages[key];
1274
- localStorage.removeItem("Sent:"+this._localKey+sentMessage.messageIdentifier);
1275
- }
1276
- this._sentMessages = {};
1277
-
1278
- for (var key in this._receivedMessages) {
1279
- var receivedMessage = this._receivedMessages[key];
1280
- localStorage.removeItem("Received:"+this._localKey+receivedMessage.messageIdentifier);
1281
- }
1282
- this._receivedMessages = {};
1283
- }
1284
- // Client connected and ready for business.
1285
- if (wireMessage.returnCode === 0) {
1286
-
1287
- this.connected = true;
1288
- // Jump to the end of the list of uris and stop looking for a good host.
1289
-
1290
- if (this.connectOptions.uris)
1291
- this.hostIndex = this.connectOptions.uris.length;
1292
-
1293
- } else {
1294
- this._disconnected(ERROR.CONNACK_RETURNCODE.code , format(ERROR.CONNACK_RETURNCODE, [wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode]]));
1295
- break;
1296
- }
1297
-
1298
- // Resend messages.
1299
- var sequencedMessages = [];
1300
- for (var msgId in this._sentMessages) {
1301
- if (this._sentMessages.hasOwnProperty(msgId))
1302
- sequencedMessages.push(this._sentMessages[msgId]);
1303
- }
1304
-
1305
- // Also schedule qos 0 buffered messages if any
1306
- if (this._buffered_msg_queue.length > 0) {
1307
- var msg = null;
1308
- while ((msg = this._buffered_msg_queue.pop())) {
1309
- sequencedMessages.push(msg);
1310
- if (this.onMessageDelivered)
1311
- this._notify_msg_sent[msg] = this.onMessageDelivered(msg.payloadMessage);
1312
- }
1313
- }
1314
-
1315
- // Sort sentMessages into the original sent order.
1316
- var sequencedMessages = sequencedMessages.sort(function(a,b) {return a.sequence - b.sequence;} );
1317
- for (var i=0, len=sequencedMessages.length; i<len; i++) {
1318
- var sentMessage = sequencedMessages[i];
1319
- if (sentMessage.type == MESSAGE_TYPE.PUBLISH && sentMessage.pubRecReceived) {
1320
- var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:sentMessage.messageIdentifier});
1321
- this._schedule_message(pubRelMessage);
1322
- } else {
1323
- this._schedule_message(sentMessage);
1324
- }
1325
- }
1326
-
1327
- // Execute the connectOptions.onSuccess callback if there is one.
1328
- // Will also now return if this connection was the result of an automatic
1329
- // reconnect and which URI was successfully connected to.
1330
- if (this.connectOptions.onSuccess) {
1331
- this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext});
1332
- }
1333
-
1334
- var reconnected = false;
1335
- if (this._reconnecting) {
1336
- reconnected = true;
1337
- this._reconnectInterval = 1;
1338
- this._reconnecting = false;
1339
- }
1340
-
1341
- // Execute the onConnected callback if there is one.
1342
- this._connected(reconnected, this._wsuri);
1343
-
1344
- // Process all queued messages now that the connection is established.
1345
- this._process_queue();
1346
- break;
1347
-
1348
- case MESSAGE_TYPE.PUBLISH:
1349
- this._receivePublish(wireMessage);
1350
- break;
1351
-
1352
- case MESSAGE_TYPE.PUBACK:
1353
- var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1354
- // If this is a re flow of a PUBACK after we have restarted receivedMessage will not exist.
1355
- if (sentMessage) {
1356
- delete this._sentMessages[wireMessage.messageIdentifier];
1357
- localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier);
1358
- if (this.onMessageDelivered)
1359
- this.onMessageDelivered(sentMessage.payloadMessage);
1360
- }
1361
- break;
1362
-
1363
- case MESSAGE_TYPE.PUBREC:
1364
- var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1365
- // If this is a re flow of a PUBREC after we have restarted receivedMessage will not exist.
1366
- if (sentMessage) {
1367
- sentMessage.pubRecReceived = true;
1368
- var pubRelMessage = new WireMessage(MESSAGE_TYPE.PUBREL, {messageIdentifier:wireMessage.messageIdentifier});
1369
- this.store("Sent:", sentMessage);
1370
- this._schedule_message(pubRelMessage);
1371
- }
1372
- break;
1373
-
1374
- case MESSAGE_TYPE.PUBREL:
1375
- var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier];
1376
- localStorage.removeItem("Received:"+this._localKey+wireMessage.messageIdentifier);
1377
- // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist.
1378
- if (receivedMessage) {
1379
- this._receiveMessage(receivedMessage);
1380
- delete this._receivedMessages[wireMessage.messageIdentifier];
1381
- }
1382
- // Always flow PubComp, we may have previously flowed PubComp but the server lost it and restarted.
1383
- var pubCompMessage = new WireMessage(MESSAGE_TYPE.PUBCOMP, {messageIdentifier:wireMessage.messageIdentifier});
1384
- this._schedule_message(pubCompMessage);
1385
-
1386
-
1387
- break;
1388
-
1389
- case MESSAGE_TYPE.PUBCOMP:
1390
- var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1391
- delete this._sentMessages[wireMessage.messageIdentifier];
1392
- localStorage.removeItem("Sent:"+this._localKey+wireMessage.messageIdentifier);
1393
- if (this.onMessageDelivered)
1394
- this.onMessageDelivered(sentMessage.payloadMessage);
1395
- break;
1396
-
1397
- case MESSAGE_TYPE.SUBACK:
1398
- var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1399
- if (sentMessage) {
1400
- if(sentMessage.timeOut)
1401
- sentMessage.timeOut.cancel();
1402
- // This will need to be fixed when we add multiple topic support
1403
- if (wireMessage.returnCode[0] === 0x80) {
1404
- if (sentMessage.onFailure) {
1405
- sentMessage.onFailure(wireMessage.returnCode);
1406
- }
1407
- } else if (sentMessage.onSuccess) {
1408
- sentMessage.onSuccess(wireMessage.returnCode);
1409
- }
1410
- delete this._sentMessages[wireMessage.messageIdentifier];
1411
- }
1412
- break;
1413
-
1414
- case MESSAGE_TYPE.UNSUBACK:
1415
- var sentMessage = this._sentMessages[wireMessage.messageIdentifier];
1416
- if (sentMessage) {
1417
- if (sentMessage.timeOut)
1418
- sentMessage.timeOut.cancel();
1419
- if (sentMessage.callback) {
1420
- sentMessage.callback();
1421
- }
1422
- delete this._sentMessages[wireMessage.messageIdentifier];
1423
- }
1424
-
1425
- break;
1426
-
1427
- case MESSAGE_TYPE.PINGRESP:
1428
- /* The sendPinger or receivePinger may have sent a ping, the receivePinger has already been reset. */
1429
- this.sendPinger.reset();
1430
- break;
1431
-
1432
- case MESSAGE_TYPE.DISCONNECT:
1433
- // Clients do not expect to receive disconnect packets.
1434
- this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]));
1435
- break;
1436
-
1437
- default:
1438
- this._disconnected(ERROR.INVALID_MQTT_MESSAGE_TYPE.code , format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]));
1439
- }
1440
- } catch (error) {
1441
- var errorStack = ((error.hasOwnProperty("stack") == "undefined") ? error.stack.toString() : "No Error Stack Available");
1442
- this._disconnected(ERROR.INTERNAL_ERROR.code , format(ERROR.INTERNAL_ERROR, [error.message,errorStack]));
1443
- return;
1444
- }
1445
- };
1446
-
1447
- /** @ignore */
1448
- ClientImpl.prototype._on_socket_error = function (error) {
1449
- if (!this._reconnecting) {
1450
- this._disconnected(ERROR.SOCKET_ERROR.code , format(ERROR.SOCKET_ERROR, [error.data]));
1451
- }
1452
- };
1453
-
1454
- /** @ignore */
1455
- ClientImpl.prototype._on_socket_close = function () {
1456
- if (!this._reconnecting) {
1457
- this._disconnected(ERROR.SOCKET_CLOSE.code , format(ERROR.SOCKET_CLOSE));
1458
- }
1459
- };
1460
-
1461
- /** @ignore */
1462
- ClientImpl.prototype._socket_send = function (wireMessage) {
1463
-
1464
- if (wireMessage.type == 1) {
1465
- var wireMessageMasked = this._traceMask(wireMessage, "password");
1466
- this._trace("Client._socket_send", wireMessageMasked);
1467
- }
1468
- else this._trace("Client._socket_send", wireMessage);
1469
-
1470
- this.socket.send(wireMessage.encode());
1471
- /* We have proved to the server we are alive. */
1472
- this.sendPinger.reset();
1473
- };
1474
-
1475
- /** @ignore */
1476
- ClientImpl.prototype._receivePublish = function (wireMessage) {
1477
- switch(wireMessage.payloadMessage.qos) {
1478
- case "undefined":
1479
- case 0:
1480
- this._receiveMessage(wireMessage);
1481
- break;
1482
-
1483
- case 1:
1484
- var pubAckMessage = new WireMessage(MESSAGE_TYPE.PUBACK, {messageIdentifier:wireMessage.messageIdentifier});
1485
- this._schedule_message(pubAckMessage);
1486
- this._receiveMessage(wireMessage);
1487
- break;
1488
-
1489
- case 2:
1490
- this._receivedMessages[wireMessage.messageIdentifier] = wireMessage;
1491
- this.store("Received:", wireMessage);
1492
- var pubRecMessage = new WireMessage(MESSAGE_TYPE.PUBREC, {messageIdentifier:wireMessage.messageIdentifier});
1493
- this._schedule_message(pubRecMessage);
1494
-
1495
- break;
1496
-
1497
- default:
1498
- throw Error("Invaild qos=" + wireMessage.payloadMessage.qos);
1499
- }
1500
- };
1501
-
1502
- /** @ignore */
1503
- ClientImpl.prototype._receiveMessage = function (wireMessage) {
1504
- if (this.onMessageArrived) {
1505
- this.onMessageArrived(wireMessage.payloadMessage);
1506
- }
1507
- };
1508
-
1509
- /**
1510
- * Client has connected.
1511
- * @param {reconnect} [boolean] indicate if this was a result of reconnect operation.
1512
- * @param {uri} [string] fully qualified WebSocket URI of the server.
1513
- */
1514
- ClientImpl.prototype._connected = function (reconnect, uri) {
1515
- // Execute the onConnected callback if there is one.
1516
- if (this.onConnected)
1517
- this.onConnected(reconnect, uri);
1518
- };
1519
-
1520
- /**
1521
- * Attempts to reconnect the client to the server.
1522
- * For each reconnect attempt, will double the reconnect interval
1523
- * up to 128 seconds.
1524
- */
1525
- ClientImpl.prototype._reconnect = function () {
1526
- this._trace("Client._reconnect");
1527
- if (!this.connected) {
1528
- this._reconnecting = true;
1529
- this.sendPinger.cancel();
1530
- this.receivePinger.cancel();
1531
- if (this._reconnectInterval < 128)
1532
- this._reconnectInterval = this._reconnectInterval * 2;
1533
- if (this.connectOptions.uris) {
1534
- this.hostIndex = 0;
1535
- this._doConnect(this.connectOptions.uris[0]);
1536
- } else {
1537
- this._doConnect(this.uri);
1538
- }
1539
- }
1540
- };
1541
-
1542
- /**
1543
- * Client has disconnected either at its own request or because the server
1544
- * or network disconnected it. Remove all non-durable state.
1545
- * @param {errorCode} [number] the error number.
1546
- * @param {errorText} [string] the error text.
1547
- * @ignore
1548
- */
1549
- ClientImpl.prototype._disconnected = function (errorCode, errorText) {
1550
- this._trace("Client._disconnected", errorCode, errorText);
1551
-
1552
- if (errorCode !== undefined && this._reconnecting) {
1553
- //Continue automatic reconnect process
1554
- this._reconnectTimeout = new Timeout(this, this._reconnectInterval, this._reconnect);
1555
- return;
1556
- }
1557
-
1558
- this.sendPinger.cancel();
1559
- this.receivePinger.cancel();
1560
- if (this._connectTimeout) {
1561
- this._connectTimeout.cancel();
1562
- this._connectTimeout = null;
1563
- }
1564
-
1565
- // Clear message buffers.
1566
- this._msg_queue = [];
1567
- this._buffered_msg_queue = [];
1568
- this._notify_msg_sent = {};
1569
-
1570
- if (this.socket) {
1571
- // Cancel all socket callbacks so that they cannot be driven again by this socket.
1572
- this.socket.onopen = null;
1573
- this.socket.onmessage = null;
1574
- this.socket.onerror = null;
1575
- this.socket.onclose = null;
1576
- if (this.socket.readyState === 1)
1577
- this.socket.close();
1578
- delete this.socket;
1579
- }
1580
-
1581
- if (this.connectOptions.uris && this.hostIndex < this.connectOptions.uris.length-1) {
1582
- // Try the next host.
1583
- this.hostIndex++;
1584
- this._doConnect(this.connectOptions.uris[this.hostIndex]);
1585
- } else {
1586
-
1587
- if (errorCode === undefined) {
1588
- errorCode = ERROR.OK.code;
1589
- errorText = format(ERROR.OK);
1590
- }
1591
-
1592
- // Run any application callbacks last as they may attempt to reconnect and hence create a new socket.
1593
- if (this.connected) {
1594
- this.connected = false;
1595
- // Execute the connectionLostCallback if there is one, and we were connected.
1596
- if (this.onConnectionLost) {
1597
- this.onConnectionLost({errorCode:errorCode, errorMessage:errorText, reconnect:this.connectOptions.reconnect, uri:this._wsuri});
1598
- }
1599
- if (errorCode !== ERROR.OK.code && this.connectOptions.reconnect) {
1600
- // Start automatic reconnect process for the very first time since last successful connect.
1601
- this._reconnectInterval = 1;
1602
- this._reconnect();
1603
- return;
1604
- }
1605
- } else {
1606
- // Otherwise we never had a connection, so indicate that the connect has failed.
1607
- if (this.connectOptions.mqttVersion === 4 && this.connectOptions.mqttVersionExplicit === false) {
1608
- this._trace("Failed to connect V4, dropping back to V3");
1609
- this.connectOptions.mqttVersion = 3;
1610
- if (this.connectOptions.uris) {
1611
- this.hostIndex = 0;
1612
- this._doConnect(this.connectOptions.uris[0]);
1613
- } else {
1614
- this._doConnect(this.uri);
1615
- }
1616
- } else if(this.connectOptions.onFailure) {
1617
- this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext, errorCode:errorCode, errorMessage:errorText});
1618
- }
1619
- }
1620
- }
1621
- };
1622
-
1623
- /** @ignore */
1624
- ClientImpl.prototype._trace = function () {
1625
- // Pass trace message back to client's callback function
1626
- if (this.traceFunction) {
1627
- var args = Array.prototype.slice.call(arguments);
1628
- for (var i in args)
1629
- {
1630
- if (typeof args[i] !== "undefined")
1631
- args.splice(i, 1, JSON.stringify(args[i]));
1632
- }
1633
- var record = args.join("");
1634
- this.traceFunction ({severity: "Debug", message: record });
1635
- }
1636
-
1637
- //buffer style trace
1638
- if ( this._traceBuffer !== null ) {
1639
- for (var i = 0, max = arguments.length; i < max; i++) {
1640
- if ( this._traceBuffer.length == this._MAX_TRACE_ENTRIES ) {
1641
- this._traceBuffer.shift();
1642
- }
1643
- if (i === 0) this._traceBuffer.push(arguments[i]);
1644
- else if (typeof arguments[i] === "undefined" ) this._traceBuffer.push(arguments[i]);
1645
- else this._traceBuffer.push(" "+JSON.stringify(arguments[i]));
1646
- }
1647
- }
1648
- };
1649
-
1650
- /** @ignore */
1651
- ClientImpl.prototype._traceMask = function (traceObject, masked) {
1652
- var traceObjectMasked = {};
1653
- for (var attr in traceObject) {
1654
- if (traceObject.hasOwnProperty(attr)) {
1655
- if (attr == masked)
1656
- traceObjectMasked[attr] = "******";
1657
- else
1658
- traceObjectMasked[attr] = traceObject[attr];
1659
- }
1660
- }
1661
- return traceObjectMasked;
1662
- };
1663
-
1664
- // ------------------------------------------------------------------------
1665
- // Public Programming interface.
1666
- // ------------------------------------------------------------------------
1667
-
1668
- /**
1669
- * The JavaScript application communicates to the server using a {@link Paho.Client} object.
1670
- * <p>
1671
- * Most applications will create just one Client object and then call its connect() method,
1672
- * however applications can create more than one Client object if they wish.
1673
- * In this case the combination of host, port and clientId attributes must be different for each Client object.
1674
- * <p>
1675
- * The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods
1676
- * (even though the underlying protocol exchange might be synchronous in nature).
1677
- * This means they signal their completion by calling back to the application,
1678
- * via Success or Failure callback functions provided by the application on the method in question.
1679
- * Such callbacks are called at most once per method invocation and do not persist beyond the lifetime
1680
- * of the script that made the invocation.
1681
- * <p>
1682
- * In contrast there are some callback functions, most notably <i>onMessageArrived</i>,
1683
- * that are defined on the {@link Paho.Client} object.
1684
- * These may get called multiple times, and aren't directly related to specific method invocations made by the client.
1685
- *
1686
- * @name Paho.Client
1687
- *
1688
- * @constructor
1689
- *
1690
- * @param {string} host - the address of the messaging server, as a fully qualified WebSocket URI, as a DNS name or dotted decimal IP address.
1691
- * @param {number} port - the port number to connect to - only required if host is not a URI
1692
- * @param {string} path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'.
1693
- * @param {string} clientId - the Messaging client identifier, between 1 and 23 characters in length.
1694
- *
1695
- * @property {string} host - <i>read only</i> the server's DNS hostname or dotted decimal IP address.
1696
- * @property {number} port - <i>read only</i> the server's port.
1697
- * @property {string} path - <i>read only</i> the server's path.
1698
- * @property {string} clientId - <i>read only</i> used when connecting to the server.
1699
- * @property {function} onConnectionLost - called when a connection has been lost.
1700
- * after a connect() method has succeeded.
1701
- * Establish the call back used when a connection has been lost. The connection may be
1702
- * lost because the client initiates a disconnect or because the server or network
1703
- * cause the client to be disconnected. The disconnect call back may be called without
1704
- * the connectionComplete call back being invoked if, for example the client fails to
1705
- * connect.
1706
- * A single response object parameter is passed to the onConnectionLost callback containing the following fields:
1707
- * <ol>
1708
- * <li>errorCode
1709
- * <li>errorMessage
1710
- * </ol>
1711
- * @property {function} onMessageDelivered - called when a message has been delivered.
1712
- * All processing that this Client will ever do has been completed. So, for example,
1713
- * in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server
1714
- * and the message has been removed from persistent storage before this callback is invoked.
1715
- * Parameters passed to the onMessageDelivered callback are:
1716
- * <ol>
1717
- * <li>{@link Paho.Message} that was delivered.
1718
- * </ol>
1719
- * @property {function} onMessageArrived - called when a message has arrived in this Paho.client.
1720
- * Parameters passed to the onMessageArrived callback are:
1721
- * <ol>
1722
- * <li>{@link Paho.Message} that has arrived.
1723
- * </ol>
1724
- * @property {function} onConnected - called when a connection is successfully made to the server.
1725
- * after a connect() method.
1726
- * Parameters passed to the onConnected callback are:
1727
- * <ol>
1728
- * <li>reconnect (boolean) - If true, the connection was the result of a reconnect.</li>
1729
- * <li>URI (string) - The URI used to connect to the server.</li>
1730
- * </ol>
1731
- * @property {boolean} disconnectedPublishing - if set, will enable disconnected publishing in
1732
- * in the event that the connection to the server is lost.
1733
- * @property {number} disconnectedBufferSize - Used to set the maximum number of messages that the disconnected
1734
- * buffer will hold before rejecting new messages. Default size: 5000 messages
1735
- * @property {function} trace - called whenever trace is called. TODO
1736
- */
1737
- var Client = function (host, port, path, clientId) {
1738
-
1739
- var uri;
1740
-
1741
- if (typeof host !== "string")
1742
- throw new Error(format(ERROR.INVALID_TYPE, [typeof host, "host"]));
1743
-
1744
- if (arguments.length == 2) {
1745
- // host: must be full ws:// uri
1746
- // port: clientId
1747
- clientId = port;
1748
- uri = host;
1749
- var match = uri.match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/);
1750
- if (match) {
1751
- host = match[4]||match[2];
1752
- port = parseInt(match[7]);
1753
- path = match[8];
1754
- } else {
1755
- throw new Error(format(ERROR.INVALID_ARGUMENT,[host,"host"]));
1756
- }
1757
- } else {
1758
- if (arguments.length == 3) {
1759
- clientId = path;
1760
- path = "/mqtt";
1761
- }
1762
- if (typeof port !== "number" || port < 0)
1763
- throw new Error(format(ERROR.INVALID_TYPE, [typeof port, "port"]));
1764
- if (typeof path !== "string")
1765
- throw new Error(format(ERROR.INVALID_TYPE, [typeof path, "path"]));
1766
-
1767
- var ipv6AddSBracket = (host.indexOf(":") !== -1 && host.slice(0,1) !== "[" && host.slice(-1) !== "]");
1768
- uri = "ws://"+(ipv6AddSBracket?"["+host+"]":host)+":"+port+path;
1769
- }
1770
-
1771
- var clientIdLength = 0;
1772
- for (var i = 0; i<clientId.length; i++) {
1773
- var charCode = clientId.charCodeAt(i);
1774
- if (0xD800 <= charCode && charCode <= 0xDBFF) {
1775
- i++; // Surrogate pair.
1776
- }
1777
- clientIdLength++;
1778
- }
1779
- if (typeof clientId !== "string" || clientIdLength > 65535)
1780
- throw new Error(format(ERROR.INVALID_ARGUMENT, [clientId, "clientId"]));
1781
-
1782
- var client = new ClientImpl(uri, host, port, path, clientId);
1783
-
1784
- //Public Properties
1785
- Object.defineProperties(this,{
1786
- "host":{
1787
- get: function() { return host; },
1788
- set: function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }
1789
- },
1790
- "port":{
1791
- get: function() { return port; },
1792
- set: function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }
1793
- },
1794
- "path":{
1795
- get: function() { return path; },
1796
- set: function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }
1797
- },
1798
- "uri":{
1799
- get: function() { return uri; },
1800
- set: function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }
1801
- },
1802
- "clientId":{
1803
- get: function() { return client.clientId; },
1804
- set: function() { throw new Error(format(ERROR.UNSUPPORTED_OPERATION)); }
1805
- },
1806
- "onConnected":{
1807
- get: function() { return client.onConnected; },
1808
- set: function(newOnConnected) {
1809
- if (typeof newOnConnected === "function")
1810
- client.onConnected = newOnConnected;
1811
- else
1812
- throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnected, "onConnected"]));
1813
- }
1814
- },
1815
- "disconnectedPublishing":{
1816
- get: function() { return client.disconnectedPublishing; },
1817
- set: function(newDisconnectedPublishing) {
1818
- client.disconnectedPublishing = newDisconnectedPublishing;
1819
- }
1820
- },
1821
- "disconnectedBufferSize":{
1822
- get: function() { return client.disconnectedBufferSize; },
1823
- set: function(newDisconnectedBufferSize) {
1824
- client.disconnectedBufferSize = newDisconnectedBufferSize;
1825
- }
1826
- },
1827
- "onConnectionLost":{
1828
- get: function() { return client.onConnectionLost; },
1829
- set: function(newOnConnectionLost) {
1830
- if (typeof newOnConnectionLost === "function")
1831
- client.onConnectionLost = newOnConnectionLost;
1832
- else
1833
- throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnConnectionLost, "onConnectionLost"]));
1834
- }
1835
- },
1836
- "onMessageDelivered":{
1837
- get: function() { return client.onMessageDelivered; },
1838
- set: function(newOnMessageDelivered) {
1839
- if (typeof newOnMessageDelivered === "function")
1840
- client.onMessageDelivered = newOnMessageDelivered;
1841
- else
1842
- throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageDelivered, "onMessageDelivered"]));
1843
- }
1844
- },
1845
- "onMessageArrived":{
1846
- get: function() { return client.onMessageArrived; },
1847
- set: function(newOnMessageArrived) {
1848
- if (typeof newOnMessageArrived === "function")
1849
- client.onMessageArrived = newOnMessageArrived;
1850
- else
1851
- throw new Error(format(ERROR.INVALID_TYPE, [typeof newOnMessageArrived, "onMessageArrived"]));
1852
- }
1853
- },
1854
- "trace":{
1855
- get: function() { return client.traceFunction; },
1856
- set: function(trace) {
1857
- if(typeof trace === "function"){
1858
- client.traceFunction = trace;
1859
- }else{
1860
- throw new Error(format(ERROR.INVALID_TYPE, [typeof trace, "onTrace"]));
1861
- }
1862
- }
1863
- },
1864
- });
1865
-
1866
- /**
1867
- * Connect this Messaging client to its server.
1868
- *
1869
- * @name Paho.Client#connect
1870
- * @function
1871
- * @param {object} connectOptions - Attributes used with the connection.
1872
- * @param {number} connectOptions.timeout - If the connect has not succeeded within this
1873
- * number of seconds, it is deemed to have failed.
1874
- * The default is 30 seconds.
1875
- * @param {string} connectOptions.userName - Authentication username for this connection.
1876
- * @param {string} connectOptions.password - Authentication password for this connection.
1877
- * @param {Paho.Message} connectOptions.willMessage - sent by the server when the client
1878
- * disconnects abnormally.
1879
- * @param {number} connectOptions.keepAliveInterval - the server disconnects this client if
1880
- * there is no activity for this number of seconds.
1881
- * The default value of 60 seconds is assumed if not set.
1882
- * @param {boolean} connectOptions.cleanSession - if true(default) the client and server
1883
- * persistent state is deleted on successful connect.
1884
- * @param {boolean} connectOptions.useSSL - if present and true, use an SSL Websocket connection.
1885
- * @param {object} connectOptions.invocationContext - passed to the onSuccess callback or onFailure callback.
1886
- * @param {function} connectOptions.onSuccess - called when the connect acknowledgement
1887
- * has been received from the server.
1888
- * A single response object parameter is passed to the onSuccess callback containing the following fields:
1889
- * <ol>
1890
- * <li>invocationContext as passed in to the onSuccess method in the connectOptions.
1891
- * </ol>
1892
- * @param {function} connectOptions.onFailure - called when the connect request has failed or timed out.
1893
- * A single response object parameter is passed to the onFailure callback containing the following fields:
1894
- * <ol>
1895
- * <li>invocationContext as passed in to the onFailure method in the connectOptions.
1896
- * <li>errorCode a number indicating the nature of the error.
1897
- * <li>errorMessage text describing the error.
1898
- * </ol>
1899
- * @param {array} connectOptions.hosts - If present this contains either a set of hostnames or fully qualified
1900
- * WebSocket URIs (ws://iot.eclipse.org:80/ws), that are tried in order in place
1901
- * of the host and port paramater on the construtor. The hosts are tried one at at time in order until
1902
- * one of then succeeds.
1903
- * @param {array} connectOptions.ports - If present the set of ports matching the hosts. If hosts contains URIs, this property
1904
- * is not used.
1905
- * @param {boolean} connectOptions.reconnect - Sets whether the client will automatically attempt to reconnect
1906
- * to the server if the connection is lost.
1907
- *<ul>
1908
- *<li>If set to false, the client will not attempt to automatically reconnect to the server in the event that the
1909
- * connection is lost.</li>
1910
- *<li>If set to true, in the event that the connection is lost, the client will attempt to reconnect to the server.
1911
- * It will initially wait 1 second before it attempts to reconnect, for every failed reconnect attempt, the delay
1912
- * will double until it is at 2 minutes at which point the delay will stay at 2 minutes.</li>
1913
- *</ul>
1914
- * @param {number} connectOptions.mqttVersion - The version of MQTT to use to connect to the MQTT Broker.
1915
- *<ul>
1916
- *<li>3 - MQTT V3.1</li>
1917
- *<li>4 - MQTT V3.1.1</li>
1918
- *</ul>
1919
- * @param {boolean} connectOptions.mqttVersionExplicit - If set to true, will force the connection to use the
1920
- * selected MQTT Version or will fail to connect.
1921
- * @param {array} connectOptions.uris - If present, should contain a list of fully qualified WebSocket uris
1922
- * (e.g. ws://iot.eclipse.org:80/ws), that are tried in order in place of the host and port parameter of the construtor.
1923
- * The uris are tried one at a time in order until one of them succeeds. Do not use this in conjunction with hosts as
1924
- * the hosts array will be converted to uris and will overwrite this property.
1925
- * @throws {InvalidState} If the client is not in disconnected state. The client must have received connectionLost
1926
- * or disconnected before calling connect for a second or subsequent time.
1927
- */
1928
- this.connect = function (connectOptions) {
1929
- connectOptions = connectOptions || {} ;
1930
- validate(connectOptions, {timeout:"number",
1931
- userName:"string",
1932
- password:"string",
1933
- willMessage:"object",
1934
- keepAliveInterval:"number",
1935
- cleanSession:"boolean",
1936
- useSSL:"boolean",
1937
- invocationContext:"object",
1938
- onSuccess:"function",
1939
- onFailure:"function",
1940
- hosts:"object",
1941
- ports:"object",
1942
- reconnect:"boolean",
1943
- mqttVersion:"number",
1944
- mqttVersionExplicit:"boolean",
1945
- uris: "object"});
1946
-
1947
- // If no keep alive interval is set, assume 60 seconds.
1948
- if (connectOptions.keepAliveInterval === undefined)
1949
- connectOptions.keepAliveInterval = 60;
1950
-
1951
- if (connectOptions.mqttVersion > 4 || connectOptions.mqttVersion < 3) {
1952
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.mqttVersion, "connectOptions.mqttVersion"]));
1953
- }
1954
-
1955
- if (connectOptions.mqttVersion === undefined) {
1956
- connectOptions.mqttVersionExplicit = false;
1957
- connectOptions.mqttVersion = 4;
1958
- } else {
1959
- connectOptions.mqttVersionExplicit = true;
1960
- }
1961
-
1962
- //Check that if password is set, so is username
1963
- if (connectOptions.password !== undefined && connectOptions.userName === undefined)
1964
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.password, "connectOptions.password"]));
1965
-
1966
- if (connectOptions.willMessage) {
1967
- if (!(connectOptions.willMessage instanceof Message))
1968
- throw new Error(format(ERROR.INVALID_TYPE, [connectOptions.willMessage, "connectOptions.willMessage"]));
1969
- // The will message must have a payload that can be represented as a string.
1970
- // Cause the willMessage to throw an exception if this is not the case.
1971
- connectOptions.willMessage.stringPayload = null;
1972
-
1973
- if (typeof connectOptions.willMessage.destinationName === "undefined")
1974
- throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.willMessage.destinationName, "connectOptions.willMessage.destinationName"]));
1975
- }
1976
- if (typeof connectOptions.cleanSession === "undefined")
1977
- connectOptions.cleanSession = true;
1978
- if (connectOptions.hosts) {
1979
-
1980
- if (!(connectOptions.hosts instanceof Array) )
1981
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"]));
1982
- if (connectOptions.hosts.length <1 )
1983
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts, "connectOptions.hosts"]));
1984
-
1985
- var usingURIs = false;
1986
- for (var i = 0; i<connectOptions.hosts.length; i++) {
1987
- if (typeof connectOptions.hosts[i] !== "string")
1988
- throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1989
- if (/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(connectOptions.hosts[i])) {
1990
- if (i === 0) {
1991
- usingURIs = true;
1992
- } else if (!usingURIs) {
1993
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1994
- }
1995
- } else if (usingURIs) {
1996
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.hosts[i], "connectOptions.hosts["+i+"]"]));
1997
- }
1998
- }
1999
-
2000
- if (!usingURIs) {
2001
- if (!connectOptions.ports)
2002
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
2003
- if (!(connectOptions.ports instanceof Array) )
2004
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
2005
- if (connectOptions.hosts.length !== connectOptions.ports.length)
2006
- throw new Error(format(ERROR.INVALID_ARGUMENT, [connectOptions.ports, "connectOptions.ports"]));
2007
-
2008
- connectOptions.uris = [];
2009
-
2010
- for (var i = 0; i<connectOptions.hosts.length; i++) {
2011
- if (typeof connectOptions.ports[i] !== "number" || connectOptions.ports[i] < 0)
2012
- throw new Error(format(ERROR.INVALID_TYPE, [typeof connectOptions.ports[i], "connectOptions.ports["+i+"]"]));
2013
- var host = connectOptions.hosts[i];
2014
- var port = connectOptions.ports[i];
2015
-
2016
- var ipv6 = (host.indexOf(":") !== -1);
2017
- uri = "ws://"+(ipv6?"["+host+"]":host)+":"+port+path;
2018
- connectOptions.uris.push(uri);
2019
- }
2020
- } else {
2021
- connectOptions.uris = connectOptions.hosts;
2022
- }
2023
- }
2024
-
2025
- client.connect(connectOptions);
2026
- };
2027
-
2028
- /**
2029
- * Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the filter.
2030
- *
2031
- * @name Paho.Client#subscribe
2032
- * @function
2033
- * @param {string} filter describing the destinations to receive messages from.
2034
- * <br>
2035
- * @param {object} subscribeOptions - used to control the subscription
2036
- *
2037
- * @param {number} subscribeOptions.qos - the maximum qos of any publications sent
2038
- * as a result of making this subscription.
2039
- * @param {object} subscribeOptions.invocationContext - passed to the onSuccess callback
2040
- * or onFailure callback.
2041
- * @param {function} subscribeOptions.onSuccess - called when the subscribe acknowledgement
2042
- * has been received from the server.
2043
- * A single response object parameter is passed to the onSuccess callback containing the following fields:
2044
- * <ol>
2045
- * <li>invocationContext if set in the subscribeOptions.
2046
- * </ol>
2047
- * @param {function} subscribeOptions.onFailure - called when the subscribe request has failed or timed out.
2048
- * A single response object parameter is passed to the onFailure callback containing the following fields:
2049
- * <ol>
2050
- * <li>invocationContext - if set in the subscribeOptions.
2051
- * <li>errorCode - a number indicating the nature of the error.
2052
- * <li>errorMessage - text describing the error.
2053
- * </ol>
2054
- * @param {number} subscribeOptions.timeout - which, if present, determines the number of
2055
- * seconds after which the onFailure calback is called.
2056
- * The presence of a timeout does not prevent the onSuccess
2057
- * callback from being called when the subscribe completes.
2058
- * @throws {InvalidState} if the client is not in connected state.
2059
- */
2060
- this.subscribe = function (filter, subscribeOptions) {
2061
- if (typeof filter !== "string" && filter.constructor !== Array)
2062
- throw new Error("Invalid argument:"+filter);
2063
- subscribeOptions = subscribeOptions || {} ;
2064
- validate(subscribeOptions, {qos:"number",
2065
- invocationContext:"object",
2066
- onSuccess:"function",
2067
- onFailure:"function",
2068
- timeout:"number"
2069
- });
2070
- if (subscribeOptions.timeout && !subscribeOptions.onFailure)
2071
- throw new Error("subscribeOptions.timeout specified with no onFailure callback.");
2072
- if (typeof subscribeOptions.qos !== "undefined" && !(subscribeOptions.qos === 0 || subscribeOptions.qos === 1 || subscribeOptions.qos === 2 ))
2073
- throw new Error(format(ERROR.INVALID_ARGUMENT, [subscribeOptions.qos, "subscribeOptions.qos"]));
2074
- client.subscribe(filter, subscribeOptions);
2075
- };
2076
-
2077
- /**
2078
- * Unsubscribe for messages, stop receiving messages sent to destinations described by the filter.
2079
- *
2080
- * @name Paho.Client#unsubscribe
2081
- * @function
2082
- * @param {string} filter - describing the destinations to receive messages from.
2083
- * @param {object} unsubscribeOptions - used to control the subscription
2084
- * @param {object} unsubscribeOptions.invocationContext - passed to the onSuccess callback
2085
- or onFailure callback.
2086
- * @param {function} unsubscribeOptions.onSuccess - called when the unsubscribe acknowledgement has been received from the server.
2087
- * A single response object parameter is passed to the
2088
- * onSuccess callback containing the following fields:
2089
- * <ol>
2090
- * <li>invocationContext - if set in the unsubscribeOptions.
2091
- * </ol>
2092
- * @param {function} unsubscribeOptions.onFailure called when the unsubscribe request has failed or timed out.
2093
- * A single response object parameter is passed to the onFailure callback containing the following fields:
2094
- * <ol>
2095
- * <li>invocationContext - if set in the unsubscribeOptions.
2096
- * <li>errorCode - a number indicating the nature of the error.
2097
- * <li>errorMessage - text describing the error.
2098
- * </ol>
2099
- * @param {number} unsubscribeOptions.timeout - which, if present, determines the number of seconds
2100
- * after which the onFailure callback is called. The presence of
2101
- * a timeout does not prevent the onSuccess callback from being
2102
- * called when the unsubscribe completes
2103
- * @throws {InvalidState} if the client is not in connected state.
2104
- */
2105
- this.unsubscribe = function (filter, unsubscribeOptions) {
2106
- if (typeof filter !== "string" && filter.constructor !== Array)
2107
- throw new Error("Invalid argument:"+filter);
2108
- unsubscribeOptions = unsubscribeOptions || {} ;
2109
- validate(unsubscribeOptions, {invocationContext:"object",
2110
- onSuccess:"function",
2111
- onFailure:"function",
2112
- timeout:"number"
2113
- });
2114
- if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure)
2115
- throw new Error("unsubscribeOptions.timeout specified with no onFailure callback.");
2116
- client.unsubscribe(filter, unsubscribeOptions);
2117
- };
2118
-
2119
- /**
2120
- * Send a message to the consumers of the destination in the Message.
2121
- *
2122
- * @name Paho.Client#send
2123
- * @function
2124
- * @param {string|Paho.Message} topic - <b>mandatory</b> The name of the destination to which the message is to be sent.
2125
- * - If it is the only parameter, used as Paho.Message object.
2126
- * @param {String|ArrayBuffer} payload - The message data to be sent.
2127
- * @param {number} qos The Quality of Service used to deliver the message.
2128
- * <dl>
2129
- * <dt>0 Best effort (default).
2130
- * <dt>1 At least once.
2131
- * <dt>2 Exactly once.
2132
- * </dl>
2133
- * @param {Boolean} retained If true, the message is to be retained by the server and delivered
2134
- * to both current and future subscriptions.
2135
- * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2136
- * A received message has the retained boolean set to true if the message was published
2137
- * with the retained boolean set to true
2138
- * and the subscrption was made after the message has been published.
2139
- * @throws {InvalidState} if the client is not connected.
2140
- */
2141
- this.send = function (topic,payload,qos,retained) {
2142
- var message ;
2143
-
2144
- if(arguments.length === 0){
2145
- throw new Error("Invalid argument."+"length");
2146
-
2147
- }else if(arguments.length == 1) {
2148
-
2149
- if (!(topic instanceof Message) && (typeof topic !== "string"))
2150
- throw new Error("Invalid argument:"+ typeof topic);
2151
-
2152
- message = topic;
2153
- if (typeof message.destinationName === "undefined")
2154
- throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"]));
2155
- client.send(message);
2156
-
2157
- }else {
2158
- //parameter checking in Message object
2159
- message = new Message(payload);
2160
- message.destinationName = topic;
2161
- if(arguments.length >= 3)
2162
- message.qos = qos;
2163
- if(arguments.length >= 4)
2164
- message.retained = retained;
2165
- client.send(message);
2166
- }
2167
- };
2168
-
2169
- /**
2170
- * Publish a message to the consumers of the destination in the Message.
2171
- * Synonym for Paho.Mqtt.Client#send
2172
- *
2173
- * @name Paho.Client#publish
2174
- * @function
2175
- * @param {string|Paho.Message} topic - <b>mandatory</b> The name of the topic to which the message is to be published.
2176
- * - If it is the only parameter, used as Paho.Message object.
2177
- * @param {String|ArrayBuffer} payload - The message data to be published.
2178
- * @param {number} qos The Quality of Service used to deliver the message.
2179
- * <dl>
2180
- * <dt>0 Best effort (default).
2181
- * <dt>1 At least once.
2182
- * <dt>2 Exactly once.
2183
- * </dl>
2184
- * @param {Boolean} retained If true, the message is to be retained by the server and delivered
2185
- * to both current and future subscriptions.
2186
- * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2187
- * A received message has the retained boolean set to true if the message was published
2188
- * with the retained boolean set to true
2189
- * and the subscrption was made after the message has been published.
2190
- * @throws {InvalidState} if the client is not connected.
2191
- */
2192
- this.publish = function(topic,payload,qos,retained) {
2193
- var message ;
2194
-
2195
- if(arguments.length === 0){
2196
- throw new Error("Invalid argument."+"length");
2197
-
2198
- }else if(arguments.length == 1) {
2199
-
2200
- if (!(topic instanceof Message) && (typeof topic !== "string"))
2201
- throw new Error("Invalid argument:"+ typeof topic);
2202
-
2203
- message = topic;
2204
- if (typeof message.destinationName === "undefined")
2205
- throw new Error(format(ERROR.INVALID_ARGUMENT,[message.destinationName,"Message.destinationName"]));
2206
- client.send(message);
2207
-
2208
- }else {
2209
- //parameter checking in Message object
2210
- message = new Message(payload);
2211
- message.destinationName = topic;
2212
- if(arguments.length >= 3)
2213
- message.qos = qos;
2214
- if(arguments.length >= 4)
2215
- message.retained = retained;
2216
- client.send(message);
2217
- }
2218
- };
2219
-
2220
- /**
2221
- * Normal disconnect of this Messaging client from its server.
2222
- *
2223
- * @name Paho.Client#disconnect
2224
- * @function
2225
- * @throws {InvalidState} if the client is already disconnected.
2226
- */
2227
- this.disconnect = function () {
2228
- client.disconnect();
2229
- };
2230
-
2231
- /**
2232
- * Get the contents of the trace log.
2233
- *
2234
- * @name Paho.Client#getTraceLog
2235
- * @function
2236
- * @return {Object[]} tracebuffer containing the time ordered trace records.
2237
- */
2238
- this.getTraceLog = function () {
2239
- return client.getTraceLog();
2240
- };
2241
-
2242
- /**
2243
- * Start tracing.
2244
- *
2245
- * @name Paho.Client#startTrace
2246
- * @function
2247
- */
2248
- this.startTrace = function () {
2249
- client.startTrace();
2250
- };
2251
-
2252
- /**
2253
- * Stop tracing.
2254
- *
2255
- * @name Paho.Client#stopTrace
2256
- * @function
2257
- */
2258
- this.stopTrace = function () {
2259
- client.stopTrace();
2260
- };
2261
-
2262
- this.isConnected = function() {
2263
- return client.connected;
2264
- };
2265
- };
2266
-
2267
- /**
2268
- * An application message, sent or received.
2269
- * <p>
2270
- * All attributes may be null, which implies the default values.
2271
- *
2272
- * @name Paho.Message
2273
- * @constructor
2274
- * @param {String|ArrayBuffer} payload The message data to be sent.
2275
- * <p>
2276
- * @property {string} payloadString <i>read only</i> The payload as a string if the payload consists of valid UTF-8 characters.
2277
- * @property {ArrayBuffer} payloadBytes <i>read only</i> The payload as an ArrayBuffer.
2278
- * <p>
2279
- * @property {string} destinationName <b>mandatory</b> The name of the destination to which the message is to be sent
2280
- * (for messages about to be sent) or the name of the destination from which the message has been received.
2281
- * (for messages received by the onMessage function).
2282
- * <p>
2283
- * @property {number} qos The Quality of Service used to deliver the message.
2284
- * <dl>
2285
- * <dt>0 Best effort (default).
2286
- * <dt>1 At least once.
2287
- * <dt>2 Exactly once.
2288
- * </dl>
2289
- * <p>
2290
- * @property {Boolean} retained If true, the message is to be retained by the server and delivered
2291
- * to both current and future subscriptions.
2292
- * If false the server only delivers the message to current subscribers, this is the default for new Messages.
2293
- * A received message has the retained boolean set to true if the message was published
2294
- * with the retained boolean set to true
2295
- * and the subscrption was made after the message has been published.
2296
- * <p>
2297
- * @property {Boolean} duplicate <i>read only</i> If true, this message might be a duplicate of one which has already been received.
2298
- * This is only set on messages received from the server.
2299
- *
2300
- */
2301
- var Message = function (newPayload) {
2302
- var payload;
2303
- if ( typeof newPayload === "string" ||
2304
- newPayload instanceof ArrayBuffer ||
2305
- (ArrayBuffer.isView(newPayload) && !(newPayload instanceof DataView))
2306
- ) {
2307
- payload = newPayload;
2308
- } else {
2309
- throw (format(ERROR.INVALID_ARGUMENT, [newPayload, "newPayload"]));
2310
- }
2311
-
2312
- var destinationName;
2313
- var qos = 0;
2314
- var retained = false;
2315
- var duplicate = false;
2316
-
2317
- Object.defineProperties(this,{
2318
- "payloadString":{
2319
- enumerable : true,
2320
- get : function () {
2321
- if (typeof payload === "string")
2322
- return payload;
2323
- else
2324
- return parseUTF8(payload, 0, payload.length);
2325
- }
2326
- },
2327
- "payloadBytes":{
2328
- enumerable: true,
2329
- get: function() {
2330
- if (typeof payload === "string") {
2331
- var buffer = new ArrayBuffer(UTF8Length(payload));
2332
- var byteStream = new Uint8Array(buffer);
2333
- stringToUTF8(payload, byteStream, 0);
2334
-
2335
- return byteStream;
2336
- } else {
2337
- return payload;
2338
- }
2339
- }
2340
- },
2341
- "destinationName":{
2342
- enumerable: true,
2343
- get: function() { return destinationName; },
2344
- set: function(newDestinationName) {
2345
- if (typeof newDestinationName === "string")
2346
- destinationName = newDestinationName;
2347
- else
2348
- throw new Error(format(ERROR.INVALID_ARGUMENT, [newDestinationName, "newDestinationName"]));
2349
- }
2350
- },
2351
- "qos":{
2352
- enumerable: true,
2353
- get: function() { return qos; },
2354
- set: function(newQos) {
2355
- if (newQos === 0 || newQos === 1 || newQos === 2 )
2356
- qos = newQos;
2357
- else
2358
- throw new Error("Invalid argument:"+newQos);
2359
- }
2360
- },
2361
- "retained":{
2362
- enumerable: true,
2363
- get: function() { return retained; },
2364
- set: function(newRetained) {
2365
- if (typeof newRetained === "boolean")
2366
- retained = newRetained;
2367
- else
2368
- throw new Error(format(ERROR.INVALID_ARGUMENT, [newRetained, "newRetained"]));
2369
- }
2370
- },
2371
- "topic":{
2372
- enumerable: true,
2373
- get: function() { return destinationName; },
2374
- set: function(newTopic) {destinationName=newTopic;}
2375
- },
2376
- "duplicate":{
2377
- enumerable: true,
2378
- get: function() { return duplicate; },
2379
- set: function(newDuplicate) {duplicate=newDuplicate;}
2380
- }
2381
- });
2382
- };
2383
-
2384
- // Module contents.
2385
- return {
2386
- Client: Client,
2387
- Message: Message
2388
- };
2389
- // eslint-disable-next-line no-nested-ternary
2390
- })(typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
2391
- return PahoMQTT;
2392
- });
2393
-
2394
-
2395
- /***/ }),
2396
-
2397
- /***/ 25:
2398
- /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
2399
-
2400
- const MQTT = __webpack_require__(361);
2401
- const NanoID = __webpack_require__(78);
2402
-
2403
- const brokerStatusTopic = "/brokerStatus";
2404
-
2405
- class HubWorker {
2406
-
2407
- constructor(postMessage) {
2408
- this.postMessage = postMessage;
2409
-
2410
- this.state = { paho: null,
2411
- config: {},
2412
- buffer: [],
2413
- connected: false,
2414
- nextStatus: "virgin",
2415
- lastStatus: "virgin",
2416
- subscriptions: new Map(),
2417
- subStatus: new Map(),
2418
- localPubTopics: new Map(),
2419
- localSubTopics: new Map(),
2420
- retained: new Map(),
2421
- };
2422
- this.state.localPubTopics.set(brokerStatusTopic, true);
2423
- this.state.localSubTopics.set(brokerStatusTopic, true);
2424
-
2425
- console.log("messaging hub: worker started");
2426
- }
2427
-
2428
- // Wire this to the Worker's message handler (see index.js and node.js)
2429
- onmessage(ev) {
2430
- let msg = ev.data;
2431
- switch (msg._rmx_type) {
2432
- case "msg_hub_configure":
2433
- this.on_msg_configure(msg);
2434
- break
2435
- case "msg_hub_newChannel":
2436
- this.on_msg_newChannel(this, msg);
2437
- break
2438
- case "msg_hub_logStatus":
2439
- this.logStatus();
2440
- break
2441
- default:
2442
- console.error("messaging hub: unknown message type: " + msg._rmx_type)
2443
- }
2444
- }
2445
-
2446
- on_msg_configure(msg) {
2447
- this.state.config.user = msg.user;
2448
- this.state.config.token = msg.token;
2449
- // the Elm runtime sets msg.baseURL while mix_vm_starts sets msg.wsURL
2450
- let ws_url = msg.wsURL;
2451
- let add_path = false;
2452
- if (ws_url === undefined) {
2453
- ws_url = msg.baseURL;
2454
- add_path = true;
2455
- };
2456
- if (msg.standalone === true) {
2457
- console.log("messaging hub: standalone mode");
2458
- this.state.paho = null;
2459
- this.postMessage({ error: null });
2460
- return;
2461
- };
2462
- let useSSL = false;
2463
- if (ws_url.startsWith("http://")) {
2464
- ws_url = "ws://" + ws_url.substr(7);
2465
- } else if (ws_url.startsWith("https://")) {
2466
- ws_url = "wss://" + ws_url.substr(8);
2467
- useSSL = true;
2468
- } else if (!ws_url.startsWith("ws://") && !ws_url.startsWith("wss://")) {
2469
- console.error("messaging hub: bad baseURL: " + msg.baseURL);
2470
- }
2471
- if (add_path) {
2472
- if (!ws_url.endsWith("/")) ws_url += "/";
2473
- ws_url += "x/broker.ws";
2474
- }
2475
- let clientId = NanoID.nanoid();
2476
- console.log("messaging hub: connecting to broker at " + ws_url);
2477
- this.state.paho = new MQTT.Client(ws_url, clientId);
2478
- this.state.paho.onMessageArrived = ((msg) => {
2479
- this.on_paho_messageArrived(msg);
2480
- });
2481
- let first = true;
2482
- this.state.paho.onConnected = ((reconnected,uri) => {
2483
- this.state.connected = true;
2484
- this.state.nextStatus = reconnected ? "reconnected" : "connected";
2485
- this.logStatus();
2486
- if (first) {
2487
- this.postMessage({ error: null });
2488
- }
2489
- first = false;
2490
- while (this.state.buffer.length > 0) {
2491
- let f = this.state.buffer.shift();
2492
- try {
2493
- f();
2494
- } catch (e) {
2495
- console.error(e);
2496
- }
2497
- };
2498
- this.state.subscriptions.forEach((subs, topic) => {
2499
- this.broker_subscribe(topic, undefined, undefined, true)
2500
- });
2501
- if (this.are_all_subscriptions_made()) {
2502
- this.deliverStatus(this.state.nextStatus);
2503
- }
2504
- });
2505
- this.state.paho.onConnectionLost = (eobject => {
2506
- console.error("messaging hub: connection lost, " + "code " + eobject.errorCode + " " + eobject.errorMessage);
2507
- this.state.connected = false;
2508
- this.state.nextStatus = "disconnected";
2509
- this.state.subStatus = new Map();
2510
- this.deliverStatus("disconnected");
2511
- });
2512
- let opts =
2513
- { userName: msg.user,
2514
- password: "Bearer " + msg.token,
2515
- useSSL: useSSL,
2516
- onFailure: ((ctx, ecode, emsg) => {
2517
- this.state.connected = false;
2518
- console.error("messaging hub: connect failure, " + "code " + ecode + " " + emsg);
2519
- this.logStatus();
2520
- if (first)
2521
- this.postMessage({ error:emsg });
2522
- first = false;
2523
- }),
2524
- reconnect: true,
2525
- keepAliveInterval: 15,
2526
- // this should be larger than the period of the session keepalive
2527
- // messages (10 seconds), but otherwise short.
2528
- mqttVersion: 4
2529
- };
2530
- this.state.paho.connect(opts);
2531
- }
2532
-
2533
- logStatus() {
2534
- console.info("messaging hub: " + (this.state.connected ? "connected to " : "disconnected from ") + this.state.paho.host + ":" + this.state.paho.port)
2535
- }
2536
-
2537
- on_msg_newChannel(msg) {
2538
- let channel = new MessageChannel();
2539
- channel.port1.onmessage = (ev => this.chan_onmessage(channel.port1, ev));
2540
- this.postMessage( { error:null, port:channel.port2, reqId: msg.reqId },
2541
- [ channel.port2 ] )
2542
- // NB. msg.reqId is only available when this comes in via chan_onmessage,
2543
- // and not via onmessage.
2544
- }
2545
-
2546
- chan_onmessage(port, ev) {
2547
- let msg = ev.data;
2548
- switch (msg._rmx_type) {
2549
- case "msg_hub_publish":
2550
- this.on_chan_publish(port, msg);
2551
- break
2552
- case "msg_hub_get":
2553
- this.on_chan_get(port, msg);
2554
- break
2555
- case "msg_hub_subscribe":
2556
- this.on_chan_subscribe(port, msg);
2557
- break
2558
- case "msg_hub_unsubscribe":
2559
- this.on_chan_unsubscribe(port, msg);
2560
- break
2561
- case "msg_hub_setLocalPubTopic":
2562
- this.on_chan_setLocalPubTopic(port, msg);
2563
- break
2564
- case "msg_hub_setLocalSubTopic":
2565
- this.on_chan_setLocalSubTopic(port, msg);
2566
- break
2567
- case "msg_hub_newChannel":
2568
- this.on_msg_newChannel(port, msg);
2569
- break
2570
- default:
2571
- console.error("messaging hub: unknown message type: " + msg._rmx_type)
2572
- }
2573
- }
2574
-
2575
- on_chan_setLocalPubTopic(port, msg) {
2576
- this.state.localPubTopics.set(msg.topic, true);
2577
- let resp = { error: null, reqId: msg.reqId };
2578
- port.postMessage(resp);
2579
- }
2580
-
2581
- on_chan_setLocalSubTopic(port, msg) {
2582
- this.state.localSubTopics.set(msg.topic, true);
2583
- let resp = { error: null, reqId: msg.reqId };
2584
- port.postMessage(resp);
2585
- }
2586
-
2587
- isLocalPubTopic(topic) {
2588
- let topic_a = topic.split("/");
2589
- for (let n = topic_a.length; n >= 2; n--) {
2590
- let t = topic_a.slice(0, n).join("/");
2591
- if (this.state.localPubTopics.has(t)) return true;
2592
- };
2593
- if (this.state.localPubTopics.has("/")) return true;
2594
- return false;
2595
- }
2596
-
2597
- isLocalSubTopic(topic) {
2598
- let topic_a = topic.split("/");
2599
- for (let n = topic_a.length; n >= 2; n--) {
2600
- let t = topic_a.slice(0, n).join("/");
2601
- if (this.state.localSubTopics.has(t)) return true;
2602
- };
2603
- if (this.state.localSubTopics.has("/")) return true;
2604
- return false;
2605
- }
2606
-
2607
- when_connected(f) {
2608
- if (this.state.connected) {
2609
- f()
2610
- } else {
2611
- this.state.buffer.push(f);
2612
- }
2613
- }
2614
-
2615
- on_chan_publish(port, msg) {
2616
- if (msg.topic == brokerStatusTopic) {
2617
- let resp = { error:"cannot publish on restricted topic", reqId:msg.reqId };
2618
- port.postMessage(resp);
2619
- return
2620
- };
2621
- if (msg.retained) {
2622
- this.state.retained.set(msg.topic, msg)
2623
- };
2624
- this.deliver(msg); // local delivery
2625
- if (this.state.paho === null || msg.localOnly || this.isLocalPubTopic(msg.topic)) {
2626
- let resp = { error:null, reqId:msg.reqId };
2627
- port.postMessage(resp);
2628
- return
2629
- };
2630
- let header =
2631
- "_rmx_type=" + msg.header._rmx_type +
2632
- ",_rmx_encoding=" + msg.header._rmx_encoding +
2633
- ",_rmx_sender=" + msg.header._rmx_sender +
2634
- ",_rmx_route=" + this.state.paho.clientId + "\n";
2635
- let headerBuf = new TextEncoder().encode(header);
2636
- let payloadBuf;
2637
- switch (msg.header._rmx_encoding) {
2638
- case "text":
2639
- payloadBuf = new TextEncoder().encode(msg.payload);
2640
- break;
2641
- case "json":
2642
- const j = JSON.stringify(msg.payload);
2643
- payloadBuf = new TextEncoder().encode(msg.payload);
2644
- break;
2645
- case "binary":
2646
- payloadBuf = new Uint8Array(msg.payload);
2647
- break;
2648
- default:
2649
- console.error("bad encoding: " + msg.header._rmx_encoding)
2650
- }
2651
- let buf = new Uint8Array(headerBuf.length + payloadBuf.length);
2652
- buf.set(headerBuf, 0);
2653
- buf.set(payloadBuf, headerBuf.length);
2654
- this.when_connected(() => {
2655
- this.state.paho.publish(msg.topic, buf.buffer, 0, msg.retained);
2656
- });
2657
- let resp = { error:null, reqId:msg.reqId };
2658
- port.postMessage(resp);
2659
- }
2660
-
2661
- on_chan_get(port, msg) {
2662
- // local only!
2663
- let payload = this.state.retained.get(msg.topic);
2664
- let resp = { error:null, reqId:msg.reqId, payload:payload };
2665
- port.postMessage(resp);
2666
- }
2667
-
2668
- are_all_subscriptions_made() {
2669
- let ok = true;
2670
- this.state.subscriptions.forEach((_, topic) => {
2671
- if (!this.isLocalSubTopic(topic)) {
2672
- let status = this.state.subStatus.get(topic);
2673
- if (!status) ok = false; // status == false || status == undefined
2674
- }
2675
- });
2676
- return ok;
2677
- }
2678
-
2679
- broker_subscribe(topic, port, reqId, autoRetry) {
2680
- if (!this.state.connected) return;
2681
- if (this.state.subStatus.has(topic)) return;
2682
- if (this.isLocalSubTopic(topic)) return;
2683
- this.state.subStatus.set(topic, false);
2684
- let opts =
2685
- { qos: 0,
2686
- onSuccess: (ctx => {
2687
- console.log("messaging hub: subscribed to " + topic);
2688
- this.state.subStatus.set(topic, true);
2689
- if (port !== undefined && reqId !== undefined) {
2690
- let resp = { error:null, reqId: reqId };
2691
- port.postMessage(resp)
2692
- };
2693
- if (this.are_all_subscriptions_made()) {
2694
- this.deliverStatus(this.state.nextStatus);
2695
- }
2696
- }),
2697
- onFailure: ((ctx,ecode,emsg) => {
2698
- let text = "subscription to " + topic + " failed - code: " + ecode + " - text: " + emsg;
2699
- console.error("messaging hub: " + text);
2700
- if (port !== undefined && reqId !== undefined) {
2701
- let resp = { error:text, reqId: reqId };
2702
- port.postMessage(resp)
2703
- };
2704
- if (autoRetry) {
2705
- setTimeout(_ => {
2706
- this.broker_subscribe(topic, port, reqId, autoRetry);
2707
- }, 1000);
2708
- }
2709
- })
2710
- };
2711
- this.state.paho.subscribe(topic, opts);
2712
- }
2713
-
2714
- on_chan_subscribe(port, msg) {
2715
- let sub = { port:port, subId: msg.subId };
2716
- if (this.state.subscriptions.has(msg.topic)) {
2717
- let list = this.state.subscriptions.get(msg.topic);
2718
- list.push(sub);
2719
- port.postMessage({ error:null, reqId:msg.reqId });
2720
- if (this.state.retained.has(msg.topic)) {
2721
- this.deliver(this.state.retained.get(msg.topic))
2722
- };
2723
- return
2724
- };
2725
- let list = new Array();
2726
- list.push(sub);
2727
- this.state.subscriptions.set(msg.topic, list);
2728
- if (this.state.paho === null || this.isLocalSubTopic(msg.topic)) {
2729
- let resp = { error:null, reqId: msg.reqId };
2730
- port.postMessage(resp);
2731
- if (this.state.retained.has(msg.topic)) {
2732
- this.deliver(this.state.retained.get(msg.topic))
2733
- };
2734
- console.log("messaging hub: locally subscribed to " + msg.topic);
2735
- return
2736
- };
2737
- this.when_connected(() => {
2738
- this.broker_subscribe(msg.topic, port, msg.reqId, false);
2739
- })
2740
- }
2741
-
2742
- on_chan_unsubscribe(port, msg) {
2743
- if (!this.state.subscriptions.has(msg.topic)) {
2744
- let resp = { error:null, reqId: msg.reqId };
2745
- port.postMessage(resp);
2746
- return;
2747
- };
2748
- let list = this.state.subscriptions.get(msg.topic);
2749
- let newList = list.filter(sub => sub.subId != msg.subId);
2750
- if (newList.length > 0) {
2751
- this.state.subscriptions.set(msg.topic, newList);
2752
- let resp = { error:null, reqId: msg.reqId };
2753
- port.postMessage(resp);
2754
- } else {
2755
- this.state.subscriptions.delete(msg.topic);
2756
- if (this.state.paho === null || this.isLocalSubTopic(msg.topic) || !this.state.connected) {
2757
- console.log("messaging hub: locally unsubscribed from " + msg.topic);
2758
- let resp = { error:null, reqId: msg.reqId };
2759
- port.postMessage(resp);
2760
- } else {
2761
- let opts =
2762
- { onSuccess: ctx => {
2763
- console.log("messaging hub: unsubscribed from " + msg.topic);
2764
- let resp = { error:null, reqId: msg.reqId };
2765
- port.postMessage(resp)
2766
- },
2767
- onFailure: ((ctx,ecode,emsg) => {
2768
- let text = "unsubscribe from " + msg.topic + " failed - code: " + ecode + " - text: " + emsg;
2769
- console.error("messaging hub: " + text);
2770
- let resp = { error:text, reqId: msg.reqId };
2771
- port.postMessage(resp)
2772
- })
2773
- };
2774
- this.state.paho.unsubscribe(msg.topic, opts);
2775
- }
2776
- };
2777
- let eof =
2778
- { header: { _rmx_type: "",
2779
- _rmx_encoding: "",
2780
- _rmx_sender: ""
2781
- },
2782
- eof: true,
2783
- payload: null,
2784
- reqId: msg.subId
2785
- };
2786
- port.postMessage(eof);
2787
- }
2788
-
2789
- on_paho_messageArrived(mqtt_msg) {
2790
- let payload = new Uint8Array(mqtt_msg.payloadBytes);
2791
- let lf = payload.indexOf(10); // LF
2792
- if (lf < 0) {
2793
- console.error("messaging hub: Got undecodable MQTT message")
2794
- return
2795
- };
2796
- let line = new TextDecoder().decode(payload.subarray(0,lf));
2797
- let props = line.split(',');
2798
- let header = {};
2799
- for (let prop of props) {
2800
- let p = prop.split("=", 2)
2801
- if (p.length < 2) continue;
2802
- switch (p[0]) {
2803
- case "_rmx_type":
2804
- header._rmx_type = p[1];
2805
- break
2806
- case "_rmx_encoding":
2807
- header._rmx_encoding = p[1];
2808
- break
2809
- case "_rmx_sender":
2810
- header._rmx_sender = p[1];
2811
- break
2812
- case "_rmx_route":
2813
- let route = p[1].split(";");
2814
- if (route.includes(this.state.paho.clientId)) {
2815
- console.log("messaging hub: dropping duplicate message");
2816
- return
2817
- }
2818
- }
2819
- }
2820
- let nicePayload;
2821
- switch (header._rmx_encoding) {
2822
- case "text":
2823
- case "json":
2824
- nicePayload = new TextDecoder().decode(payload.subarray(lf+1));
2825
- break;
2826
- case "binary":
2827
- // not sure whether we can use payload.subarray here - the array
2828
- // comes from the MQTT client, and could be immediately reused
2829
- nicePayload = payload.slice(lf+1);
2830
- break;
2831
- default:
2832
- console.log("messaging hub: dropping message with bad _rmx_encoding")
2833
- }
2834
- let msg =
2835
- { header: header,
2836
- payload: nicePayload,
2837
- topic: mqtt_msg.destinationName,
2838
- retained: mqtt_msg.retained
2839
- };
2840
- if (msg.retained) {
2841
- this.state.retained.set(msg.topic, msg);
2842
- };
2843
- this.deliver(msg)
2844
- }
2845
-
2846
- deliver(msg) {
2847
- if (this.state.subscriptions.has(msg.topic)) {
2848
- let list = this.state.subscriptions.get(msg.topic);
2849
- let copy = Object.fromEntries(Object.entries(msg));
2850
- for (let sub of list) {
2851
- try {
2852
- copy.reqId = sub.subId;
2853
- sub.port.postMessage(copy)
2854
- } catch (error) {
2855
- // port could be closed. Ignore.
2856
- }
2857
- }
2858
- }
2859
- }
2860
-
2861
- deliverStatus(status) {
2862
- if (status == this.state.lastStatus) return;
2863
- this.state.lastStatus = status;
2864
- let topic = brokerStatusTopic;
2865
- let msg = {
2866
- "_rmx_type": "msg_hub_publish",
2867
- "header": {
2868
- "_rmx_type": "msg_hub_status",
2869
- "_rmx_encoding": "json",
2870
- "_rmx_sender": "hub-worker",
2871
- },
2872
- "topic": topic,
2873
- "payload": JSON.stringify(status),
2874
- "retained": true,
2875
- "localOnly": true,
2876
- };
2877
- this.state.retained.set(topic, msg);
2878
- console.debug("messaging hub: " + brokerStatusTopic + " = " + status);
2879
- this.deliver(msg);
2880
- }
2881
-
2882
- }
2883
-
2884
- module.exports = HubWorker;
2885
-
2886
-
2887
- /***/ }),
2888
-
2889
- /***/ 78:
2890
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2891
-
2892
- "use strict";
2893
- // ESM COMPAT FLAG
2894
- __webpack_require__.r(__webpack_exports__);
2895
-
2896
- // EXPORTS
2897
- __webpack_require__.d(__webpack_exports__, {
2898
- "customAlphabet": () => (/* binding */ customAlphabet),
2899
- "customRandom": () => (/* binding */ customRandom),
2900
- "nanoid": () => (/* binding */ nanoid),
2901
- "random": () => (/* binding */ random),
2902
- "urlAlphabet": () => (/* reexport */ urlAlphabet)
2903
- });
2904
-
2905
- ;// CONCATENATED MODULE: ./node_modules/nanoid/url-alphabet/index.js
2906
- let urlAlphabet =
2907
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
2908
-
2909
-
2910
- ;// CONCATENATED MODULE: ./node_modules/nanoid/index.browser.js
2911
-
2912
- let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
2913
- let customRandom = (alphabet, defaultSize, getRandom) => {
2914
- let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
2915
- let step = -~((1.6 * mask * defaultSize) / alphabet.length)
2916
- return (size = defaultSize) => {
2917
- let id = ''
2918
- while (true) {
2919
- let bytes = getRandom(step)
2920
- let j = step
2921
- while (j--) {
2922
- id += alphabet[bytes[j] & mask] || ''
2923
- if (id.length === size) return id
2924
- }
2925
- }
2926
- }
2927
- }
2928
- let customAlphabet = (alphabet, size = 21) =>
2929
- customRandom(alphabet, size, random)
2930
- let nanoid = (size = 21) =>
2931
- crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
2932
- byte &= 63
2933
- if (byte < 36) {
2934
- id += byte.toString(36)
2935
- } else if (byte < 62) {
2936
- id += (byte - 26).toString(36).toUpperCase()
2937
- } else if (byte > 62) {
2938
- id += '-'
2939
- } else {
2940
- id += '_'
2941
- }
2942
- return id
2943
- }, '')
2944
-
2945
-
2946
-
2947
- /***/ })
2948
-
2949
- /******/ });
2950
- /************************************************************************/
2951
- /******/ // The module cache
2952
- /******/ var __webpack_module_cache__ = {};
2953
- /******/
2954
- /******/ // The require function
2955
- /******/ function __webpack_require__(moduleId) {
2956
- /******/ // Check if module is in cache
2957
- /******/ var cachedModule = __webpack_module_cache__[moduleId];
2958
- /******/ if (cachedModule !== undefined) {
2959
- /******/ return cachedModule.exports;
2960
- /******/ }
2961
- /******/ // Create a new module (and put it into the cache)
2962
- /******/ var module = __webpack_module_cache__[moduleId] = {
2963
- /******/ // no module.id needed
2964
- /******/ // no module.loaded needed
2965
- /******/ exports: {}
2966
- /******/ };
2967
- /******/
2968
- /******/ // Execute the module function
2969
- /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
2970
- /******/
2971
- /******/ // Return the exports of the module
2972
- /******/ return module.exports;
2973
- /******/ }
2974
- /******/
2975
- /************************************************************************/
2976
- /******/ /* webpack/runtime/define property getters */
2977
- /******/ (() => {
2978
- /******/ // define getter functions for harmony exports
2979
- /******/ __webpack_require__.d = (exports, definition) => {
2980
- /******/ for(var key in definition) {
2981
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
2982
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
2983
- /******/ }
2984
- /******/ }
2985
- /******/ };
2986
- /******/ })();
2987
- /******/
2988
- /******/ /* webpack/runtime/global */
2989
- /******/ (() => {
2990
- /******/ __webpack_require__.g = (function() {
2991
- /******/ if (typeof globalThis === 'object') return globalThis;
2992
- /******/ try {
2993
- /******/ return this || new Function('return this')();
2994
- /******/ } catch (e) {
2995
- /******/ if (typeof window === 'object') return window;
2996
- /******/ }
2997
- /******/ })();
2998
- /******/ })();
2999
- /******/
3000
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
3001
- /******/ (() => {
3002
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
3003
- /******/ })();
3004
- /******/
3005
- /******/ /* webpack/runtime/make namespace object */
3006
- /******/ (() => {
3007
- /******/ // define __esModule on exports
3008
- /******/ __webpack_require__.r = (exports) => {
3009
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
3010
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3011
- /******/ }
3012
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
3013
- /******/ };
3014
- /******/ })();
3015
- /******/
3016
- /************************************************************************/
3017
- var __webpack_exports__ = {};
3018
- // This entry need to be wrapped in an IIFE because it need to be in strict mode.
3019
- (() => {
3020
- "use strict";
3021
- /* harmony import */ var _worker_cjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25);
3022
-
3023
-
3024
- // Instantiate worker and wire up message handling: we pass in the global
3025
- // `postMessage` method that exists in the web Worker context, for passing
3026
- // messages back out to the main script.
3027
- const worker = new _worker_cjs__WEBPACK_IMPORTED_MODULE_0__(postMessage);
3028
-
3029
- // `onmessage` is exposed for passing in messages from the main script. We bind
3030
- // `worker.onmessage` so that `this` is available.
3031
- onmessage = worker.onmessage.bind(worker);
3032
-
3033
- })();
3034
-
3035
- /******/ })()
3036
- ;
1
+ (()=>{var e={361:function(e,t,s){var n;n=function(){var e=function(e){var t,s=e.localStorage||(t={},{setItem:function(e,s){t[e]=s},getItem:function(e){return t[e]},removeItem:function(e){delete t[e]}}),n=function(e,t){for(var s in e)if(e.hasOwnProperty(s)){if(!t.hasOwnProperty(s)){var n="Unknown property, "+s+". Valid properties are:";for(var i in t)t.hasOwnProperty(i)&&(n=n+" "+i);throw new Error(n)}if(typeof e[s]!==t[s])throw new Error(a(o.INVALID_TYPE,[typeof e[s],s]))}},i=function(e,t){return function(){return e.apply(t,arguments)}},o={OK:{code:0,text:"AMQJSC0000I OK."},CONNECT_TIMEOUT:{code:1,text:"AMQJSC0001E Connect timed out."},SUBSCRIBE_TIMEOUT:{code:2,text:"AMQJS0002E Subscribe timed out."},UNSUBSCRIBE_TIMEOUT:{code:3,text:"AMQJS0003E Unsubscribe timed out."},PING_TIMEOUT:{code:4,text:"AMQJS0004E Ping timed out."},INTERNAL_ERROR:{code:5,text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},CONNACK_RETURNCODE:{code:6,text:"AMQJS0006E Bad Connack return code:{0} {1}."},SOCKET_ERROR:{code:7,text:"AMQJS0007E Socket error:{0}."},SOCKET_CLOSE:{code:8,text:"AMQJS0008I Socket closed."},MALFORMED_UTF:{code:9,text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},UNSUPPORTED:{code:10,text:"AMQJS0010E {0} is not supported by this browser."},INVALID_STATE:{code:11,text:"AMQJS0011E Invalid state {0}."},INVALID_TYPE:{code:12,text:"AMQJS0012E Invalid type {0} for {1}."},INVALID_ARGUMENT:{code:13,text:"AMQJS0013E Invalid argument {0} for {1}."},UNSUPPORTED_OPERATION:{code:14,text:"AMQJS0014E Unsupported operation."},INVALID_STORED_DATA:{code:15,text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},INVALID_MQTT_MESSAGE_TYPE:{code:16,text:"AMQJS0016E Invalid MQTT message type {0}."},MALFORMED_UNICODE:{code:17,text:"AMQJS0017E Malformed Unicode string:{0} {1}."},BUFFER_FULL:{code:18,text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."}},r={0:"Connection Accepted",1:"Connection Refused: unacceptable protocol version",2:"Connection Refused: identifier rejected",3:"Connection Refused: server unavailable",4:"Connection Refused: bad user name or password",5:"Connection Refused: not authorized"},a=function(e,t){var s=e.text;if(t)for(var n,i,o=0;o<t.length;o++)if(n="{"+o+"}",(i=s.indexOf(n))>0){var r=s.substring(0,i),a=s.substring(i+n.length);s=r+t[o]+a}return s},c=[0,6,77,81,73,115,100,112,3],h=[0,4,77,81,84,84,4],u=function(e,t){for(var s in this.type=e,t)t.hasOwnProperty(s)&&(this[s]=t[s])};function l(e,t){var s,n=t,i=e[t],o=i>>4,r=i&=15;t+=1;var a=0,c=1;do{if(t==e.length)return[null,n];a+=(127&(s=e[t++]))*c,c*=128}while(0!=(128&s));var h=t+a;if(h>e.length)return[null,n];var l=new u(o);switch(o){case 2:1&e[t++]&&(l.sessionPresent=!0),l.returnCode=e[t++];break;case 3:var d=r>>1&3,p=g(e,t),f=m(e,t+=2,p);t+=p,d>0&&(l.messageIdentifier=g(e,t),t+=2);var _=new w(e.subarray(t,h));1==(1&r)&&(_.retained=!0),8==(8&r)&&(_.duplicate=!0),_.qos=d,_.destinationName=f,l.payloadMessage=_;break;case 4:case 5:case 6:case 7:case 11:l.messageIdentifier=g(e,t);break;case 9:l.messageIdentifier=g(e,t),t+=2,l.returnCode=e.subarray(t,h)}return[l,h]}function d(e,t,s){return t[s++]=e>>8,t[s++]=e%256,s}function p(e,t,s,n){return _(e,s,n=d(t,s,n)),n+t}function g(e,t){return 256*e[t]+e[t+1]}function f(e){for(var t=0,s=0;s<e.length;s++){var n=e.charCodeAt(s);n>2047?(55296<=n&&n<=56319&&(s++,t++),t+=3):n>127?t+=2:t++}return t}function _(e,t,s){for(var n=s,i=0;i<e.length;i++){var r=e.charCodeAt(i);if(55296<=r&&r<=56319){var c=e.charCodeAt(++i);if(isNaN(c))throw new Error(a(o.MALFORMED_UNICODE,[r,c]));r=c-56320+(r-55296<<10)+65536}r<=127?t[n++]=r:r<=2047?(t[n++]=r>>6&31|192,t[n++]=63&r|128):r<=65535?(t[n++]=r>>12&15|224,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>18&7|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128)}return t}function m(e,t,s){for(var n,i="",r=t;r<t+s;){var c=e[r++];if(c<128)n=c;else{var h=e[r++]-128;if(h<0)throw new Error(a(o.MALFORMED_UTF,[c.toString(16),h.toString(16),""]));if(c<224)n=64*(c-192)+h;else{var u=e[r++]-128;if(u<0)throw new Error(a(o.MALFORMED_UTF,[c.toString(16),h.toString(16),u.toString(16)]));if(c<240)n=4096*(c-224)+64*h+u;else{var l=e[r++]-128;if(l<0)throw new Error(a(o.MALFORMED_UTF,[c.toString(16),h.toString(16),u.toString(16),l.toString(16)]));if(!(c<248))throw new Error(a(o.MALFORMED_UTF,[c.toString(16),h.toString(16),u.toString(16),l.toString(16)]));n=262144*(c-240)+4096*h+64*u+l}}}n>65535&&(n-=65536,i+=String.fromCharCode(55296+(n>>10)),n=56320+(1023&n)),i+=String.fromCharCode(n)}return i}u.prototype.encode=function(){var e,t=(15&this.type)<<4,s=0,n=[],i=0;switch(void 0!==this.messageIdentifier&&(s+=2),this.type){case 1:switch(this.mqttVersion){case 3:s+=c.length+3;break;case 4:s+=h.length+3}s+=f(this.clientId)+2,void 0!==this.willMessage&&(s+=f(this.willMessage.destinationName)+2,(e=this.willMessage.payloadBytes)instanceof Uint8Array||(e=new Uint8Array(r)),s+=e.byteLength+2),void 0!==this.userName&&(s+=f(this.userName)+2),void 0!==this.password&&(s+=f(this.password)+2);break;case 8:t|=2;for(var o=0;o<this.topics.length;o++)n[o]=f(this.topics[o]),s+=n[o]+2;s+=this.requestedQos.length;break;case 10:for(t|=2,o=0;o<this.topics.length;o++)n[o]=f(this.topics[o]),s+=n[o]+2;break;case 6:t|=2;break;case 3:this.payloadMessage.duplicate&&(t|=8),t=t|=this.payloadMessage.qos<<1,this.payloadMessage.retained&&(t|=1),s+=(i=f(this.payloadMessage.destinationName))+2;var r=this.payloadMessage.payloadBytes;s+=r.byteLength,r instanceof ArrayBuffer?r=new Uint8Array(r):r instanceof Uint8Array||(r=new Uint8Array(r.buffer))}var a=function(e){var t=new Array(1),s=0;do{var n=e%128;(e>>=7)>0&&(n|=128),t[s++]=n}while(e>0&&s<4);return t}(s),u=a.length+1,l=new ArrayBuffer(s+u),g=new Uint8Array(l);if(g[0]=t,g.set(a,1),3==this.type)u=p(this.payloadMessage.destinationName,i,g,u);else if(1==this.type){switch(this.mqttVersion){case 3:g.set(c,u),u+=c.length;break;case 4:g.set(h,u),u+=h.length}var _=0;this.cleanSession&&(_=2),void 0!==this.willMessage&&(_|=4,_|=this.willMessage.qos<<3,this.willMessage.retained&&(_|=32)),void 0!==this.userName&&(_|=128),void 0!==this.password&&(_|=64),g[u++]=_,u=d(this.keepAliveInterval,g,u)}switch(void 0!==this.messageIdentifier&&(u=d(this.messageIdentifier,g,u)),this.type){case 1:u=p(this.clientId,f(this.clientId),g,u),void 0!==this.willMessage&&(u=p(this.willMessage.destinationName,f(this.willMessage.destinationName),g,u),u=d(e.byteLength,g,u),g.set(e,u),u+=e.byteLength),void 0!==this.userName&&(u=p(this.userName,f(this.userName),g,u)),void 0!==this.password&&(u=p(this.password,f(this.password),g,u));break;case 3:g.set(r,u);break;case 8:for(o=0;o<this.topics.length;o++)u=p(this.topics[o],n[o],g,u),g[u++]=this.requestedQos[o];break;case 10:for(o=0;o<this.topics.length;o++)u=p(this.topics[o],n[o],g,u)}return l};var b=function(e,t){this._client=e,this._keepAliveInterval=1e3*t,this.isReset=!1;var s=new u(12).encode(),n=function(e){return function(){return i.apply(e)}},i=function(){this.isReset?(this.isReset=!1,this._client._trace("Pinger.doPing","send PINGREQ"),this._client.socket.send(s),this.timeout=setTimeout(n(this),this._keepAliveInterval)):(this._client._trace("Pinger.doPing","Timed out"),this._client._disconnected(o.PING_TIMEOUT.code,a(o.PING_TIMEOUT)))};this.reset=function(){this.isReset=!0,clearTimeout(this.timeout),this._keepAliveInterval>0&&(this.timeout=setTimeout(n(this),this._keepAliveInterval))},this.cancel=function(){clearTimeout(this.timeout)}},y=function(e,t,s,n){t||(t=30),this.timeout=setTimeout(function(e,t,s){return function(){return e.apply(t,s)}}(s,e,n),1e3*t),this.cancel=function(){clearTimeout(this.timeout)}},v=function(t,n,i,r,c){if(!("WebSocket"in e)||null===e.WebSocket)throw new Error(a(o.UNSUPPORTED,["WebSocket"]));if(!("ArrayBuffer"in e)||null===e.ArrayBuffer)throw new Error(a(o.UNSUPPORTED,["ArrayBuffer"]));for(var h in this._trace("Paho.Client",t,n,i,r,c),this.host=n,this.port=i,this.path=r,this.uri=t,this.clientId=c,this._wsuri=null,this._localKey=n+":"+i+("/mqtt"!=r?":"+r:"")+":"+c+":",this._msg_queue=[],this._buffered_msg_queue=[],this._sentMessages={},this._receivedMessages={},this._notify_msg_sent={},this._message_identifier=1,this._sequence=0,s)0!==h.indexOf("Sent:"+this._localKey)&&0!==h.indexOf("Received:"+this._localKey)||this.restore(h)};v.prototype.host=null,v.prototype.port=null,v.prototype.path=null,v.prototype.uri=null,v.prototype.clientId=null,v.prototype.socket=null,v.prototype.connected=!1,v.prototype.maxMessageIdentifier=65536,v.prototype.connectOptions=null,v.prototype.hostIndex=null,v.prototype.onConnected=null,v.prototype.onConnectionLost=null,v.prototype.onMessageDelivered=null,v.prototype.onMessageArrived=null,v.prototype.traceFunction=null,v.prototype._msg_queue=null,v.prototype._buffered_msg_queue=null,v.prototype._connectTimeout=null,v.prototype.sendPinger=null,v.prototype.receivePinger=null,v.prototype._reconnectInterval=1,v.prototype._reconnecting=!1,v.prototype._reconnectTimeout=null,v.prototype.disconnectedPublishing=!1,v.prototype.disconnectedBufferSize=5e3,v.prototype.receiveBuffer=null,v.prototype._traceBuffer=null,v.prototype._MAX_TRACE_ENTRIES=100,v.prototype.connect=function(e){var t=this._traceMask(e,"password");if(this._trace("Client.connect",t,this.socket,this.connected),this.connected)throw new Error(a(o.INVALID_STATE,["already connected"]));if(this.socket)throw new Error(a(o.INVALID_STATE,["already connected"]));this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),this.connectOptions=e,this._reconnectInterval=1,this._reconnecting=!1,e.uris?(this.hostIndex=0,this._doConnect(e.uris[0])):this._doConnect(this.uri)},v.prototype.subscribe=function(e,t){if(this._trace("Client.subscribe",e,t),!this.connected)throw new Error(a(o.INVALID_STATE,["not connected"]));var s=new u(8);s.topics=e.constructor===Array?e:[e],void 0===t.qos&&(t.qos=0),s.requestedQos=[];for(var n=0;n<s.topics.length;n++)s.requestedQos[n]=t.qos;t.onSuccess&&(s.onSuccess=function(e){t.onSuccess({invocationContext:t.invocationContext,grantedQos:e})}),t.onFailure&&(s.onFailure=function(e){t.onFailure({invocationContext:t.invocationContext,errorCode:e,errorMessage:a(e)})}),t.timeout&&(s.timeOut=new y(this,t.timeout,t.onFailure,[{invocationContext:t.invocationContext,errorCode:o.SUBSCRIBE_TIMEOUT.code,errorMessage:a(o.SUBSCRIBE_TIMEOUT)}])),this._requires_ack(s),this._schedule_message(s)},v.prototype.unsubscribe=function(e,t){if(this._trace("Client.unsubscribe",e,t),!this.connected)throw new Error(a(o.INVALID_STATE,["not connected"]));var s=new u(10);s.topics=e.constructor===Array?e:[e],t.onSuccess&&(s.callback=function(){t.onSuccess({invocationContext:t.invocationContext})}),t.timeout&&(s.timeOut=new y(this,t.timeout,t.onFailure,[{invocationContext:t.invocationContext,errorCode:o.UNSUBSCRIBE_TIMEOUT.code,errorMessage:a(o.UNSUBSCRIBE_TIMEOUT)}])),this._requires_ack(s),this._schedule_message(s)},v.prototype.send=function(e){this._trace("Client.send",e);var t=new u(3);if(t.payloadMessage=e,this.connected)e.qos>0?this._requires_ack(t):this.onMessageDelivered&&(this._notify_msg_sent[t]=this.onMessageDelivered(t.payloadMessage)),this._schedule_message(t);else{if(!this._reconnecting||!this.disconnectedPublishing)throw new Error(a(o.INVALID_STATE,["not connected"]));if(Object.keys(this._sentMessages).length+this._buffered_msg_queue.length>this.disconnectedBufferSize)throw new Error(a(o.BUFFER_FULL,[this.disconnectedBufferSize]));e.qos>0?this._requires_ack(t):(t.sequence=++this._sequence,this._buffered_msg_queue.unshift(t))}},v.prototype.disconnect=function(){if(this._trace("Client.disconnect"),this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),!this.socket)throw new Error(a(o.INVALID_STATE,["not connecting or connected"]));var e=new u(14);this._notify_msg_sent[e]=i(this._disconnected,this),this._schedule_message(e)},v.prototype.getTraceLog=function(){if(null!==this._traceBuffer){for(var e in this._trace("Client.getTraceLog",new Date),this._trace("Client.getTraceLog in flight messages",this._sentMessages.length),this._sentMessages)this._trace("_sentMessages ",e,this._sentMessages[e]);for(var e in this._receivedMessages)this._trace("_receivedMessages ",e,this._receivedMessages[e]);return this._traceBuffer}},v.prototype.startTrace=function(){null===this._traceBuffer&&(this._traceBuffer=[]),this._trace("Client.startTrace",new Date,"@VERSION@-@BUILDLEVEL@")},v.prototype.stopTrace=function(){delete this._traceBuffer},v.prototype._doConnect=function(e){if(this.connectOptions.useSSL){var t=e.split(":");t[0]="wss",e=t.join(":")}this._wsuri=e,this.connected=!1,this.connectOptions.mqttVersion<4?this.socket=new WebSocket(e,["mqttv3.1"]):this.socket=new WebSocket(e,["mqtt"]),this.socket.binaryType="arraybuffer",this.socket.onopen=i(this._on_socket_open,this),this.socket.onmessage=i(this._on_socket_message,this),this.socket.onerror=i(this._on_socket_error,this),this.socket.onclose=i(this._on_socket_close,this),this.sendPinger=new b(this,this.connectOptions.keepAliveInterval),this.receivePinger=new b(this,this.connectOptions.keepAliveInterval),this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null),this._connectTimeout=new y(this,this.connectOptions.timeout,this._disconnected,[o.CONNECT_TIMEOUT.code,a(o.CONNECT_TIMEOUT)])},v.prototype._schedule_message=function(e){this._msg_queue.unshift(e),this.connected&&this._process_queue()},v.prototype.store=function(e,t){var n={type:t.type,messageIdentifier:t.messageIdentifier,version:1};if(3!==t.type)throw Error(a(o.INVALID_STORED_DATA,[e+this._localKey+t.messageIdentifier,n]));t.pubRecReceived&&(n.pubRecReceived=!0),n.payloadMessage={};for(var i="",r=t.payloadMessage.payloadBytes,c=0;c<r.length;c++)r[c]<=15?i=i+"0"+r[c].toString(16):i+=r[c].toString(16);n.payloadMessage.payloadHex=i,n.payloadMessage.qos=t.payloadMessage.qos,n.payloadMessage.destinationName=t.payloadMessage.destinationName,t.payloadMessage.duplicate&&(n.payloadMessage.duplicate=!0),t.payloadMessage.retained&&(n.payloadMessage.retained=!0),0===e.indexOf("Sent:")&&(void 0===t.sequence&&(t.sequence=++this._sequence),n.sequence=t.sequence),s.setItem(e+this._localKey+t.messageIdentifier,JSON.stringify(n))},v.prototype.restore=function(e){var t=s.getItem(e),n=JSON.parse(t),i=new u(n.type,n);if(3!==n.type)throw Error(a(o.INVALID_STORED_DATA,[e,t]));for(var r=n.payloadMessage.payloadHex,c=new ArrayBuffer(r.length/2),h=new Uint8Array(c),l=0;r.length>=2;){var d=parseInt(r.substring(0,2),16);r=r.substring(2,r.length),h[l++]=d}var p=new w(h);p.qos=n.payloadMessage.qos,p.destinationName=n.payloadMessage.destinationName,n.payloadMessage.duplicate&&(p.duplicate=!0),n.payloadMessage.retained&&(p.retained=!0),i.payloadMessage=p,0===e.indexOf("Sent:"+this._localKey)?(i.payloadMessage.duplicate=!0,this._sentMessages[i.messageIdentifier]=i):0===e.indexOf("Received:"+this._localKey)&&(this._receivedMessages[i.messageIdentifier]=i)},v.prototype._process_queue=function(){for(var e=null;e=this._msg_queue.pop();)this._socket_send(e),this._notify_msg_sent[e]&&(this._notify_msg_sent[e](),delete this._notify_msg_sent[e])},v.prototype._requires_ack=function(e){var t=Object.keys(this._sentMessages).length;if(t>this.maxMessageIdentifier)throw Error("Too many messages:"+t);for(;void 0!==this._sentMessages[this._message_identifier];)this._message_identifier++;e.messageIdentifier=this._message_identifier,this._sentMessages[e.messageIdentifier]=e,3===e.type&&this.store("Sent:",e),this._message_identifier===this.maxMessageIdentifier&&(this._message_identifier=1)},v.prototype._on_socket_open=function(){var e=new u(1,this.connectOptions);e.clientId=this.clientId,this._socket_send(e)},v.prototype._on_socket_message=function(e){this._trace("Client._on_socket_message",e.data);for(var t=this._deframeMessages(e.data),s=0;s<t.length;s+=1)this._handleMessage(t[s])},v.prototype._deframeMessages=function(e){var t=new Uint8Array(e),s=[];if(this.receiveBuffer){var n=new Uint8Array(this.receiveBuffer.length+t.length);n.set(this.receiveBuffer),n.set(t,this.receiveBuffer.length),t=n,delete this.receiveBuffer}try{for(var i=0;i<t.length;){var r=l(t,i),c=r[0];if(i=r[1],null===c)break;s.push(c)}i<t.length&&(this.receiveBuffer=t.subarray(i))}catch(e){var h="undefined"==e.hasOwnProperty("stack")?e.stack.toString():"No Error Stack Available";return void this._disconnected(o.INTERNAL_ERROR.code,a(o.INTERNAL_ERROR,[e.message,h]))}return s},v.prototype._handleMessage=function(e){this._trace("Client._handleMessage",e);try{switch(e.type){case 2:if(this._connectTimeout.cancel(),this._reconnectTimeout&&this._reconnectTimeout.cancel(),this.connectOptions.cleanSession){for(var t in this._sentMessages){var n=this._sentMessages[t];s.removeItem("Sent:"+this._localKey+n.messageIdentifier)}for(var t in this._sentMessages={},this._receivedMessages){var i=this._receivedMessages[t];s.removeItem("Received:"+this._localKey+i.messageIdentifier)}this._receivedMessages={}}if(0!==e.returnCode){this._disconnected(o.CONNACK_RETURNCODE.code,a(o.CONNACK_RETURNCODE,[e.returnCode,r[e.returnCode]]));break}this.connected=!0,this.connectOptions.uris&&(this.hostIndex=this.connectOptions.uris.length);var c=[];for(var h in this._sentMessages)this._sentMessages.hasOwnProperty(h)&&c.push(this._sentMessages[h]);if(this._buffered_msg_queue.length>0)for(var l=null;l=this._buffered_msg_queue.pop();)c.push(l),this.onMessageDelivered&&(this._notify_msg_sent[l]=this.onMessageDelivered(l.payloadMessage));c=c.sort((function(e,t){return e.sequence-t.sequence}));for(var d=0,p=c.length;d<p;d++)if(3==(n=c[d]).type&&n.pubRecReceived){var g=new u(6,{messageIdentifier:n.messageIdentifier});this._schedule_message(g)}else this._schedule_message(n);this.connectOptions.onSuccess&&this.connectOptions.onSuccess({invocationContext:this.connectOptions.invocationContext});var f=!1;this._reconnecting&&(f=!0,this._reconnectInterval=1,this._reconnecting=!1),this._connected(f,this._wsuri),this._process_queue();break;case 3:this._receivePublish(e);break;case 4:(n=this._sentMessages[e.messageIdentifier])&&(delete this._sentMessages[e.messageIdentifier],s.removeItem("Sent:"+this._localKey+e.messageIdentifier),this.onMessageDelivered&&this.onMessageDelivered(n.payloadMessage));break;case 5:(n=this._sentMessages[e.messageIdentifier])&&(n.pubRecReceived=!0,g=new u(6,{messageIdentifier:e.messageIdentifier}),this.store("Sent:",n),this._schedule_message(g));break;case 6:i=this._receivedMessages[e.messageIdentifier],s.removeItem("Received:"+this._localKey+e.messageIdentifier),i&&(this._receiveMessage(i),delete this._receivedMessages[e.messageIdentifier]);var _=new u(7,{messageIdentifier:e.messageIdentifier});this._schedule_message(_);break;case 7:n=this._sentMessages[e.messageIdentifier],delete this._sentMessages[e.messageIdentifier],s.removeItem("Sent:"+this._localKey+e.messageIdentifier),this.onMessageDelivered&&this.onMessageDelivered(n.payloadMessage);break;case 9:(n=this._sentMessages[e.messageIdentifier])&&(n.timeOut&&n.timeOut.cancel(),128===e.returnCode[0]?n.onFailure&&n.onFailure(e.returnCode):n.onSuccess&&n.onSuccess(e.returnCode),delete this._sentMessages[e.messageIdentifier]);break;case 11:(n=this._sentMessages[e.messageIdentifier])&&(n.timeOut&&n.timeOut.cancel(),n.callback&&n.callback(),delete this._sentMessages[e.messageIdentifier]);break;case 13:this.sendPinger.reset();break;default:this._disconnected(o.INVALID_MQTT_MESSAGE_TYPE.code,a(o.INVALID_MQTT_MESSAGE_TYPE,[e.type]))}}catch(e){var m="undefined"==e.hasOwnProperty("stack")?e.stack.toString():"No Error Stack Available";return void this._disconnected(o.INTERNAL_ERROR.code,a(o.INTERNAL_ERROR,[e.message,m]))}},v.prototype._on_socket_error=function(e){this._reconnecting||this._disconnected(o.SOCKET_ERROR.code,a(o.SOCKET_ERROR,[e.data]))},v.prototype._on_socket_close=function(){this._reconnecting||this._disconnected(o.SOCKET_CLOSE.code,a(o.SOCKET_CLOSE))},v.prototype._socket_send=function(e){if(1==e.type){var t=this._traceMask(e,"password");this._trace("Client._socket_send",t)}else this._trace("Client._socket_send",e);this.socket.send(e.encode()),this.sendPinger.reset()},v.prototype._receivePublish=function(e){switch(e.payloadMessage.qos){case"undefined":case 0:this._receiveMessage(e);break;case 1:var t=new u(4,{messageIdentifier:e.messageIdentifier});this._schedule_message(t),this._receiveMessage(e);break;case 2:this._receivedMessages[e.messageIdentifier]=e,this.store("Received:",e);var s=new u(5,{messageIdentifier:e.messageIdentifier});this._schedule_message(s);break;default:throw Error("Invaild qos="+e.payloadMessage.qos)}},v.prototype._receiveMessage=function(e){this.onMessageArrived&&this.onMessageArrived(e.payloadMessage)},v.prototype._connected=function(e,t){this.onConnected&&this.onConnected(e,t)},v.prototype._reconnect=function(){this._trace("Client._reconnect"),this.connected||(this._reconnecting=!0,this.sendPinger.cancel(),this.receivePinger.cancel(),this._reconnectInterval<128&&(this._reconnectInterval=2*this._reconnectInterval),this.connectOptions.uris?(this.hostIndex=0,this._doConnect(this.connectOptions.uris[0])):this._doConnect(this.uri))},v.prototype._disconnected=function(e,t){if(this._trace("Client._disconnected",e,t),void 0!==e&&this._reconnecting)this._reconnectTimeout=new y(this,this._reconnectInterval,this._reconnect);else if(this.sendPinger.cancel(),this.receivePinger.cancel(),this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null),this._msg_queue=[],this._buffered_msg_queue=[],this._notify_msg_sent={},this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,1===this.socket.readyState&&this.socket.close(),delete this.socket),this.connectOptions.uris&&this.hostIndex<this.connectOptions.uris.length-1)this.hostIndex++,this._doConnect(this.connectOptions.uris[this.hostIndex]);else if(void 0===e&&(e=o.OK.code,t=a(o.OK)),this.connected){if(this.connected=!1,this.onConnectionLost&&this.onConnectionLost({errorCode:e,errorMessage:t,reconnect:this.connectOptions.reconnect,uri:this._wsuri}),e!==o.OK.code&&this.connectOptions.reconnect)return this._reconnectInterval=1,void this._reconnect()}else 4===this.connectOptions.mqttVersion&&!1===this.connectOptions.mqttVersionExplicit?(this._trace("Failed to connect V4, dropping back to V3"),this.connectOptions.mqttVersion=3,this.connectOptions.uris?(this.hostIndex=0,this._doConnect(this.connectOptions.uris[0])):this._doConnect(this.uri)):this.connectOptions.onFailure&&this.connectOptions.onFailure({invocationContext:this.connectOptions.invocationContext,errorCode:e,errorMessage:t})},v.prototype._trace=function(){if(this.traceFunction){var e=Array.prototype.slice.call(arguments);for(var t in e)void 0!==e[t]&&e.splice(t,1,JSON.stringify(e[t]));var s=e.join("");this.traceFunction({severity:"Debug",message:s})}if(null!==this._traceBuffer){t=0;for(var n=arguments.length;t<n;t++)this._traceBuffer.length==this._MAX_TRACE_ENTRIES&&this._traceBuffer.shift(),0===t||void 0===arguments[t]?this._traceBuffer.push(arguments[t]):this._traceBuffer.push(" "+JSON.stringify(arguments[t]))}},v.prototype._traceMask=function(e,t){var s={};for(var n in e)e.hasOwnProperty(n)&&(s[n]=n==t?"******":e[n]);return s};var w=function(e){var t,s;if(!("string"==typeof e||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView)))throw a(o.INVALID_ARGUMENT,[e,"newPayload"]);t=e;var n=0,i=!1,r=!1;Object.defineProperties(this,{payloadString:{enumerable:!0,get:function(){return"string"==typeof t?t:m(t,0,t.length)}},payloadBytes:{enumerable:!0,get:function(){if("string"==typeof t){var e=new ArrayBuffer(f(t)),s=new Uint8Array(e);return _(t,s,0),s}return t}},destinationName:{enumerable:!0,get:function(){return s},set:function(e){if("string"!=typeof e)throw new Error(a(o.INVALID_ARGUMENT,[e,"newDestinationName"]));s=e}},qos:{enumerable:!0,get:function(){return n},set:function(e){if(0!==e&&1!==e&&2!==e)throw new Error("Invalid argument:"+e);n=e}},retained:{enumerable:!0,get:function(){return i},set:function(e){if("boolean"!=typeof e)throw new Error(a(o.INVALID_ARGUMENT,[e,"newRetained"]));i=e}},topic:{enumerable:!0,get:function(){return s},set:function(e){s=e}},duplicate:{enumerable:!0,get:function(){return r},set:function(e){r=e}}})};return{Client:function(e,t,s,i){var r;if("string"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"host"]));if(2==arguments.length){i=t;var c=(r=e).match(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/);if(!c)throw new Error(a(o.INVALID_ARGUMENT,[e,"host"]));e=c[4]||c[2],t=parseInt(c[7]),s=c[8]}else{if(3==arguments.length&&(i=s,s="/mqtt"),"number"!=typeof t||t<0)throw new Error(a(o.INVALID_TYPE,[typeof t,"port"]));if("string"!=typeof s)throw new Error(a(o.INVALID_TYPE,[typeof s,"path"]));var h=-1!==e.indexOf(":")&&"["!==e.slice(0,1)&&"]"!==e.slice(-1);r="ws://"+(h?"["+e+"]":e)+":"+t+s}for(var u=0,l=0;l<i.length;l++){var d=i.charCodeAt(l);55296<=d&&d<=56319&&l++,u++}if("string"!=typeof i||u>65535)throw new Error(a(o.INVALID_ARGUMENT,[i,"clientId"]));var p=new v(r,e,t,s,i);Object.defineProperties(this,{host:{get:function(){return e},set:function(){throw new Error(a(o.UNSUPPORTED_OPERATION))}},port:{get:function(){return t},set:function(){throw new Error(a(o.UNSUPPORTED_OPERATION))}},path:{get:function(){return s},set:function(){throw new Error(a(o.UNSUPPORTED_OPERATION))}},uri:{get:function(){return r},set:function(){throw new Error(a(o.UNSUPPORTED_OPERATION))}},clientId:{get:function(){return p.clientId},set:function(){throw new Error(a(o.UNSUPPORTED_OPERATION))}},onConnected:{get:function(){return p.onConnected},set:function(e){if("function"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"onConnected"]));p.onConnected=e}},disconnectedPublishing:{get:function(){return p.disconnectedPublishing},set:function(e){p.disconnectedPublishing=e}},disconnectedBufferSize:{get:function(){return p.disconnectedBufferSize},set:function(e){p.disconnectedBufferSize=e}},onConnectionLost:{get:function(){return p.onConnectionLost},set:function(e){if("function"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"onConnectionLost"]));p.onConnectionLost=e}},onMessageDelivered:{get:function(){return p.onMessageDelivered},set:function(e){if("function"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"onMessageDelivered"]));p.onMessageDelivered=e}},onMessageArrived:{get:function(){return p.onMessageArrived},set:function(e){if("function"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"onMessageArrived"]));p.onMessageArrived=e}},trace:{get:function(){return p.traceFunction},set:function(e){if("function"!=typeof e)throw new Error(a(o.INVALID_TYPE,[typeof e,"onTrace"]));p.traceFunction=e}}}),this.connect=function(e){if(n(e=e||{},{timeout:"number",userName:"string",password:"string",willMessage:"object",keepAliveInterval:"number",cleanSession:"boolean",useSSL:"boolean",invocationContext:"object",onSuccess:"function",onFailure:"function",hosts:"object",ports:"object",reconnect:"boolean",mqttVersion:"number",mqttVersionExplicit:"boolean",uris:"object"}),void 0===e.keepAliveInterval&&(e.keepAliveInterval=60),e.mqttVersion>4||e.mqttVersion<3)throw new Error(a(o.INVALID_ARGUMENT,[e.mqttVersion,"connectOptions.mqttVersion"]));if(void 0===e.mqttVersion?(e.mqttVersionExplicit=!1,e.mqttVersion=4):e.mqttVersionExplicit=!0,void 0!==e.password&&void 0===e.userName)throw new Error(a(o.INVALID_ARGUMENT,[e.password,"connectOptions.password"]));if(e.willMessage){if(!(e.willMessage instanceof w))throw new Error(a(o.INVALID_TYPE,[e.willMessage,"connectOptions.willMessage"]));if(e.willMessage.stringPayload=null,void 0===e.willMessage.destinationName)throw new Error(a(o.INVALID_TYPE,[typeof e.willMessage.destinationName,"connectOptions.willMessage.destinationName"]))}if(void 0===e.cleanSession&&(e.cleanSession=!0),e.hosts){if(!(e.hosts instanceof Array))throw new Error(a(o.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));if(e.hosts.length<1)throw new Error(a(o.INVALID_ARGUMENT,[e.hosts,"connectOptions.hosts"]));for(var t=!1,i=0;i<e.hosts.length;i++){if("string"!=typeof e.hosts[i])throw new Error(a(o.INVALID_TYPE,[typeof e.hosts[i],"connectOptions.hosts["+i+"]"]));if(/^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test(e.hosts[i])){if(0===i)t=!0;else if(!t)throw new Error(a(o.INVALID_ARGUMENT,[e.hosts[i],"connectOptions.hosts["+i+"]"]))}else if(t)throw new Error(a(o.INVALID_ARGUMENT,[e.hosts[i],"connectOptions.hosts["+i+"]"]))}if(t)e.uris=e.hosts;else{if(!e.ports)throw new Error(a(o.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));if(!(e.ports instanceof Array))throw new Error(a(o.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));if(e.hosts.length!==e.ports.length)throw new Error(a(o.INVALID_ARGUMENT,[e.ports,"connectOptions.ports"]));for(e.uris=[],i=0;i<e.hosts.length;i++){if("number"!=typeof e.ports[i]||e.ports[i]<0)throw new Error(a(o.INVALID_TYPE,[typeof e.ports[i],"connectOptions.ports["+i+"]"]));var c=e.hosts[i],h=e.ports[i],u=-1!==c.indexOf(":");r="ws://"+(u?"["+c+"]":c)+":"+h+s,e.uris.push(r)}}}p.connect(e)},this.subscribe=function(e,t){if("string"!=typeof e&&e.constructor!==Array)throw new Error("Invalid argument:"+e);if(n(t=t||{},{qos:"number",invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"}),t.timeout&&!t.onFailure)throw new Error("subscribeOptions.timeout specified with no onFailure callback.");if(void 0!==t.qos&&0!==t.qos&&1!==t.qos&&2!==t.qos)throw new Error(a(o.INVALID_ARGUMENT,[t.qos,"subscribeOptions.qos"]));p.subscribe(e,t)},this.unsubscribe=function(e,t){if("string"!=typeof e&&e.constructor!==Array)throw new Error("Invalid argument:"+e);if(n(t=t||{},{invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"}),t.timeout&&!t.onFailure)throw new Error("unsubscribeOptions.timeout specified with no onFailure callback.");p.unsubscribe(e,t)},this.send=function(e,t,s,n){var i;if(0===arguments.length)throw new Error("Invalid argument.length");if(1==arguments.length){if(!(e instanceof w)&&"string"!=typeof e)throw new Error("Invalid argument:"+typeof e);if(void 0===(i=e).destinationName)throw new Error(a(o.INVALID_ARGUMENT,[i.destinationName,"Message.destinationName"]));p.send(i)}else(i=new w(t)).destinationName=e,arguments.length>=3&&(i.qos=s),arguments.length>=4&&(i.retained=n),p.send(i)},this.publish=function(e,t,s,n){var i;if(0===arguments.length)throw new Error("Invalid argument.length");if(1==arguments.length){if(!(e instanceof w)&&"string"!=typeof e)throw new Error("Invalid argument:"+typeof e);if(void 0===(i=e).destinationName)throw new Error(a(o.INVALID_ARGUMENT,[i.destinationName,"Message.destinationName"]));p.send(i)}else(i=new w(t)).destinationName=e,arguments.length>=3&&(i.qos=s),arguments.length>=4&&(i.retained=n),p.send(i)},this.disconnect=function(){p.disconnect()},this.getTraceLog=function(){return p.getTraceLog()},this.startTrace=function(){p.startTrace()},this.stopTrace=function(){p.stopTrace()},this.isConnected=function(){return p.connected}},Message:w}}(void 0!==s.g?s.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});return e},e.exports=n()},25:(e,t,s)=>{const n=s(361),i=s(78),o="/brokerStatus";e.exports=class{constructor(e){this.postMessage=e,this.state={paho:null,config:{},buffer:[],connected:!1,nextStatus:"virgin",lastStatus:"virgin",subscriptions:new Map,subStatus:new Map,localPubTopics:new Map,localSubTopics:new Map,retained:new Map},this.state.localPubTopics.set(o,!0),this.state.localSubTopics.set(o,!0),console.log("messaging hub: worker started")}onmessage(e){let t=e.data;switch(t._rmx_type){case"msg_hub_configure":this.on_msg_configure(t);break;case"msg_hub_newChannel":this.on_msg_newChannel(this,t);break;case"msg_hub_logStatus":this.logStatus();break;default:console.error("messaging hub: unknown message type: "+t._rmx_type)}}on_msg_configure(e){this.state.config.user=e.user,this.state.config.token=e.token;let t=e.wsURL,s=!1;if(void 0===t&&(t=e.baseURL,s=!0),!0===e.standalone)return console.log("messaging hub: standalone mode"),this.state.paho=null,void this.postMessage({error:null});let o=!1;t.startsWith("http://")?t="ws://"+t.substr(7):t.startsWith("https://")?(t="wss://"+t.substr(8),o=!0):t.startsWith("ws://")||t.startsWith("wss://")||console.error("messaging hub: bad baseURL: "+e.baseURL),s&&(t.endsWith("/")||(t+="/"),t+="x/broker.ws");let r=i.nanoid();console.log("messaging hub: connecting to broker at "+t),this.state.paho=new n.Client(t,r),this.state.paho.onMessageArrived=e=>{this.on_paho_messageArrived(e)};let a=!0;this.state.paho.onConnected=(e,t)=>{for(this.state.connected=!0,this.state.nextStatus=e?"reconnected":"connected",this.logStatus(),a&&this.postMessage({error:null}),a=!1;this.state.buffer.length>0;){let e=this.state.buffer.shift();try{e()}catch(e){console.error(e)}}this.state.subscriptions.forEach(((e,t)=>{this.broker_subscribe(t,void 0,void 0,!0)})),this.are_all_subscriptions_made()&&this.deliverStatus(this.state.nextStatus)},this.state.paho.onConnectionLost=e=>{console.error("messaging hub: connection lost, code "+e.errorCode+" "+e.errorMessage),this.state.connected=!1,this.state.nextStatus="disconnected",this.state.subStatus=new Map,this.deliverStatus("disconnected")};let c={userName:e.user,password:"Bearer "+e.token,useSSL:o,onFailure:(e,t,s)=>{this.state.connected=!1,console.error("messaging hub: connect failure, code "+t+" "+s),this.logStatus(),a&&this.postMessage({error:s}),a=!1},reconnect:!0,keepAliveInterval:15,mqttVersion:4};this.state.paho.connect(c)}logStatus(){console.info("messaging hub: "+(this.state.connected?"connected to ":"disconnected from ")+this.state.paho.host+":"+this.state.paho.port)}on_msg_newChannel(e){let t=new MessageChannel;t.port1.onmessage=e=>this.chan_onmessage(t.port1,e),this.postMessage({error:null,port:t.port2,reqId:e.reqId},[t.port2])}chan_onmessage(e,t){let s=t.data;switch(s._rmx_type){case"msg_hub_publish":this.on_chan_publish(e,s);break;case"msg_hub_get":this.on_chan_get(e,s);break;case"msg_hub_subscribe":this.on_chan_subscribe(e,s);break;case"msg_hub_unsubscribe":this.on_chan_unsubscribe(e,s);break;case"msg_hub_setLocalPubTopic":this.on_chan_setLocalPubTopic(e,s);break;case"msg_hub_setLocalSubTopic":this.on_chan_setLocalSubTopic(e,s);break;case"msg_hub_newChannel":this.on_msg_newChannel(e,s);break;default:console.error("messaging hub: unknown message type: "+s._rmx_type)}}on_chan_setLocalPubTopic(e,t){this.state.localPubTopics.set(t.topic,!0);let s={error:null,reqId:t.reqId};e.postMessage(s)}on_chan_setLocalSubTopic(e,t){this.state.localSubTopics.set(t.topic,!0);let s={error:null,reqId:t.reqId};e.postMessage(s)}isLocalPubTopic(e){let t=e.split("/");for(let e=t.length;e>=2;e--){let s=t.slice(0,e).join("/");if(this.state.localPubTopics.has(s))return!0}return!!this.state.localPubTopics.has("/")}isLocalSubTopic(e){let t=e.split("/");for(let e=t.length;e>=2;e--){let s=t.slice(0,e).join("/");if(this.state.localSubTopics.has(s))return!0}return!!this.state.localSubTopics.has("/")}when_connected(e){this.state.connected?e():this.state.buffer.push(e)}on_chan_publish(e,t){if(t.topic==o){let s={error:"cannot publish on restricted topic",reqId:t.reqId};return void e.postMessage(s)}if(t.retained&&this.state.retained.set(t.topic,t),this.deliver(t),null===this.state.paho||t.localOnly||this.isLocalPubTopic(t.topic)){let s={error:null,reqId:t.reqId};return void e.postMessage(s)}let s,n="_rmx_type="+t.header._rmx_type+",_rmx_encoding="+t.header._rmx_encoding+",_rmx_sender="+t.header._rmx_sender+",_rmx_route="+this.state.paho.clientId+"\n",i=(new TextEncoder).encode(n);switch(t.header._rmx_encoding){case"text":s=(new TextEncoder).encode(t.payload);break;case"json":JSON.stringify(t.payload),s=(new TextEncoder).encode(t.payload);break;case"binary":s=new Uint8Array(t.payload);break;default:console.error("bad encoding: "+t.header._rmx_encoding)}let r=new Uint8Array(i.length+s.length);r.set(i,0),r.set(s,i.length),this.when_connected((()=>{this.state.paho.publish(t.topic,r.buffer,0,t.retained)}));let a={error:null,reqId:t.reqId};e.postMessage(a)}on_chan_get(e,t){let s=this.state.retained.get(t.topic),n={error:null,reqId:t.reqId,payload:s};e.postMessage(n)}are_all_subscriptions_made(){let e=!0;return this.state.subscriptions.forEach(((t,s)=>{this.isLocalSubTopic(s)||this.state.subStatus.get(s)||(e=!1)})),e}broker_subscribe(e,t,s,n){if(!this.state.connected)return;if(this.state.subStatus.has(e))return;if(this.isLocalSubTopic(e))return;this.state.subStatus.set(e,!1);let i={qos:0,onSuccess:n=>{if(console.log("messaging hub: subscribed to "+e),this.state.subStatus.set(e,!0),void 0!==t&&void 0!==s){let e={error:null,reqId:s};t.postMessage(e)}this.are_all_subscriptions_made()&&this.deliverStatus(this.state.nextStatus)},onFailure:(i,o,r)=>{let a="subscription to "+e+" failed - code: "+o+" - text: "+r;if(console.error("messaging hub: "+a),void 0!==t&&void 0!==s){let e={error:a,reqId:s};t.postMessage(e)}n&&setTimeout((i=>{this.broker_subscribe(e,t,s,n)}),1e3)}};this.state.paho.subscribe(e,i)}on_chan_subscribe(e,t){let s={port:e,subId:t.subId};if(this.state.subscriptions.has(t.topic))return this.state.subscriptions.get(t.topic).push(s),e.postMessage({error:null,reqId:t.reqId}),void(this.state.retained.has(t.topic)&&this.deliver(this.state.retained.get(t.topic)));let n=new Array;if(n.push(s),this.state.subscriptions.set(t.topic,n),null===this.state.paho||this.isLocalSubTopic(t.topic)){let s={error:null,reqId:t.reqId};return e.postMessage(s),this.state.retained.has(t.topic)&&this.deliver(this.state.retained.get(t.topic)),void console.log("messaging hub: locally subscribed to "+t.topic)}this.when_connected((()=>{this.broker_subscribe(t.topic,e,t.reqId,!1)}))}on_chan_unsubscribe(e,t){if(!this.state.subscriptions.has(t.topic)){let s={error:null,reqId:t.reqId};return void e.postMessage(s)}let s=this.state.subscriptions.get(t.topic).filter((e=>e.subId!=t.subId));if(s.length>0){this.state.subscriptions.set(t.topic,s);let n={error:null,reqId:t.reqId};e.postMessage(n)}else if(this.state.subscriptions.delete(t.topic),null===this.state.paho||this.isLocalSubTopic(t.topic)||!this.state.connected){console.log("messaging hub: locally unsubscribed from "+t.topic);let s={error:null,reqId:t.reqId};e.postMessage(s)}else{let s={onSuccess:s=>{console.log("messaging hub: unsubscribed from "+t.topic);let n={error:null,reqId:t.reqId};e.postMessage(n)},onFailure:(s,n,i)=>{let o="unsubscribe from "+t.topic+" failed - code: "+n+" - text: "+i;console.error("messaging hub: "+o);let r={error:o,reqId:t.reqId};e.postMessage(r)}};this.state.paho.unsubscribe(t.topic,s)}let n={header:{_rmx_type:"",_rmx_encoding:"",_rmx_sender:""},eof:!0,payload:null,reqId:t.subId};e.postMessage(n)}on_paho_messageArrived(e){let t=new Uint8Array(e.payloadBytes),s=t.indexOf(10);if(s<0)return void console.error("messaging hub: Got undecodable MQTT message");let n,i=(new TextDecoder).decode(t.subarray(0,s)).split(","),o={};for(let e of i){let t=e.split("=",2);if(!(t.length<2))switch(t[0]){case"_rmx_type":o._rmx_type=t[1];break;case"_rmx_encoding":o._rmx_encoding=t[1];break;case"_rmx_sender":o._rmx_sender=t[1];break;case"_rmx_route":if(t[1].split(";").includes(this.state.paho.clientId))return void console.log("messaging hub: dropping duplicate message")}}switch(o._rmx_encoding){case"text":case"json":n=(new TextDecoder).decode(t.subarray(s+1));break;case"binary":n=t.slice(s+1);break;default:console.log("messaging hub: dropping message with bad _rmx_encoding")}let r={header:o,payload:n,topic:e.destinationName,retained:e.retained};r.retained&&this.state.retained.set(r.topic,r),this.deliver(r)}deliver(e){if(this.state.subscriptions.has(e.topic)){let t=this.state.subscriptions.get(e.topic),s=Object.fromEntries(Object.entries(e));for(let e of t)try{s.reqId=e.subId,e.port.postMessage(s)}catch(e){}}}deliverStatus(e){if(e==this.state.lastStatus)return;this.state.lastStatus=e;let t=o,s={_rmx_type:"msg_hub_publish",header:{_rmx_type:"msg_hub_status",_rmx_encoding:"json",_rmx_sender:"hub-worker"},topic:t,payload:JSON.stringify(e),retained:!0,localOnly:!0};this.state.retained.set(t,s),console.debug("messaging hub: "+o+" = "+e),this.deliver(s)}}},78:(e,t,s)=>{"use strict";s.r(t),s.d(t,{customAlphabet:()=>r,customRandom:()=>o,nanoid:()=>a,random:()=>i,urlAlphabet:()=>n});let n="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",i=e=>crypto.getRandomValues(new Uint8Array(e)),o=(e,t,s)=>{let n=(2<<Math.log(e.length-1)/Math.LN2)-1,i=-~(1.6*n*t/e.length);return(o=t)=>{let r="";for(;;){let t=s(i),a=i;for(;a--;)if(r+=e[t[a]&n]||"",r.length===o)return r}}},r=(e,t=21)=>o(e,t,i),a=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_")),"")}},t={};function s(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,s),o.exports}s.d=(e,t)=>{for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";const e=new(s(25))(postMessage);onmessage=e.onmessage.bind(e)})()})();