Files
react-native/packages/react-native/Libraries/Utilities/defineLazyObjectProperty.js
T
Iwo Plaza 028c0b36f6 Migrate Utilities/deepFreezeAndThrowOnMutationInDev.js, Utilities/defineLazyObjectProperty.js, Utilities/DeviceInfo.js & Utilities/FeatureDetection.js to use export syntax (#49408)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49408

## Motivation
Modernising the RN codebase to allow for modern Flow tooling to process it.

## This diff
- Migrates Utilities/deepFreezeAndThrowOnMutationInDev.js, Utilities/defineLazyObjectProperty.js, Utilities/DeviceInfo.js & Utilities/FeatureDetection.js to use the export syntax.
- Updates deep-imports of files that were migrated to a single export default to use `.default`
- Updates the current iteration of API snapshots (intended).

Changelog:
[General][Breaking] - Deep imports to `Utilities/deepFreezeAndThrowOnMutationInDev`, `Utilities/defineLazyObjectProperty`, `Utilities/DeviceInfo` or `Utilities/FeatureDetection` with `require` syntax may need to be appended with '.default'.

Reviewed By: huntie

Differential Revision: D69602536

fbshipit-source-id: 7ec06995a1d244b95d4f970551955d9e6013de13
2025-02-13 13:11:20 -08:00

67 lines
1.7 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict
*/
'use strict';
/**
* Defines a lazily evaluated property on the supplied `object`.
*/
function defineLazyObjectProperty<T>(
object: interface {},
name: string,
descriptor: {
get: () => T,
enumerable?: boolean,
writable?: boolean,
...
},
): void {
const {get} = descriptor;
const enumerable = descriptor.enumerable !== false;
const writable = descriptor.writable !== false;
let value;
let valueSet = false;
function getValue(): T {
// WORKAROUND: A weird infinite loop occurs where calling `getValue` calls
// `setValue` which calls `Object.defineProperty` which somehow triggers
// `getValue` again. Adding `valueSet` breaks this loop.
if (!valueSet) {
// Calling `get()` here can trigger an infinite loop if it fails to
// remove the getter on the property, which can happen when executing
// JS in a V8 context. `valueSet = true` will break this loop, and
// sets the value of the property to undefined, until the code in `get()`
// finishes, at which point the property is set to the correct value.
valueSet = true;
setValue(get());
}
return value;
}
function setValue(newValue: T): void {
value = newValue;
valueSet = true;
Object.defineProperty(object, name, {
value: newValue,
configurable: true,
enumerable,
writable,
});
}
Object.defineProperty(object, name, {
get: getValue,
set: setValue,
configurable: true,
enumerable,
});
}
export default defineLazyObjectProperty;