promise-constructor-detection.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var global = require('../internals/global');
  2. var NativePromiseConstructor = require('../internals/promise-native-constructor');
  3. var isCallable = require('../internals/is-callable');
  4. var isForced = require('../internals/is-forced');
  5. var inspectSource = require('../internals/inspect-source');
  6. var wellKnownSymbol = require('../internals/well-known-symbol');
  7. var IS_BROWSER = require('../internals/engine-is-browser');
  8. var IS_DENO = require('../internals/engine-is-deno');
  9. var IS_PURE = require('../internals/is-pure');
  10. var V8_VERSION = require('../internals/engine-v8-version');
  11. var NativePromisePrototype = NativePromiseConstructor && NativePromiseConstructor.prototype;
  12. var SPECIES = wellKnownSymbol('species');
  13. var SUBCLASSING = false;
  14. var NATIVE_PROMISE_REJECTION_EVENT = isCallable(global.PromiseRejectionEvent);
  15. var FORCED_PROMISE_CONSTRUCTOR = isForced('Promise', function () {
  16. var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(NativePromiseConstructor);
  17. var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(NativePromiseConstructor);
  18. // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
  19. // https://bugs.chromium.org/p/chromium/issues/detail?id=830565
  20. // We can't detect it synchronously, so just check versions
  21. if (!GLOBAL_CORE_JS_PROMISE && V8_VERSION === 66) return true;
  22. // We need Promise#{ catch, finally } in the pure version for preventing prototype pollution
  23. if (IS_PURE && !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true;
  24. // We can't use @@species feature detection in V8 since it causes
  25. // deoptimization and performance degradation
  26. // https://github.com/zloirock/core-js/issues/679
  27. if (!V8_VERSION || V8_VERSION < 51 || !/native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) {
  28. // Detect correctness of subclassing with @@species support
  29. var promise = new NativePromiseConstructor(function (resolve) { resolve(1); });
  30. var FakePromise = function (exec) {
  31. exec(function () { /* empty */ }, function () { /* empty */ });
  32. };
  33. var constructor = promise.constructor = {};
  34. constructor[SPECIES] = FakePromise;
  35. SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
  36. if (!SUBCLASSING) return true;
  37. // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
  38. } return !GLOBAL_CORE_JS_PROMISE && (IS_BROWSER || IS_DENO) && !NATIVE_PROMISE_REJECTION_EVENT;
  39. });
  40. module.exports = {
  41. CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR,
  42. REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT,
  43. SUBCLASSING: SUBCLASSING
  44. };