summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor/src/components/messages/parsers
diff options
context:
space:
mode:
Diffstat (limited to 'devtools/client/netmonitor/src/components/messages/parsers')
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/moz.build11
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js82
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js120
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js13
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build12
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js48
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js84
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js292
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js56
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build7
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js204
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js230
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js274
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build8
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js73
23 files changed, 1730 insertions, 0 deletions
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
new file mode 100644
index 0000000000..6b1947e4a1
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
@@ -0,0 +1,11 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += [
+ "socket-io",
+ "sockjs",
+ "stomp",
+ "signalr",
+ "wamp",
+]
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
new file mode 100644
index 0000000000..c1c64d6717
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
@@ -0,0 +1,82 @@
+/*
+ * A helper class for working with SignalR handshakes.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+const Utils = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js");
+/** @private */
+class HandshakeProtocol {
+ // Handshake request is always JSON
+ writeHandshakeRequest(handshakeRequest) {
+ return TextMessageFormat.TextMessageFormat.write(
+ JSON.stringify(handshakeRequest)
+ );
+ }
+ parseHandshakeResponse(data) {
+ let messageData;
+ let remainingData;
+ if (
+ Utils.isArrayBuffer(data) ||
+ // eslint-disable-next-line no-undef
+ (typeof Buffer !== "undefined" && data instanceof Buffer)
+ ) {
+ // Format is binary but still need to read JSON text from handshake response
+ const binaryData = new Uint8Array(data);
+ const separatorIndex = binaryData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparatorCode
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = String.fromCharCode.apply(
+ null,
+ binaryData.slice(0, responseLength)
+ );
+ remainingData =
+ binaryData.byteLength > responseLength
+ ? binaryData.slice(responseLength).buffer
+ : null;
+ } else {
+ const textData = data;
+ const separatorIndex = textData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparator
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = textData.substring(0, responseLength);
+ remainingData =
+ textData.length > responseLength
+ ? textData.substring(responseLength)
+ : null;
+ }
+ // At this point we should have just the single handshake message
+ const messages = TextMessageFormat.TextMessageFormat.parse(messageData);
+ const response = JSON.parse(messages[0]);
+ if (response.type) {
+ throw new Error("Expected a handshake response from the server.");
+ }
+ const responseMessage = response;
+ // multiple messages could have arrived with handshake
+ // return additional data to be parsed as usual, or null if all parsed
+ return [remainingData, responseMessage];
+ }
+}
+exports.HandshakeProtocol = HandshakeProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
new file mode 100644
index 0000000000..fec2cdbff4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
@@ -0,0 +1,33 @@
+/*
+ * A protocol abstraction for communicating with SignalR hubs.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+/** Defines the type of a Hub Message. */
+var MessageType;
+(function (_MessageType) {
+ /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
+ MessageType[(MessageType.Invocation = 1)] = "Invocation";
+ /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
+ MessageType[(MessageType.StreamItem = 2)] = "StreamItem";
+ /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
+ MessageType[(MessageType.Completion = 3)] = "Completion";
+ /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
+ MessageType[(MessageType.StreamInvocation = 4)] = "StreamInvocation";
+ /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
+ MessageType[(MessageType.CancelInvocation = 5)] = "CancelInvocation";
+ /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
+ MessageType[(MessageType.Ping = 6)] = "Ping";
+ /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
+ MessageType[(MessageType.Close = 7)] = "Close";
+})((MessageType = exports.MessageType || (exports.MessageType = {})));
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
new file mode 100644
index 0000000000..c3648e940f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
@@ -0,0 +1,120 @@
+/*
+ * Implements the SignalR Hub Protocol.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const IHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js");
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+/** Implements the JSON Hub Protocol. */
+class JsonHubProtocol {
+ /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
+ *
+ * @param {string} input A string containing the serialized representation.
+ */
+ parseMessages(input) {
+ // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
+ if (typeof input !== "string") {
+ throw new Error(
+ "Invalid input for JSON hub protocol. Expected a string."
+ );
+ }
+ if (!input) {
+ return [];
+ }
+ // Parse the messages
+ const messages = TextMessageFormat.TextMessageFormat.parse(input);
+ const hubMessages = [];
+ for (const message of messages) {
+ const parsedMessage = JSON.parse(message);
+ if (typeof parsedMessage.type !== "number") {
+ throw new Error("Invalid payload.");
+ }
+ switch (parsedMessage.type) {
+ case IHubProtocol.MessageType.Invocation:
+ this.isInvocationMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.StreamItem:
+ this.isStreamItemMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Completion:
+ this.isCompletionMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Ping:
+ // Single value, no need to validate
+ break;
+ case IHubProtocol.MessageType.Close:
+ // All optional values, no need to validate
+ break;
+ default:
+ // Future protocol changes can add message types, new kinds of messages
+ // will show up without having to update Firefox.
+ break;
+ }
+ // Map numeric message type to their textual name if it exists
+ parsedMessage.type =
+ IHubProtocol.MessageType[parsedMessage.type] || parsedMessage.type;
+ hubMessages.push(parsedMessage);
+ }
+ return hubMessages;
+ }
+ /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
+ *
+ * @param {HubMessage} message The message to write.
+ * @returns {string} A string containing the serialized representation of the message.
+ */
+ writeMessage(message) {
+ return TextMessageFormat.TextMessageFormat.write(JSON.stringify(message));
+ }
+ isInvocationMessage(message) {
+ this.assertNotEmptyString(
+ message.target,
+ "Invalid payload for Invocation message."
+ );
+ if (message.invocationId !== undefined) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Invocation message."
+ );
+ }
+ }
+ isStreamItemMessage(message) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for StreamItem message."
+ );
+ if (message.item === undefined) {
+ throw new Error("Invalid payload for StreamItem message.");
+ }
+ }
+ isCompletionMessage(message) {
+ if (message.result && message.error) {
+ throw new Error("Invalid payload for Completion message.");
+ }
+ if (!message.result && message.error) {
+ this.assertNotEmptyString(
+ message.error,
+ "Invalid payload for Completion message."
+ );
+ }
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Completion message."
+ );
+ }
+ assertNotEmptyString(value, errorMessage) {
+ if (typeof value !== "string" || value === "") {
+ throw new Error(errorMessage);
+ }
+ }
+}
+exports.JsonHubProtocol = JsonHubProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
new file mode 100644
index 0000000000..a9ec58ee36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Not exported from index
+/** @private */
+class TextMessageFormat {
+ static write(output) {
+ return `${output}${TextMessageFormat.RecordSeparator}`;
+ }
+ static parse(input) {
+ if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
+ throw new Error("Message is incomplete.");
+ }
+ const messages = input.split(TextMessageFormat.RecordSeparator);
+ messages.pop();
+ return messages;
+ }
+}
+exports.TextMessageFormat = TextMessageFormat;
+TextMessageFormat.RecordSeparatorCode = 0x1e;
+TextMessageFormat.RecordSeparator = String.fromCharCode(
+ TextMessageFormat.RecordSeparatorCode
+);
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
new file mode 100644
index 0000000000..77b00daf45
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Also in signalr-protocol-msgpack/Utils.ts
+/** @private */
+function isArrayBuffer(val) {
+ return (
+ val &&
+ typeof ArrayBuffer !== "undefined" &&
+ (val instanceof ArrayBuffer ||
+ // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
+ (val.constructor && val.constructor.name === "ArrayBuffer"))
+ );
+}
+exports.isArrayBuffer = isArrayBuffer;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
new file mode 100644
index 0000000000..927b0a0922
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
@@ -0,0 +1,13 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const JsonHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js");
+const HandshakeProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js");
+
+module.exports = {
+ JsonHubProtocol: JsonHubProtocol.JsonHubProtocol,
+ HandshakeProtocol: HandshakeProtocol.HandshakeProtocol,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
new file mode 100644
index 0000000000..48329513f2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
@@ -0,0 +1,12 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "HandshakeProtocol.js",
+ "IHubProtocol.js",
+ "index.js",
+ "JSONHubProtocol.js",
+ "TextMessageFormat.js",
+ "Utils.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
new file mode 100644
index 0000000000..340791199f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
@@ -0,0 +1,48 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+"use strict";
+
+/**
+ * Reconstructs a binary packet from its placeholder packet and buffers
+ *
+ * @param {Object} packet - event packet with placeholders
+ * @param {Array} buffers - binary buffers to put in placeholder positions
+ * @return {Object} reconstructed packet
+ * @api public
+ */
+
+exports.reconstructPacket = function (packet, buffers) {
+ packet.data = _reconstructPacket(packet.data, buffers);
+ packet.attachments = undefined; // no longer useful
+ return packet;
+};
+
+function _reconstructPacket(data, buffers) {
+ if (!data) {
+ return data;
+ }
+
+ if (data && data._placeholder) {
+ return buffers[data.num]; // appropriate buffer (should be natural order anyway)
+ } else if (Array.isArray(data)) {
+ for (let i = 0; i < data.length; i++) {
+ data[i] = _reconstructPacket(data[i], buffers);
+ }
+ } else if (typeof data === "object") {
+ for (const key in data) {
+ data[key] = _reconstructPacket(data[key], buffers);
+ }
+ }
+
+ return data;
+}
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
new file mode 100644
index 0000000000..5874778f75
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
@@ -0,0 +1,84 @@
+/*
+ * Event emitter component.
+ *
+ * Copyright (c) 2014 Component contributors <dev@component.io>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/component/emitter
+ */
+
+"use strict";
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) {
+ return mixin(obj);
+ }
+}
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (const key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on = function (event, fn) {
+ this._callbacks = this._callbacks || {};
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function (event) {
+ this._callbacks = this._callbacks || {};
+
+ const args = new Array(arguments.length - 1);
+ let callbacks = this._callbacks["$" + event];
+
+ for (let i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (let i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+module.exports = Emitter;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
new file mode 100644
index 0000000000..9d631d014b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
@@ -0,0 +1,292 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-unused-vars */
+
+"use strict";
+
+const Emitter = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js");
+const binary = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js");
+const isBuf = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js");
+
+/**
+ * Packet types
+ */
+
+const TYPES = [
+ "CONNECT",
+ "DISCONNECT",
+ "EVENT",
+ "ACK",
+ "ERROR",
+ "BINARY_EVENT",
+ "BINARY_ACK",
+];
+
+/**
+ * Packet type `connect`
+ */
+
+const CONNECT = 0;
+
+/**
+ * Packet type `disconnect`
+ */
+
+const DISCONNECT = 1;
+
+/**
+ * Packet type `event`
+ */
+
+const EVENT = 2;
+
+/**
+ * Packet type `ack`
+ */
+
+const ACK = 3;
+
+/**
+ * Packet type `error`
+ */
+
+const ERROR = 4;
+
+/**
+ * Packet type 'binary event'
+ */
+const BINARY_EVENT = 5;
+
+/**
+ * Packet type `binary ack`. For acks with binary arguments
+ */
+
+const BINARY_ACK = 6;
+
+/**
+ * A socket.io Decoder instance
+ *
+ * @return {Object} decoder
+ * @api public
+ */
+
+function Decoder() {
+ this.reconstructor = null;
+}
+
+/**
+ * Mix in `Emitter` with Decoder.
+ */
+
+Emitter(Decoder.prototype);
+
+/**
+ * A manager of a binary event's 'buffer sequence'. Should
+ * be constructed whenever a packet of type BINARY_EVENT is
+ * decoded.
+ *
+ * @param {Object} packet
+ * @return {BinaryReconstructor} initialized reconstructor
+ * @api private
+ */
+
+function BinaryReconstructor(packet) {
+ this.reconPack = packet;
+ this.buffers = [];
+}
+
+/**
+ * Method to be called when binary data received from connection
+ * after a BINARY_EVENT packet.
+ *
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
+ * @return {null | Object} returns null if more binary data is expected or
+ * a reconstructed packet object if all buffers have been received.
+ * @api private
+ */
+
+BinaryReconstructor.prototype.takeBinaryData = function (binData) {
+ this.buffers.push(binData);
+ if (this.buffers.length === this.reconPack.attachments) {
+ // done with buffer list
+ const packet = binary.reconstructPacket(this.reconPack, this.buffers);
+ this.finishedReconstruction();
+ return packet;
+ }
+ return null;
+};
+
+/**
+ * Cleans up binary packet reconstruction variables.
+ *
+ * @api private
+ */
+
+BinaryReconstructor.prototype.finishedReconstruction = function () {
+ this.reconPack = null;
+ this.buffers = [];
+};
+
+/**
+ * Decodes an encoded packet string into packet JSON.
+ *
+ * @param {String} obj - encoded packet
+ * @return {Object} packet
+ * @api public
+ */
+
+Decoder.prototype.add = function (obj) {
+ let packet;
+ if (typeof obj === "string") {
+ packet = decodeString(obj);
+ if (BINARY_EVENT === packet.type || BINARY_ACK === packet.type) {
+ // binary packet's json
+ this.reconstructor = new BinaryReconstructor(packet);
+
+ // no attachments, labeled binary but no binary data to follow
+ if (this.reconstructor.reconPack.attachments === 0) {
+ this.emit("decoded", packet);
+ }
+ } else {
+ // non-binary full packet
+ this.emit("decoded", packet);
+ }
+ } else if (isBuf(obj) || obj.base64) {
+ // raw binary data
+ if (!this.reconstructor) {
+ throw new Error("got binary data when not reconstructing a packet");
+ } else {
+ packet = this.reconstructor.takeBinaryData(obj);
+ if (packet) {
+ // received final buffer
+ this.reconstructor = null;
+ this.emit("decoded", packet);
+ }
+ }
+ } else {
+ throw new Error("Unknown type: " + obj);
+ }
+};
+
+/**
+ * Decode a packet String (JSON data)
+ *
+ * @param {String} str
+ * @return {Object} packet
+ * @api private
+ */
+// eslint-disable-next-line complexity
+function decodeString(str) {
+ let i = 0;
+ // look up type
+ const p = {
+ type: Number(str.charAt(0)),
+ };
+
+ if (TYPES[p.type] == null) {
+ return error("unknown packet type " + p.type);
+ }
+
+ // look up attachments if type binary
+ if (BINARY_EVENT === p.type || BINARY_ACK === p.type) {
+ let buf = "";
+ while (str.charAt(++i) !== "-") {
+ buf += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
+ throw new Error("Illegal attachments");
+ }
+ p.attachments = Number(buf);
+ }
+
+ // look up namespace (if any)
+ if (str.charAt(i + 1) === "/") {
+ p.nsp = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c === ",") {
+ break;
+ }
+ p.nsp += c;
+ if (i === str.length) {
+ break;
+ }
+ }
+ } else {
+ p.nsp = "/";
+ }
+
+ // look up id
+ const next = str.charAt(i + 1);
+ if (next !== "" && Number(next) == next) {
+ p.id = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c == null || Number(c) != c) {
+ --i;
+ break;
+ }
+ p.id += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ p.id = Number(p.id);
+ }
+
+ // look up json data
+ if (str.charAt(++i)) {
+ const payload = tryParse(str.substr(i));
+ const isPayloadValid =
+ payload !== false && (p.type === ERROR || Array.isArray(payload));
+ if (isPayloadValid) {
+ p.data = payload;
+ } else {
+ return error("invalid payload");
+ }
+ }
+
+ return p;
+}
+
+function tryParse(str) {
+ try {
+ return JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+}
+
+/**
+ * Deallocates a parser's resources
+ *
+ * @api public
+ */
+
+Decoder.prototype.destroy = function () {
+ if (this.reconstructor) {
+ this.reconstructor.finishedReconstruction();
+ }
+};
+
+function error(msg) {
+ return {
+ type: ERROR,
+ data: "parser error: " + msg,
+ };
+}
+
+module.exports = Decoder;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
new file mode 100644
index 0000000000..cdbad14abc
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
@@ -0,0 +1,40 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-undef */
+
+"use strict";
+
+var withNativeBuffer =
+ typeof Buffer === "function" && typeof Buffer.isBuffer === "function";
+var withNativeArrayBuffer = typeof ArrayBuffer === "function";
+
+var isView = function (obj) {
+ return typeof ArrayBuffer.isView === "function"
+ ? ArrayBuffer.isView(obj)
+ : obj.buffer instanceof ArrayBuffer;
+};
+
+/**
+ * Returns true if obj is a buffer or an arraybuffer.
+ *
+ * @api private
+ */
+
+function isBuf(obj) {
+ return (
+ (withNativeBuffer && Buffer.isBuffer(obj)) ||
+ (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)))
+ );
+}
+
+module.exports = isBuf;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
new file mode 100644
index 0000000000..d38ca19dd6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
@@ -0,0 +1,10 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "binary.js",
+ "component-emitter.js",
+ "index.js",
+ "is-buffer.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
new file mode 100644
index 0000000000..b688b84b36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
@@ -0,0 +1,56 @@
+/*
+ * SockJS is a browser JavaScript library that provides a WebSocket-like object.
+ * SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency,
+ * full duplex, cross-domain communication channel between the browser and the web server.
+ *
+ * Copyright (c) 2011-2018 The sockjs-client Authors.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/sockjs/sockjs-client
+ */
+
+"use strict";
+
+function parseSockJS(msg) {
+ const type = msg.slice(0, 1);
+ const content = msg.slice(1);
+
+ // first check for messages that don't need a payload
+ switch (type) {
+ case "o":
+ return { type: "open" };
+ case "h":
+ return { type: "heartbeat" };
+ }
+
+ let payload;
+ if (content) {
+ try {
+ payload = JSON.parse(content);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ if (typeof payload === "undefined") {
+ return null;
+ }
+
+ switch (type) {
+ case "a":
+ return { type: "message", data: payload };
+ case "m":
+ return { type: "message", data: payload };
+ case "c":
+ const [code, message] = payload;
+ return { type: "close", code, message };
+ default:
+ return null;
+ }
+}
+
+module.exports = {
+ parseSockJS,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
new file mode 100644
index 0000000000..e1ca52aa96
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
@@ -0,0 +1,7 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "index.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
new file mode 100644
index 0000000000..a55d5bff7a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/byte.ts
+ */
+
+"use strict";
+
+const BYTE = {
+ // LINEFEED byte (octet 10)
+ LF: "\x0A",
+ // NULL byte (octet 0)
+ NULL: "\x00",
+};
+
+module.exports = { BYTE };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
new file mode 100644
index 0000000000..679b1140b4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/frame.ts
+ */
+
+"use strict";
+
+const {
+ BYTE,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js");
+
+/**
+ * Frame class represents a STOMP frame.
+ *
+ * @internal
+ */
+class FrameImpl {
+ /**
+ * Frame constructor. `command`, `headers` and `body` are available as properties.
+ *
+ * @internal
+ */
+ constructor(params) {
+ const {
+ command,
+ headers,
+ body,
+ binaryBody,
+ escapeHeaderValues,
+ skipContentLengthHeader,
+ } = params;
+ this.command = command;
+ this.headers = Object.assign({}, headers || {});
+ if (binaryBody) {
+ this._binaryBody = binaryBody;
+ this.isBinaryBody = true;
+ } else {
+ this._body = body || "";
+ this.isBinaryBody = false;
+ }
+ this.escapeHeaderValues = escapeHeaderValues || false;
+ this.skipContentLengthHeader = skipContentLengthHeader || false;
+ }
+ /**
+ * body of the frame
+ */
+ get body() {
+ if (!this._body && this.isBinaryBody) {
+ this._body = new TextDecoder().decode(this._binaryBody);
+ }
+ return this._body;
+ }
+ /**
+ * body as Uint8Array
+ */
+ get binaryBody() {
+ if (!this._binaryBody && !this.isBinaryBody) {
+ this._binaryBody = new TextEncoder().encode(this._body);
+ }
+ return this._binaryBody;
+ }
+ /**
+ * deserialize a STOMP Frame from raw data.
+ *
+ * @internal
+ */
+ static fromRawFrame(rawFrame, escapeHeaderValues) {
+ const headers = {};
+ const trim = str => str.replace(/^\s+|\s+$/g, "");
+ // In case of repeated headers, as per standards, first value need to be used
+ for (const header of rawFrame.headers.reverse()) {
+ const key = trim(header[0]);
+ let value = trim(header[1]);
+ if (
+ escapeHeaderValues &&
+ rawFrame.command !== "CONNECT" &&
+ rawFrame.command !== "CONNECTED"
+ ) {
+ value = FrameImpl.hdrValueUnEscape(value);
+ }
+ headers[key] = value;
+ }
+ return new FrameImpl({
+ command: rawFrame.command,
+ headers,
+ binaryBody: rawFrame.binaryBody,
+ escapeHeaderValues,
+ });
+ }
+ /**
+ * @internal
+ */
+ toString() {
+ return this.serializeCmdAndHeaders();
+ }
+ /**
+ * serialize this Frame in a format suitable to be passed to WebSocket.
+ * If the body is string the output will be string.
+ * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer.
+ *
+ * @internal
+ */
+ serialize() {
+ const cmdAndHeaders = this.serializeCmdAndHeaders();
+ if (this.isBinaryBody) {
+ return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer;
+ }
+ return cmdAndHeaders + this._body + BYTE.NULL;
+ }
+ serializeCmdAndHeaders() {
+ const lines = [this.command];
+ if (this.skipContentLengthHeader) {
+ delete this.headers["content-length"];
+ }
+ for (const name of Object.keys(this.headers || {})) {
+ const value = this.headers[name];
+ if (
+ this.escapeHeaderValues &&
+ this.command !== "CONNECT" &&
+ this.command !== "CONNECTED"
+ ) {
+ lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`);
+ } else {
+ lines.push(`${name}:${value}`);
+ }
+ }
+ if (
+ this.isBinaryBody ||
+ (!this.isBodyEmpty() && !this.skipContentLengthHeader)
+ ) {
+ lines.push(`content-length:${this.bodyLength()}`);
+ }
+ return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF;
+ }
+ isBodyEmpty() {
+ return this.bodyLength() === 0;
+ }
+ bodyLength() {
+ const binaryBody = this.binaryBody;
+ return binaryBody ? binaryBody.length : 0;
+ }
+ /**
+ * Compute the size of a UTF-8 string by counting its number of bytes
+ * (and not the number of characters composing the string)
+ */
+ static sizeOfUTF8(s) {
+ return s ? new TextEncoder().encode(s).length : 0;
+ }
+ static toUnit8Array(cmdAndHeaders, binaryBody) {
+ const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders);
+ const nullTerminator = new Uint8Array([0]);
+ const uint8Frame = new Uint8Array(
+ uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length
+ );
+ uint8Frame.set(uint8CmdAndHeaders);
+ uint8Frame.set(binaryBody, uint8CmdAndHeaders.length);
+ uint8Frame.set(
+ nullTerminator,
+ uint8CmdAndHeaders.length + binaryBody.length
+ );
+ return uint8Frame;
+ }
+ /**
+ * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker.
+ *
+ * @internal
+ */
+ static marshall(params) {
+ const frame = new FrameImpl(params);
+ return frame.serialize();
+ }
+ /**
+ * Escape header values
+ */
+ static hdrValueEscape(str) {
+ return str
+ .replace(/\\/g, "\\\\")
+ .replace(/\r/g, "\\r")
+ .replace(/\n/g, "\\n")
+ .replace(/:/g, "\\c");
+ }
+ /**
+ * UnEscape header values
+ */
+ static hdrValueUnEscape(str) {
+ return str
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\c/g, ":")
+ .replace(/\\\\/g, "\\");
+ }
+}
+
+module.exports = { Frame: FrameImpl };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
new file mode 100644
index 0000000000..d5d441c543
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
@@ -0,0 +1,40 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const frameModule = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js");
+const {
+ Parser,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js");
+const {
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { Frame } = frameModule;
+
+function parseStompJs(message) {
+ let output;
+
+ function onFrame(rawFrame) {
+ const frame = Frame.fromRawFrame(rawFrame);
+ const { error, json } = parseJSON(frame.body);
+
+ output = {
+ command: frame.command,
+ headers: frame.headers,
+ body: error ? frame.body : json,
+ };
+ }
+ const onIncomingPing = () => {};
+ const parser = new Parser(onFrame, onIncomingPing);
+
+ parser.parseChunk(message);
+
+ return output;
+}
+
+module.exports = {
+ parseStompJs,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
new file mode 100644
index 0000000000..420c7479db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
@@ -0,0 +1,10 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "byte.js",
+ "frame.js",
+ "index.js",
+ "parser.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
new file mode 100644
index 0000000000..a7116627d3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/parser.ts
+ */
+
+"use strict";
+
+/**
+ * @internal
+ */
+const NULL = 0;
+/**
+ * @internal
+ */
+const LF = 10;
+/**
+ * @internal
+ */
+const CR = 13;
+/**
+ * @internal
+ */
+const COLON = 58;
+/**
+ * This is an evented, rec descent parser.
+ * A stream of Octets can be passed and whenever it recognizes
+ * a complete Frame or an incoming ping it will invoke the registered callbacks.
+ *
+ * All incoming Octets are fed into _onByte function.
+ * Depending on current state the _onByte function keeps changing.
+ * Depending on the state it keeps accumulating into _token and _results.
+ * State is indicated by current value of _onByte, all states are named as _collect.
+ *
+ * STOMP standards https://stomp.github.io/stomp-specification-1.2.html
+ * imply that all lengths are considered in bytes (instead of string lengths).
+ * So, before actual parsing, if the incoming data is String it is converted to Octets.
+ * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body.
+ *
+ * There is no peek function on the incoming data.
+ * When a state change occurs based on an Octet without consuming the Octet,
+ * the Octet, after state change, is fed again (_reinjectByte).
+ * This became possible as the state change can be determined by inspecting just one Octet.
+ *
+ * There are two modes to collect the body, if content-length header is there then it by counting Octets
+ * otherwise it is determined by NULL terminator.
+ *
+ * Following the standards, the command and headers are converted to Strings
+ * and the body is returned as Octets.
+ * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header.
+ *
+ * This parser does not use Regular Expressions as that can only operate on Strings.
+ *
+ * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or
+ * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk
+ * is pushed.
+ *
+ * Typically the higher level function will convert headers to Hash, handle unescaping of header values
+ * (which is protocol version specific), and convert body to text.
+ *
+ * Check the parser.spec.js to understand cases that this parser is supposed to handle.
+ *
+ * Part of `@stomp/stompjs`.
+ *
+ * @internal
+ */
+class Parser {
+ constructor(onFrame, onIncomingPing) {
+ this.onFrame = onFrame;
+ this.onIncomingPing = onIncomingPing;
+ this._encoder = new TextEncoder();
+ this._decoder = new TextDecoder();
+ this._token = [];
+ this._initState();
+ }
+ parseChunk(segment, appendMissingNULLonIncoming = false) {
+ let chunk;
+ if (segment instanceof ArrayBuffer) {
+ chunk = new Uint8Array(segment);
+ } else {
+ chunk = this._encoder.encode(segment);
+ }
+ // See https://github.com/stomp-js/stompjs/issues/89
+ // Remove when underlying issue is fixed.
+ //
+ // Send a NULL byte, if the last byte of a Text frame was not NULL.F
+ if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) {
+ const chunkWithNull = new Uint8Array(chunk.length + 1);
+ chunkWithNull.set(chunk, 0);
+ chunkWithNull[chunk.length] = 0;
+ chunk = chunkWithNull;
+ }
+ // tslint:disable-next-line:prefer-for-of
+ for (let i = 0; i < chunk.length; i++) {
+ const byte = chunk[i];
+ this._onByte(byte);
+ }
+ }
+ // The following implements a simple Rec Descent Parser.
+ // The grammar is simple and just one byte tells what should be the next state
+ _collectFrame(byte) {
+ if (byte === NULL) {
+ // Ignore
+ return;
+ }
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ // Incoming Ping
+ this.onIncomingPing();
+ return;
+ }
+ this._onByte = this._collectCommand;
+ this._reinjectByte(byte);
+ }
+ _collectCommand(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.command = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaders(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._setupCollectBody();
+ return;
+ }
+ this._onByte = this._collectHeaderKey;
+ this._reinjectByte(byte);
+ }
+ _reinjectByte(byte) {
+ this._onByte(byte);
+ }
+ _collectHeaderKey(byte) {
+ if (byte === COLON) {
+ this._headerKey = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaderValue;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaderValue(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.headers.push([this._headerKey, this._consumeTokenAsUTF8()]);
+ this._headerKey = undefined;
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _setupCollectBody() {
+ const contentLengthHeader = this._results.headers.filter(header => {
+ return header[0] === "content-length";
+ })[0];
+ if (contentLengthHeader) {
+ this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10);
+ this._onByte = this._collectBodyFixedSize;
+ } else {
+ this._onByte = this._collectBodyNullTerminated;
+ }
+ }
+ _collectBodyNullTerminated(byte) {
+ if (byte === NULL) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectBodyFixedSize(byte) {
+ // It is post decrement, so that we discard the trailing NULL octet
+ if (this._bodyBytesRemaining-- === 0) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _retrievedBody() {
+ this._results.binaryBody = this._consumeTokenAsRaw();
+ this.onFrame(this._results);
+ this._initState();
+ }
+ // Rec Descent Parser helpers
+ _consumeByte(byte) {
+ this._token.push(byte);
+ }
+ _consumeTokenAsUTF8() {
+ return this._decoder.decode(this._consumeTokenAsRaw());
+ }
+ _consumeTokenAsRaw() {
+ const rawResult = new Uint8Array(this._token);
+ this._token = [];
+ return rawResult;
+ }
+ _initState() {
+ this._results = {
+ command: undefined,
+ headers: [],
+ binaryBody: undefined,
+ };
+ this._token = [];
+ this._headerKey = undefined;
+ this._onByte = this._collectFrame;
+ }
+}
+
+module.exports = { Parser };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
new file mode 100644
index 0000000000..de73a7986c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
@@ -0,0 +1,274 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// An implementation for WAMP messages parsing https://wamp-proto.org/
+var WampMessageType;
+(function (wampMessageTypeEnum) {
+ wampMessageTypeEnum[(wampMessageTypeEnum.Hello = 1)] = "Hello";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Welcome = 2)] = "Welcome";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Abort = 3)] = "Abort";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Challenge = 4)] = "Challenge";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Authenticate = 5)] = "Authenticate";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Goodbye = 6)] = "Goodbye";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Error = 8)] = "Error";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Publish = 16)] = "Publish";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Published = 17)] = "Published";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribe = 32)] = "Subscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribed = 33)] = "Subscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribe = 34)] = "Unsubscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribed = 35)] = "Unsubscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Event = 36)] = "Event";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Call = 48)] = "Call";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Cancel = 49)] = "Cancel";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Result = 50)] = "Result";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Register = 64)] = "Register";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Registered = 65)] = "Registered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregister = 66)] = "Unregister";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregistered = 67)] = "Unregistered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Invocation = 68)] = "Invocation";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Interrupt = 69)] = "Interrupt";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Yield = 70)] = "Yield";
+})(WampMessageType || (WampMessageType = {}));
+
+// The WAMP protocol consists of many messages, disable complexity for one time
+// eslint-disable-next-line complexity
+function parseWampArray(messageArray) {
+ const [messageType, ...args] = messageArray;
+ switch (messageType) {
+ case WampMessageType.Hello:
+ return new HelloMessage(args);
+ case WampMessageType.Welcome:
+ return new WelcomeMessage(args);
+ case WampMessageType.Abort:
+ return new AbortMessage(args);
+ case WampMessageType.Challenge:
+ return new ChallengeMessage(args);
+ case WampMessageType.Authenticate:
+ return new AuthenticateMessage(args);
+ case WampMessageType.Goodbye:
+ return new GoodbyeMessage(args);
+ case WampMessageType.Error:
+ return new ErrorMessage(args);
+ case WampMessageType.Publish:
+ return new PublishMessage(args);
+ case WampMessageType.Published:
+ return new PublishedMessage(args);
+ case WampMessageType.Subscribe:
+ return new SubscribeMessage(args);
+ case WampMessageType.Subscribed:
+ return new SubscribedMessage(args);
+ case WampMessageType.Unsubscribe:
+ return new UnsubscribeMessage(args);
+ case WampMessageType.Unsubscribed:
+ return new UnsubscribedMessage(args);
+ case WampMessageType.Event:
+ return new EventMessage(args);
+ case WampMessageType.Call:
+ return new CallMessage(args);
+ case WampMessageType.Cancel:
+ return new CancelMessage(args);
+ case WampMessageType.Result:
+ return new ResultMessage(args);
+ case WampMessageType.Register:
+ return new RegisterMessage(args);
+ case WampMessageType.Registered:
+ return new RegisteredMessage(args);
+ case WampMessageType.Unregister:
+ return new UnregisterMessage(args);
+ case WampMessageType.Unregistered:
+ return new UnregisteredMessage(args);
+ case WampMessageType.Invocation:
+ return new InvocationMessage(args);
+ case WampMessageType.Interrupt:
+ return new InterruptMessage(args);
+ case WampMessageType.Yield:
+ return new YieldMessage(args);
+ default:
+ return null;
+ }
+}
+class WampMessage {
+ constructor(code) {
+ this.messageCode = code;
+ this.messageName = WampMessageType[code].toUpperCase();
+ }
+}
+class HelloMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Hello);
+ [this.realm, this.details] = messageArgs;
+ }
+}
+class WelcomeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Welcome);
+ [this.session, this.details] = messageArgs;
+ }
+}
+class AbortMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Abort);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ChallengeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Challenge);
+ [this.authMethod, this.extra] = messageArgs;
+ }
+}
+class AuthenticateMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Authenticate);
+ [this.signature, this.extra] = messageArgs;
+ }
+}
+class GoodbyeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Goodbye);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ErrorMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Error);
+ [
+ this.type,
+ this.request,
+ this.details,
+ this.error,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class PublishMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Publish);
+ [this.request, this.options, this.topic, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class PublishedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Published);
+ [this.request, this.publication] = messageArgs;
+ }
+}
+class SubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribe);
+ [this.request, this.options, this.topic] = messageArgs;
+ }
+}
+class SubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribed);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribe);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribed);
+ [this.request] = messageArgs;
+ }
+}
+class EventMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Event);
+ [
+ this.subscription,
+ this.publication,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CallMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Call);
+ [
+ this.request,
+ this.options,
+ this.procedure,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CancelMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Cancel);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class ResultMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Result);
+ [this.request, this.details, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class RegisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Register);
+ [this.request, this.options, this.procedure] = messageArgs;
+ }
+}
+class RegisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Registered);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregister);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregistered);
+ [this.request] = messageArgs;
+ }
+}
+class InvocationMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Invocation);
+ [
+ this.request,
+ this.registration,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class InterruptMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Interrupt);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class YieldMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Yield);
+ [this.request, this.options, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+
+module.exports = {
+ parseWampArray,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
new file mode 100644
index 0000000000..b6b7c91036
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
@@ -0,0 +1,8 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "arrayParser.js",
+ "serializers.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
new file mode 100644
index 0000000000..c2139d320c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
@@ -0,0 +1,73 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const {
+ parseWampArray,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js");
+const msgpack = require("resource://devtools/client/netmonitor/src/components/messages/msgpack.js");
+const cbor = require("resource://devtools/client/netmonitor/src/components/messages/cbor.js");
+
+class WampSerializer {
+ deserializeMessage(payload) {
+ const array = this.deserializeToArray(payload);
+ const result = parseWampArray(array);
+ return result;
+ }
+
+ stringToBinary(str) {
+ const result = new Uint8Array(str.length);
+ for (let i = 0; i < str.length; i++) {
+ result[i] = str[i].charCodeAt(0);
+ }
+ return result;
+ }
+}
+
+class JsonSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.json";
+ this.description = "WAMP JSON";
+ }
+ deserializeToArray(payload) {
+ return JSON.parse(payload);
+ }
+}
+
+class MessagePackSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.msgpack";
+ this.description = "WAMP MessagePack";
+ }
+ deserializeToArray(payload) {
+ const binary = this.stringToBinary(payload);
+ return msgpack.deserialize(binary);
+ }
+}
+
+class CBORSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.cbor";
+ this.description = "WAMP CBOR";
+ }
+ deserializeToArray(payload) {
+ const binaryBuffer = this.stringToBinary(payload).buffer;
+ return cbor.decode(binaryBuffer);
+ }
+}
+
+const serializers = {};
+for (var serializer of [
+ new JsonSerializer(),
+ new MessagePackSerializer(),
+ new CBORSerializer(),
+]) {
+ serializers[serializer.subProtocol] = serializer;
+}
+
+module.exports = { wampSerializers: serializers };