HandshakeProtocol.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. import { TextMessageFormat } from "./TextMessageFormat";
  4. import { isArrayBuffer } from "./Utils";
  5. /** @private */
  6. var HandshakeProtocol = /** @class */ (function () {
  7. function HandshakeProtocol() {
  8. }
  9. // Handshake request is always JSON
  10. HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) {
  11. return TextMessageFormat.write(JSON.stringify(handshakeRequest));
  12. };
  13. HandshakeProtocol.prototype.parseHandshakeResponse = function (data) {
  14. var responseMessage;
  15. var messageData;
  16. var remainingData;
  17. if (isArrayBuffer(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) {
  18. // Format is binary but still need to read JSON text from handshake response
  19. var binaryData = new Uint8Array(data);
  20. var separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
  21. if (separatorIndex === -1) {
  22. throw new Error("Message is incomplete.");
  23. }
  24. // content before separator is handshake response
  25. // optional content after is additional messages
  26. var responseLength = separatorIndex + 1;
  27. messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
  28. remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
  29. }
  30. else {
  31. var textData = data;
  32. var separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
  33. if (separatorIndex === -1) {
  34. throw new Error("Message is incomplete.");
  35. }
  36. // content before separator is handshake response
  37. // optional content after is additional messages
  38. var responseLength = separatorIndex + 1;
  39. messageData = textData.substring(0, responseLength);
  40. remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
  41. }
  42. // At this point we should have just the single handshake message
  43. var messages = TextMessageFormat.parse(messageData);
  44. var response = JSON.parse(messages[0]);
  45. if (response.type) {
  46. throw new Error("Expected a handshake response from the server.");
  47. }
  48. responseMessage = response;
  49. // multiple messages could have arrived with handshake
  50. // return additional data to be parsed as usual, or null if all parsed
  51. return [remainingData, responseMessage];
  52. };
  53. return HandshakeProtocol;
  54. }());
  55. export { HandshakeProtocol };
  56. //# sourceMappingURL=HandshakeProtocol.js.map