init.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import * as util from 'util';
  2. import { electronBindingSetup } from '@electron/internal/common/electron-binding-setup';
  3. const timers = require('timers');
  4. process.electronBinding = electronBindingSetup(process._linkedBinding, process.type);
  5. type AnyFn = (...args: any[]) => any
  6. // setImmediate and process.nextTick makes use of uv_check and uv_prepare to
  7. // run the callbacks, however since we only run uv loop on requests, the
  8. // callbacks wouldn't be called until something else activated the uv loop,
  9. // which would delay the callbacks for arbitrary long time. So we should
  10. // initiatively activate the uv loop once setImmediate and process.nextTick is
  11. // called.
  12. const wrapWithActivateUvLoop = function <T extends AnyFn> (func: T): T {
  13. return wrap(func, function (func) {
  14. return function (this: any, ...args: any[]) {
  15. process.activateUvLoop();
  16. return func.apply(this, args);
  17. };
  18. }) as T;
  19. };
  20. /**
  21. * Casts to any below for func are due to Typescript not supporting symbols
  22. * in index signatures
  23. *
  24. * Refs: https://github.com/Microsoft/TypeScript/issues/1863
  25. */
  26. function wrap <T extends AnyFn> (func: T, wrapper: (fn: AnyFn) => T) {
  27. const wrapped = wrapper(func);
  28. if ((func as any)[util.promisify.custom]) {
  29. (wrapped as any)[util.promisify.custom] = wrapper((func as any)[util.promisify.custom]);
  30. }
  31. return wrapped;
  32. }
  33. process.nextTick = wrapWithActivateUvLoop(process.nextTick);
  34. global.setImmediate = timers.setImmediate = wrapWithActivateUvLoop(timers.setImmediate);
  35. global.clearImmediate = timers.clearImmediate;
  36. // setTimeout needs to update the polling timeout of the event loop, when
  37. // called under Chromium's event loop the node's event loop won't get a chance
  38. // to update the timeout, so we have to force the node's event loop to
  39. // recalculate the timeout in browser process.
  40. timers.setTimeout = wrapWithActivateUvLoop(timers.setTimeout);
  41. timers.setInterval = wrapWithActivateUvLoop(timers.setInterval);
  42. // Only override the global setTimeout/setInterval impls in the browser process
  43. if (process.type === 'browser') {
  44. global.setTimeout = timers.setTimeout;
  45. global.setInterval = timers.setInterval;
  46. }
  47. if (process.platform === 'win32') {
  48. // Always returns EOF for stdin stream.
  49. const { Readable } = require('stream');
  50. const stdin = new Readable();
  51. stdin.push(null);
  52. Object.defineProperty(process, 'stdin', {
  53. configurable: false,
  54. enumerable: true,
  55. get () {
  56. return stdin;
  57. }
  58. });
  59. }