expose-rpc.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. var __importDefault = (this && this.__importDefault) || function (mod) {
  12. return (mod && mod.__esModule) ? mod : { "default": mod };
  13. };
  14. Object.defineProperty(exports, "__esModule", { value: true });
  15. exports.exposeRpc = void 0;
  16. const process_1 = __importDefault(require("process"));
  17. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  18. function exposeRpc(fn) {
  19. const sendMessage = (message) => new Promise((resolve, reject) => {
  20. if (!process_1.default.send) {
  21. reject(new Error(`Process ${process_1.default.pid} doesn't have IPC channels`));
  22. }
  23. else if (!process_1.default.connected) {
  24. reject(new Error(`Process ${process_1.default.pid} doesn't have open IPC channels`));
  25. }
  26. else {
  27. process_1.default.send(message, undefined, undefined, (error) => {
  28. if (error) {
  29. reject(error);
  30. }
  31. else {
  32. resolve(undefined);
  33. }
  34. });
  35. }
  36. });
  37. const handleMessage = (message) => __awaiter(this, void 0, void 0, function* () {
  38. if (message.type === 'call') {
  39. if (!process_1.default.send) {
  40. // process disconnected - skip
  41. return;
  42. }
  43. let value;
  44. let error;
  45. try {
  46. value = yield fn(...message.args);
  47. }
  48. catch (fnError) {
  49. error = fnError;
  50. }
  51. try {
  52. if (error) {
  53. yield sendMessage({
  54. type: 'reject',
  55. id: message.id,
  56. error,
  57. });
  58. }
  59. else {
  60. yield sendMessage({
  61. type: 'resolve',
  62. id: message.id,
  63. value,
  64. });
  65. }
  66. }
  67. catch (sendError) {
  68. // we can't send things back to the parent process - let's use stdout to communicate error
  69. if (error) {
  70. console.error(error);
  71. }
  72. console.error(sendError);
  73. }
  74. }
  75. });
  76. process_1.default.on('message', handleMessage);
  77. }
  78. exports.exposeRpc = exposeRpc;