init.ts 2.2 KB

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