PolyfillFunctions.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow
  8. * @format
  9. */
  10. 'use strict';
  11. const defineLazyObjectProperty = require('./defineLazyObjectProperty');
  12. /**
  13. * Sets an object's property. If a property with the same name exists, this will
  14. * replace it but maintain its descriptor configuration. The property will be
  15. * replaced with a lazy getter.
  16. *
  17. * In DEV mode the original property value will be preserved as `original[PropertyName]`
  18. * so that, if necessary, it can be restored. For example, if you want to route
  19. * network requests through DevTools (to trace them):
  20. *
  21. * global.XMLHttpRequest = global.originalXMLHttpRequest;
  22. *
  23. * @see https://github.com/facebook/react-native/issues/934
  24. */
  25. function polyfillObjectProperty<T>(
  26. object: Object,
  27. name: string,
  28. getValue: () => T,
  29. ): void {
  30. const descriptor = Object.getOwnPropertyDescriptor(object, name);
  31. if (__DEV__ && descriptor) {
  32. const backupName = `original${name[0].toUpperCase()}${name.substr(1)}`;
  33. Object.defineProperty(object, backupName, descriptor);
  34. }
  35. const {enumerable, writable, configurable} = descriptor || {};
  36. if (descriptor && !configurable) {
  37. console.error('Failed to set polyfill. ' + name + ' is not configurable.');
  38. return;
  39. }
  40. defineLazyObjectProperty(object, name, {
  41. get: getValue,
  42. enumerable: enumerable !== false,
  43. writable: writable !== false,
  44. });
  45. }
  46. function polyfillGlobal<T>(name: string, getValue: () => T): void {
  47. polyfillObjectProperty(global, name, getValue);
  48. }
  49. module.exports = {polyfillObjectProperty, polyfillGlobal};