promise-constructor-detection.js 2.5 KB

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