provider-ipcsocket.js 2.1 KB

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