provider-ipcsocket.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.IpcSocketProvider = void 0;
  4. const net_1 = require("net");
  5. const provider_socket_js_1 = require("./provider-socket.js");
  6. // @TODO: Is this sufficient? Is this robust? Will newlines occur between
  7. // all payloads and only between payloads?
  8. function splitBuffer(data) {
  9. const messages = [];
  10. let lastStart = 0;
  11. while (true) {
  12. const nl = data.indexOf(10, lastStart);
  13. if (nl === -1) {
  14. break;
  15. }
  16. messages.push(data.subarray(lastStart, nl).toString().trim());
  17. lastStart = nl + 1;
  18. }
  19. return { messages, remaining: data.subarray(lastStart) };
  20. }
  21. /**
  22. * An **IpcSocketProvider** connects over an IPC socket on the host
  23. * which provides fast access to the node, but requires the node and
  24. * the script run on the same machine.
  25. */
  26. class IpcSocketProvider extends provider_socket_js_1.SocketProvider {
  27. #socket;
  28. /**
  29. * The connected socket.
  30. */
  31. get socket() { return this.#socket; }
  32. constructor(path, network, options) {
  33. super(network, options);
  34. this.#socket = (0, net_1.connect)(path);
  35. this.socket.on("ready", async () => {
  36. try {
  37. await this._start();
  38. }
  39. catch (error) {
  40. console.log("failed to start IpcSocketProvider", error);
  41. // @TODO: Now what? Restart?
  42. }
  43. });
  44. let response = Buffer.alloc(0);
  45. this.socket.on("data", (data) => {
  46. response = Buffer.concat([response, data]);
  47. const { messages, remaining } = splitBuffer(response);
  48. messages.forEach((message) => {
  49. this._processMessage(message);
  50. });
  51. response = remaining;
  52. });
  53. this.socket.on("end", () => {
  54. this.emit("close");
  55. this.socket.destroy();
  56. this.socket.end();
  57. });
  58. }
  59. destroy() {
  60. this.socket.destroy();
  61. this.socket.end();
  62. super.destroy();
  63. }
  64. async _write(message) {
  65. if (!message.endsWith("\n")) {
  66. message += "\n";
  67. }
  68. this.socket.write(message);
  69. }
  70. }
  71. exports.IpcSocketProvider = IpcSocketProvider;
  72. //# sourceMappingURL=provider-ipcsocket.js.map