Repository: oblador/flipper-plugin-react-native-performance Branch: master Commit: 66d91c03d1a6 Files: 136 Total size: 201.2 KB Directory structure: gitextract_91if_wb_/ ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ └── tests.yml ├── .gitignore ├── .node-version ├── .prettierrc ├── .tool-versions ├── .watchmanconfig ├── LICENSE ├── README.md ├── examples/ │ ├── vanilla/ │ │ ├── .bundle/ │ │ │ └── config │ │ ├── .eslintrc.js │ │ ├── .gitignore │ │ ├── .watchmanconfig │ │ ├── App.tsx │ │ ├── Gemfile │ │ ├── README.md │ │ ├── __tests__/ │ │ │ └── App.test.tsx │ │ ├── android/ │ │ │ ├── app/ │ │ │ │ ├── build.gradle │ │ │ │ ├── debug.keystore │ │ │ │ ├── proguard-rules.pro │ │ │ │ └── src/ │ │ │ │ ├── debug/ │ │ │ │ │ └── AndroidManifest.xml │ │ │ │ └── main/ │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── java/ │ │ │ │ │ └── com/ │ │ │ │ │ └── example/ │ │ │ │ │ ├── MainActivity.kt │ │ │ │ │ └── MainApplication.kt │ │ │ │ └── res/ │ │ │ │ ├── drawable/ │ │ │ │ │ └── rn_edit_text_material.xml │ │ │ │ └── values/ │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ │ ├── build.gradle │ │ │ ├── gradle/ │ │ │ │ └── wrapper/ │ │ │ │ ├── gradle-wrapper.jar │ │ │ │ └── gradle-wrapper.properties │ │ │ ├── gradle.properties │ │ │ ├── gradlew │ │ │ ├── gradlew.bat │ │ │ └── settings.gradle │ │ ├── app.json │ │ ├── babel.config.js │ │ ├── index.js │ │ ├── ios/ │ │ │ ├── .xcode.env │ │ │ ├── Example/ │ │ │ │ ├── AppDelegate.swift │ │ │ │ ├── Images.xcassets/ │ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ │ └── Contents.json │ │ │ │ │ └── Contents.json │ │ │ │ ├── Info.plist │ │ │ │ ├── LaunchScreen.storyboard │ │ │ │ └── PrivacyInfo.xcprivacy │ │ │ ├── Example-Bridging-Header.h │ │ │ ├── Example.xcodeproj/ │ │ │ │ ├── project.pbxproj │ │ │ │ └── xcshareddata/ │ │ │ │ └── xcschemes/ │ │ │ │ └── Example.xcscheme │ │ │ ├── Example.xcworkspace/ │ │ │ │ └── contents.xcworkspacedata │ │ │ └── Podfile │ │ ├── jest.config.js │ │ ├── metro.config.js │ │ ├── package.json │ │ └── tsconfig.json │ └── web/ │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public/ │ │ ├── index.html │ │ ├── manifest.json │ │ └── robots.txt │ ├── src/ │ │ ├── App.css │ │ ├── App.test.tsx │ │ ├── App.tsx │ │ ├── index.css │ │ ├── index.tsx │ │ ├── react-app-env.d.ts │ │ ├── reportWebVitals.ts │ │ └── setupTests.ts │ └── tsconfig.json ├── lerna.json ├── package.json ├── packages/ │ ├── isomorphic-performance/ │ │ ├── README.md │ │ ├── package.json │ │ ├── src/ │ │ │ ├── browser.js │ │ │ ├── node.js │ │ │ ├── react-native.js │ │ │ └── types.d.ts │ │ └── tsconfig.json │ └── react-native-performance/ │ ├── README.md │ ├── android/ │ │ ├── .gitignore │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── oblador/ │ │ └── performance/ │ │ ├── PerformanceEntry.java │ │ ├── PerformanceMark.java │ │ ├── PerformanceMetric.java │ │ ├── PerformanceModule.java │ │ ├── PerformancePackage.java │ │ ├── RNPerformance.java │ │ └── StartTimeProvider.java │ ├── babel.config.js │ ├── ios/ │ │ ├── RNPerformance.h │ │ ├── RNPerformance.mm │ │ ├── RNPerformanceEntry.h │ │ ├── RNPerformanceEntry.m │ │ ├── RNPerformanceManager.h │ │ ├── RNPerformanceManager.mm │ │ └── RNPerformanceUtils.h │ ├── jest.config.js │ ├── package.json │ ├── react-native-performance.podspec │ ├── react-native-performance.xcodeproj/ │ │ ├── project.pbxproj │ │ └── xcshareddata/ │ │ └── xcschemes/ │ │ ├── react-native-performance-tvOS.xcscheme │ │ └── react-native-performance.xcscheme │ ├── src/ │ │ ├── NativeRNPerformanceManager.ts │ │ ├── event-emitter.ts │ │ ├── index.ts │ │ ├── instance.ts │ │ ├── performance-entry.ts │ │ ├── performance-observer.ts │ │ ├── performance.ts │ │ └── resource-logger.ts │ ├── test/ │ │ ├── README.md │ │ ├── performance-entry.spec.ts │ │ ├── performance-now.spec.ts │ │ ├── performance-observer/ │ │ │ ├── buffered-false.spec.ts │ │ │ ├── buffered-flag-after-timeout.spec.ts │ │ │ ├── buffered-flag.spec.ts │ │ │ ├── disconnect-removes-observed-types.spec.ts │ │ │ ├── disconnect.spec.ts │ │ │ ├── entries-sort.spec.ts │ │ │ ├── get-entries.spec.ts │ │ │ ├── helpers.ts │ │ │ ├── mark-measure.spec.ts │ │ │ ├── multiple-buffered-flag-observers.spec.ts │ │ │ ├── observe-repeated-type.spec.ts │ │ │ ├── observe-type.spec.ts │ │ │ ├── observe.spec.ts │ │ │ ├── supported-entry-types.spec.ts │ │ │ └── take-records.spec.ts │ │ ├── setup.js │ │ └── user-timing-3.spec.ts │ ├── tsconfig.build.json │ └── tsconfig.json └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ github: [oblador] ================================================ FILE: .github/workflows/tests.yml ================================================ name: Tests on: push: branches: - master pull_request: jobs: unit-tests: name: Unit tests runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version-file: '.node-version' - name: Install dependencies run: yarn --frozen-lockfile --non-interactive --silent --ignore-scripts - name: Run tests run: yarn test integration-tests: name: Integration tests runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version-file: '.node-version' - name: Install dependencies run: yarn --frozen-lockfile --non-interactive --silent - name: Run tests run: yarn workspace web-example run test types: name: Type checks runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version-file: '.node-version' - name: Install dependencies run: yarn --frozen-lockfile --non-interactive --silent - name: Check package types run: yarn types - name: Check web example types run: yarn workspace web-example run tsc - name: Check vanilla example types run: yarn workspace vanilla-example run tsc format: name: Code formatting runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version-file: '.node-version' - name: Install dependencies run: yarn --frozen-lockfile --non-interactive --silent --ignore-scripts - name: Check formatting run: yarn check-format build: name: Package builds runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version-file: '.node-version' - name: Install dependencies run: yarn --frozen-lockfile --non-interactive --silent --ignore-scripts - name: Build packages env: PACKAGES: react-native-performance run: for p in $PACKAGES; do pushd packages/$p && npm pack --dry-run && popd; done ================================================ FILE: .gitignore ================================================ # Logs logs *.log # Runtime data pids *.pid *.seed # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # node-waf configuration .lock-wscript # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release # Dependency directory # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git node_modules # Transpilation / bundling output dist # OSX .DS_Store # Xcode build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate project.xcworkspace # generated by bob packages/*/lib/ ================================================ FILE: .node-version ================================================ 22.12.0 ================================================ FILE: .prettierrc ================================================ { "printWidth": 80, "singleQuote": true, "trailingComma": "es5" } ================================================ FILE: .tool-versions ================================================ ruby 3.2.1 bundler 2.6.0 ================================================ FILE: .watchmanconfig ================================================ { "ignore_dirs": [ "examples/vanilla/ios", "examples/vanilla/android", "examples/react-native-navigation/ios", "examples/react-native-navigation/android" ] } ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2019 - present Joel Arvidsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # React Native Performance tooling Toolchain to measure and monitor the performance of your React Native app in development, pipeline and in production. ## Packages ### [`react-native-performance`](https://github.com/oblador/react-native-performance/blob/master/packages/react-native-performance/README.md) An implementation of the [`Performance` API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) for React Native. - Integrates well with `React.Profiler` API - Trace arbitrary events in your app such as component render time - Capture network traffic - Collect native traces such as script execution and time to interactive of root view - Collect native metrics in development such as JS bundle size ### [`isomorphic-performance`](https://github.com/oblador/react-native-performance/blob/master/packages/isomorphic-performance/README.md) Isomorphic Performance API for Node, Browser & React Native. Useful if your app targets both web and native. ## Demo See the projects in the [`examples`](https://github.com/oblador/react-native-performance/tree/master/examples) folder. ## Devtools integration With Flipper deprecated, the best replacement is currently [Rozenite](https://www.rozenite.dev) that supports `react-native-performance` out of the box with an [official plugin](https://www.rozenite.dev/docs/official-plugins/performance-monitor). ## Development Make sure to have [`yarn`](https://classic.yarnpkg.com/lang/en/) v1 installed and run `yarn` in the root folder to install dependencies for all packages. Run the example app with: ```bash cd examples/vanilla yarn start # important to run this before the next step! yarn ios # or yarn android ``` Run the unit tests with: ```bash yarn test ``` ## License MIT © Joel Arvidsson 2019 – present ================================================ FILE: examples/vanilla/.bundle/config ================================================ BUNDLE_PATH: "vendor/bundle" BUNDLE_FORCE_RUBY_PLATFORM: 1 ================================================ FILE: examples/vanilla/.eslintrc.js ================================================ module.exports = { root: true, extends: '@react-native', }; ================================================ FILE: examples/vanilla/.gitignore ================================================ # OSX # .DS_Store # Xcode # build/ *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 xcuserdata *.xccheckout *.moved-aside DerivedData *.hmap *.ipa *.xcuserstate **/.xcode.env.local # Android/IntelliJ # build/ .idea .gradle local.properties *.iml *.hprof .cxx/ *.keystore !debug.keystore .kotlin/ # node.js # node_modules/ npm-debug.log yarn-error.log # fastlane # # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the # screenshots whenever they are needed. # For more information about the recommended setup visit: # https://docs.fastlane.tools/best-practices/source-control/ **/fastlane/report.xml **/fastlane/Preview.html **/fastlane/screenshots **/fastlane/test_output # Bundle artifact *.jsbundle # Ruby / CocoaPods **/Pods/ /vendor/bundle/ # Temporary files created by Metro to check the health of the file watcher .metro-health-check* # testing /coverage # Yarn .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions ================================================ FILE: examples/vanilla/.watchmanconfig ================================================ {} ================================================ FILE: examples/vanilla/App.tsx ================================================ /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React, { Profiler, ProfilerOnRenderCallback } from 'react'; import { StyleSheet, ScrollView, View, Text } from 'react-native'; import { Header, Colors } from 'react-native/Libraries/NewAppScreen'; import performance, { setResourceLoggingEnabled, PerformanceObserver, } from 'react-native-performance'; import type { PerformanceMetric, PerformanceResourceTiming, PerformanceReactNativeMark, } from 'react-native-performance'; setResourceLoggingEnabled(true); const traceRender: ProfilerOnRenderCallback = ( id, // the "id" prop of the Profiler tree that has just committed phase, // either "mount" (if the tree just mounted) or "update" (if it re-rendered) actualDuration, // time spent rendering the committed update baseDuration, // estimated time to render the entire subtree without memoization startTime, // when React began rendering this update _commitTime, // when React committed this update _interactions // the Set of interactions belonging to this update ) => performance.measure(id, { start: startTime, duration: actualDuration, }); const formatValue = (value: number, unit?: string) => { switch (unit) { case 'ms': return `${value.toFixed(1)}ms`; case 'byte': return `${(value / 1024 / 1024).toFixed(1)}MB`; case '$DOGE': return `${value} doge coins`; default: return value.toFixed(1); } }; const Entry = ({ name, value, unit = 'ms', }: { name: string; value: number; unit?: string; }) => ( {name}: {formatValue(value, unit)} ); const App = () => { const [metrics, setMetrics] = React.useState([]); const [nativeMarks, setNativeMarks] = React.useState< PerformanceReactNativeMark[] >([]); const [resources, setResources] = React.useState( [] ); React.useEffect(() => { new PerformanceObserver(() => { setNativeMarks( performance .getEntriesByType('react-native-mark') .sort( (a: PerformanceReactNativeMark, b: PerformanceReactNativeMark) => a.startTime - b.startTime ) ); }).observe({ type: 'react-native-mark', buffered: true }); new PerformanceObserver(() => { setMetrics(performance.getEntriesByType('metric')); }).observe({ type: 'metric', buffered: true }); new PerformanceObserver(() => { setResources(performance.getEntriesByType('resource')); }).observe({ type: 'resource', buffered: true }); }, []); React.useEffect(() => { // @ts-ignore fetch('https://xkcd.com/info.0.json', { cache: 'no-cache' }); }, []); return (
performance.getEntriesByType('metric') {metrics.map(({ name, startTime, value, detail }) => ( ))} performance.getEntriesByType('resource') {resources.map(({ name, duration, startTime }) => ( ))} performance.getEntriesByType('react-native-mark') {nativeMarks.map(({ name, startTime }) => ( ))} ); }; const styles = StyleSheet.create({ scrollView: { backgroundColor: Colors.lighter, }, engine: { position: 'absolute', right: 0, }, body: { backgroundColor: Colors.white, }, sectionContainer: { marginBottom: 20, paddingHorizontal: 24, }, sectionTitle: { fontSize: 20, fontWeight: '600', color: Colors.black, fontFamily: 'Courier', marginTop: 20, marginBottom: 10, }, entry: { marginBottom: 8, fontSize: 14, fontWeight: '400', color: Colors.dark, fontFamily: 'Courier', }, footer: { color: Colors.dark, fontSize: 12, fontWeight: '600', padding: 4, paddingRight: 12, textAlign: 'right', }, }); export default App; ================================================ FILE: examples/vanilla/Gemfile ================================================ source 'https://rubygems.org' # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version ruby ">= 2.6.10" # Exclude problematic versions of cocoapods and activesupport that causes build failures. gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' gem 'xcodeproj', '< 1.26.0' gem 'concurrent-ruby', '< 1.3.4' ================================================ FILE: examples/vanilla/README.md ================================================ This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli). # Getting Started > **Note**: Make sure you have completed the [Set Up Your Environment](https://reactnative.dev/docs/set-up-your-environment) guide before proceeding. ## Step 1: Start Metro First, you will need to run **Metro**, the JavaScript build tool for React Native. To start the Metro dev server, run the following command from the root of your React Native project: ```sh # Using npm npm start # OR using Yarn yarn start ``` ## Step 2: Build and run your app With Metro running, open a new terminal window/pane from the root of your React Native project, and use one of the following commands to build and run your Android or iOS app: ### Android ```sh # Using npm npm run android # OR using Yarn yarn android ``` ### iOS For iOS, remember to install CocoaPods dependencies (this only needs to be run on first clone or after updating native deps). The first time you create a new project, run the Ruby bundler to install CocoaPods itself: ```sh bundle install ``` Then, and every time you update your native dependencies, run: ```sh bundle exec pod install ``` For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html). ```sh # Using npm npm run ios # OR using Yarn yarn ios ``` If everything is set up correctly, you should see your new app running in the Android Emulator, iOS Simulator, or your connected device. This is one way to run your app — you can also build it directly from Android Studio or Xcode. ## Step 3: Modify your app Now that you have successfully run the app, let's make changes! Open `App.tsx` in your text editor of choice and make some changes. When you save, your app will automatically update and reflect these changes — this is powered by [Fast Refresh](https://reactnative.dev/docs/fast-refresh). When you want to forcefully reload, for example to reset the state of your app, you can perform a full reload: - **Android**: Press the R key twice or select **"Reload"** from the **Dev Menu**, accessed via Ctrl + M (Windows/Linux) or Cmd ⌘ + M (macOS). - **iOS**: Press R in iOS Simulator. ## Congratulations! :tada: You've successfully run and modified your React Native App. :partying_face: ### Now what? - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps). - If you're curious to learn more about React Native, check out the [docs](https://reactnative.dev/docs/getting-started). # Troubleshooting If you're having issues getting the above steps to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page. # Learn More To learn more about React Native, take a look at the following resources: - [React Native Website](https://reactnative.dev) - learn more about React Native. - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment. - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**. - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts. - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native. ================================================ FILE: examples/vanilla/__tests__/App.test.tsx ================================================ /** * @format */ import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; import App from '../App'; test('renders correctly', async () => { await ReactTestRenderer.act(() => { ReactTestRenderer.create(); }); }); ================================================ FILE: examples/vanilla/android/app/build.gradle ================================================ apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native reactNativeDir = file("../../../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen codegenDir = file("../../../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js cliFile = file("../../../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.example" defaultConfig { applicationId "com.example" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } } ================================================ FILE: examples/vanilla/android/app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: ================================================ FILE: examples/vanilla/android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: examples/vanilla/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: examples/vanilla/android/app/src/main/java/com/example/MainActivity.kt ================================================ package com.example import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "Example" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) } ================================================ FILE: examples/vanilla/android/app/src/main/java/com/example/MainApplication.kt ================================================ package com.example import android.app.Application import android.os.Bundle; import android.os.Handler; import android.os.Looper; import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.soloader.OpenSourceMergedSoMapping import com.facebook.soloader.SoLoader import com.oblador.performance.RNPerformance; class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(applicationContext, reactNativeHost) override fun onCreate() { RNPerformance.getInstance().mark("onCreateStart") super.onCreate() SoLoader.init(this, OpenSourceMergedSoMapping) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } RNPerformance.getInstance().mark("onCreateEnd") var detail = Bundle() detail.putString("unit", "byte") RNPerformance.getInstance().metric("bundleSize", 1337.0, detail) Handler(Looper.getMainLooper()).postDelayed({ RNPerformance.getInstance().mark("Delayed Mark") }, 3000L) } } ================================================ FILE: examples/vanilla/android/app/src/main/res/drawable/rn_edit_text_material.xml ================================================ ================================================ FILE: examples/vanilla/android/app/src/main/res/values/strings.xml ================================================ Example ================================================ FILE: examples/vanilla/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: examples/vanilla/android/build.gradle ================================================ buildscript { ext { buildToolsVersion = "35.0.0" minSdkVersion = 24 compileSdkVersion = 35 targetSdkVersion = 35 ndkVersion = "27.1.12297006" kotlinVersion = "2.0.21" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject" ================================================ FILE: examples/vanilla/android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: examples/vanilla/android/gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the # Android operating system, and which are packaged with your app's APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Use this property to specify which architecture you want to build. # You can also override it from the CLI using # ./gradlew -PreactNativeArchitectures=x86_64 reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # Use this property to enable support to the new architecture. # This will allow you to use TurboModules and the Fabric render in # your application. You should enable this flag either if you want # to write custom TurboModules/Fabric components OR use libraries that # are providing them. newArchEnabled=true # Use this property to enable or disable the Hermes JS engine. # If set to false, you will be using JSC instead. hermesEnabled=true ================================================ FILE: examples/vanilla/android/gradlew ================================================ #!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@" ================================================ FILE: examples/vanilla/android/gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @rem SPDX-License-Identifier: Apache-2.0 @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo. 1>&2 echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: examples/vanilla/android/settings.gradle ================================================ pluginManagement { includeBuild("../../../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'Example' include ':app' includeBuild('../../../node_modules/@react-native/gradle-plugin') ================================================ FILE: examples/vanilla/app.json ================================================ { "name": "Example", "displayName": "Example" } ================================================ FILE: examples/vanilla/babel.config.js ================================================ module.exports = { presets: ['module:@react-native/babel-preset'], }; ================================================ FILE: examples/vanilla/index.js ================================================ import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App); ================================================ FILE: examples/vanilla/ios/.xcode.env ================================================ # This `.xcode.env` file is versioned and is used to source the environment # used when running script phases inside Xcode. # To customize your local environment, you can create an `.xcode.env.local` # file that is not versioned. # NODE_BINARY variable contains the PATH to the node executable. # # Customize the NODE_BINARY variable here. # For example, to use nvm with brew, add the following line # . "$(brew --prefix nvm)/nvm.sh" --no-use export NODE_BINARY=$(command -v node) ================================================ FILE: examples/vanilla/ios/Example/AppDelegate.swift ================================================ import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: RCTAppDelegate { override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { self.moduleName = "Example" self.dependencyProvider = RCTAppDependencyProvider() // You can add your custom initial props in the dictionary below. // They will be passed down to the ViewController used by React Native. self.initialProps = [:] RNPerformance.sharedInstance().mark("myCustomMark", ephemeral: false) /* [RNPerformance.sharedInstance mark:@"myCustomMark"]; [RNPerformance.sharedInstance mark:@"myCustomMark" detail:@{ @"extra": @"info" }]; [RNPerformance.sharedInstance mark:@"myCustomMark" ephemeral:NO]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123)]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123) detail:@{ @"unit": @"ms" }]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123) ephemeral:NO];*/ return super.application(application, didFinishLaunchingWithOptions: launchOptions) } override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } } ================================================ FILE: examples/vanilla/ios/Example/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "scale" : "2x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "3x", "size" : "20x20" }, { "idiom" : "iphone", "scale" : "2x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "3x", "size" : "29x29" }, { "idiom" : "iphone", "scale" : "2x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "3x", "size" : "40x40" }, { "idiom" : "iphone", "scale" : "2x", "size" : "60x60" }, { "idiom" : "iphone", "scale" : "3x", "size" : "60x60" }, { "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" } ], "info" : { "author" : "xcode", "version" : 1 } } ================================================ FILE: examples/vanilla/ios/Example/Images.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: examples/vanilla/ios/Example/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleDisplayName Example CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion $(CURRENT_PROJECT_VERSION) LSRequiresIPhoneOS NSAppTransportSecurity NSAllowsArbitraryLoads NSAllowsLocalNetworking NSLocationWhenInUseUsageDescription UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities arm64 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: examples/vanilla/ios/Example/LaunchScreen.storyboard ================================================ ================================================ FILE: examples/vanilla/ios/Example/PrivacyInfo.xcprivacy ================================================ NSPrivacyAccessedAPITypes NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryFileTimestamp NSPrivacyAccessedAPITypeReasons C617.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategoryUserDefaults NSPrivacyAccessedAPITypeReasons CA92.1 NSPrivacyAccessedAPIType NSPrivacyAccessedAPICategorySystemBootTime NSPrivacyAccessedAPITypeReasons 35F9.1 NSPrivacyCollectedDataTypes NSPrivacyTracking ================================================ FILE: examples/vanilla/ios/Example-Bridging-Header.h ================================================ // // Example-Bridging-Header.h // Example // // Created by Joel Arvidsson on 2025-04-05. // #import ================================================ FILE: examples/vanilla/ios/Example.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 0C80B921A6F3F58F76C31292 /* libPods-Example.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-Example.a */; }; 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; }; 7DEBBB6DE2ED1027D5165AD4 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */; }; 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ 13B07F961A680F5B00A75B9A /* Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = Example/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = Example/Info.plist; sourceTree = ""; }; 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = Example/PrivacyInfo.xcprivacy; sourceTree = ""; }; 3B4392A12AC88292D35C810B /* Pods-Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Example.debug.xcconfig"; path = "Target Support Files/Pods-Example/Pods-Example.debug.xcconfig"; sourceTree = ""; }; 5709B34CF0A7D63546082F79 /* Pods-Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Example.release.xcconfig"; path = "Target Support Files/Pods-Example/Pods-Example.release.xcconfig"; sourceTree = ""; }; 5DCACB8F33CDC322A6C60F78 /* libPods-Example.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Example.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 5DD804042DA11CD300D134D5 /* Example-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Example-Bridging-Header.h"; sourceTree = ""; }; 761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = Example/AppDelegate.swift; sourceTree = ""; }; 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = Example/LaunchScreen.storyboard; sourceTree = ""; }; ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 0C80B921A6F3F58F76C31292 /* libPods-Example.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 13B07FAE1A68108700A75B9A /* Example */ = { isa = PBXGroup; children = ( 5DD804042DA11CD300D134D5 /* Example-Bridging-Header.h */, 13B07FB51A68108700A75B9A /* Images.xcassets */, 761780EC2CA45674006654EE /* AppDelegate.swift */, 13B07FB61A68108700A75B9A /* Info.plist */, 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */, 13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */, ); name = Example; sourceTree = ""; }; 2D16E6871FA4F8E400B85C8A /* Frameworks */ = { isa = PBXGroup; children = ( ED297162215061F000B7C4FE /* JavaScriptCore.framework */, 5DCACB8F33CDC322A6C60F78 /* libPods-Example.a */, ); name = Frameworks; sourceTree = ""; }; 832341AE1AAA6A7D00B99B32 /* Libraries */ = { isa = PBXGroup; children = ( ); name = Libraries; sourceTree = ""; }; 83CBB9F61A601CBA00E9B192 = { isa = PBXGroup; children = ( 13B07FAE1A68108700A75B9A /* Example */, 832341AE1AAA6A7D00B99B32 /* Libraries */, 83CBBA001A601CBA00E9B192 /* Products */, 2D16E6871FA4F8E400B85C8A /* Frameworks */, BBD78D7AC51CEA395F1C20DB /* Pods */, ); indentWidth = 2; sourceTree = ""; tabWidth = 2; usesTabs = 0; }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* Example.app */, ); name = Products; sourceTree = ""; }; BBD78D7AC51CEA395F1C20DB /* Pods */ = { isa = PBXGroup; children = ( 3B4392A12AC88292D35C810B /* Pods-Example.debug.xcconfig */, 5709B34CF0A7D63546082F79 /* Pods-Example.release.xcconfig */, ); path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 13B07F861A680F5B00A75B9A /* Example */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "Example" */; buildPhases = ( C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */, 13B07F871A680F5B00A75B9A /* Sources */, 13B07F8C1A680F5B00A75B9A /* Frameworks */, 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */, E235C05ADACE081382539298 /* [CP] Copy Pods Resources */, ); buildRules = ( ); dependencies = ( ); name = Example; productName = Example; productReference = 13B07F961A680F5B00A75B9A /* Example.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 83CBB9F71A601CBA00E9B192 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1210; TargetAttributes = { 13B07F861A680F5B00A75B9A = { LastSwiftMigration = 1120; }; }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "Example" */; compatibilityVersion = "Xcode 12.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 83CBB9F61A601CBA00E9B192; productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* Example */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */, 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, 7DEBBB6DE2ED1027D5165AD4 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( "$(SRCROOT)/.xcode.env.local", "$(SRCROOT)/.xcode.env", ); name = "Bundle React Native code and images"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\"\n"; }; 00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-Example-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-resources-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Copy Pods Resources"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-resources-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Example/Pods-Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 761780ED2CA45674006654EE /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-Example.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; ENABLE_BITCODE = NO; INFOPLIST_FILE = Example/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = Example; SWIFT_OBJC_BRIDGING_HEADER = "Example-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-Example.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = 1; INFOPLIST_FILE = Example/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; OTHER_LDFLAGS = ( "$(inherited)", "-ObjC", "-lc++", ); PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = Example; SWIFT_OBJC_BRIDGING_HEADER = "Example-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); OTHER_LDFLAGS = ( "$(inherited)", " ", ); REACT_NATIVE_PATH = "${PODS_ROOT}/../../../../node_modules/react-native"; SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; USE_HERMES = true; }; name = Debug; }; 83CBBA211A601CBA00E9B192 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_CXX_LANGUAGE_STANDARD = "c++20"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = ""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 15.1; LD_RUNPATH_SEARCH_PATHS = ( /usr/lib/swift, "$(inherited)", ); LIBRARY_SEARCH_PATHS = ( "\"$(SDKROOT)/usr/lib/swift\"", "\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"", "\"$(inherited)\"", ); MTL_ENABLE_DEBUG_INFO = NO; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-DFOLLY_NO_CONFIG", "-DFOLLY_MOBILE=1", "-DFOLLY_USE_LIBCPP=1", "-DFOLLY_CFG_NO_COROUTINES=1", "-DFOLLY_HAVE_CLOCK_GETTIME=1", ); OTHER_LDFLAGS = ( "$(inherited)", " ", ); REACT_NATIVE_PATH = "${PODS_ROOT}/../../../../node_modules/react-native"; SDKROOT = iphoneos; USE_HERMES = true; VALIDATE_PRODUCT = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "Example" */ = { isa = XCConfigurationList; buildConfigurations = ( 13B07F941A680F5B00A75B9A /* Debug */, 13B07F951A680F5B00A75B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "Example" */ = { isa = XCConfigurationList; buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; } ================================================ FILE: examples/vanilla/ios/Example.xcodeproj/xcshareddata/xcschemes/Example.xcscheme ================================================ ================================================ FILE: examples/vanilla/ios/Example.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: examples/vanilla/ios/Podfile ================================================ # Resolve react_native_pods.rb with node to allow for hoisting require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, min_ios_version_supported prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] if linkage != nil Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green use_frameworks! :linkage => linkage.to_sym end target 'Example' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( installer, config[:reactNativePath], :mac_catalyst_enabled => false, # :ccache_enabled => true ) end end ================================================ FILE: examples/vanilla/jest.config.js ================================================ module.exports = { preset: 'react-native', }; ================================================ FILE: examples/vanilla/metro.config.js ================================================ const path = require('path'); const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = { watchFolders: [path.resolve(__dirname, '../../')], }; module.exports = mergeConfig(getDefaultConfig(__dirname), config); ================================================ FILE: examples/vanilla/package.json ================================================ { "name": "vanilla-example", "version": "6.0.0", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint .", "start": "react-native start", "test": "jest" }, "dependencies": { "react": "19.0.0", "react-native": "0.78.2", "react-native-performance": "^6.0.0" }, "devDependencies": { "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.25.0", "@react-native-community/cli": "15.0.1", "@react-native-community/cli-platform-android": "15.0.1", "@react-native-community/cli-platform-ios": "15.0.1", "@react-native/babel-preset": "0.78.2", "@react-native/eslint-config": "0.78.2", "@react-native/metro-config": "0.78.2", "@react-native/typescript-config": "0.78.2", "@types/jest": "^29.5.13", "@types/react": "^19.0.0", "@types/react-test-renderer": "^19.0.0", "eslint": "^8.19.0", "jest": "^29.6.3", "react-test-renderer": "19.0.0", "typescript": "5.0.4" }, "engines": { "node": ">=18" } } ================================================ FILE: examples/vanilla/tsconfig.json ================================================ { "extends": "@react-native/typescript-config/tsconfig.json" } ================================================ FILE: examples/web/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: examples/web/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ================================================ FILE: examples/web/package.json ================================================ { "name": "web-example", "version": "6.0.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.14.1", "@testing-library/react": "^12.0.0", "@testing-library/user-event": "^13.2.1", "@types/jest": "^27.0.1", "@types/node": "^16.7.13", "@types/react": "^17.0.20", "@types/react-dom": "^17.0.9", "isomorphic-performance": "^6.0.0", "react": "18.2.0", "react-dom": "18.2.0", "react-scripts": "5.0.1", "typescript": "5.0.4", "web-vitals": "^2.1.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: examples/web/public/index.html ================================================ React App
================================================ FILE: examples/web/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: examples/web/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: examples/web/src/App.css ================================================ .App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ================================================ FILE: examples/web/src/App.test.tsx ================================================ import React from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import App from './App'; test('renders App.render performance entry', async () => { render(); await waitFor(() => screen.getByText(/App\.render/i)); }); ================================================ FILE: examples/web/src/App.tsx ================================================ import React from 'react'; import logo from './logo.svg'; import './App.css'; import { performance, PerformanceObserver } from 'isomorphic-performance'; function App() { const [measures, setMeasures] = React.useState([]); React.useEffect(() => { performance.measure('App.render'); new PerformanceObserver(() => { setMeasures(performance.getEntriesByName('App.render')); }).observe({ type: 'measure', buffered: true }); }, []); return (
logo

Edit src/App.tsx and save to reload.

Learn React
    {measures.map((entry) => (
  • {entry.name}: {entry.duration.toFixed(1)}ms
  • ))}
); } export default App; ================================================ FILE: examples/web/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: examples/web/src/index.tsx ================================================ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( , document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: examples/web/src/react-app-env.d.ts ================================================ /// ================================================ FILE: examples/web/src/reportWebVitals.ts ================================================ import { ReportHandler } from 'web-vitals'; const reportWebVitals = (onPerfEntry?: ReportHandler) => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: examples/web/src/setupTests.ts ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: examples/web/tsconfig.json ================================================ { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"] } ================================================ FILE: lerna.json ================================================ { "version": "6.0.0", "useWorkspaces": true, "registry": "https://registry.npmjs.org", "npmClient": "yarn" } ================================================ FILE: package.json ================================================ { "private": true, "author": "Joel Arvidsson", "license": "MIT", "scripts": { "build": "yarn workspace react-native-performance prepare", "check-format": "prettier '{,packages/**/,examples/*/}*.{md,js,ts,tsx,json}' --check", "format": "prettier '{,packages/**/,examples/*/}*.{md,js,ts,tsx,json}' --write", "postinstall": "yarn build", "test": "yarn workspace react-native-performance test", "types": "tsc --noEmit" }, "workspaces": { "packages": [ "examples/*", "packages/*" ] }, "devDependencies": { "lerna": "^3.20.2", "prettier": "^2.4.1", "react": "19.0.0", "react-native": "0.78.2" }, "resolutions": { "@types/eslint": "^7.28.2", "@types/node": "*", "@types/react": "^18.0.24" }, "packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610" } ================================================ FILE: packages/isomorphic-performance/README.md ================================================ # Isomorphic Performance Isomorphic Performance API for Node, Browser & React Native. Useful if your app targets both web and native. ## Installation ```bash yarn add react-native-performance isomorphic-performance ``` ## Usage ```js import { performance, PerformanceObserver } from 'isomorphic-performance'; performance.mark('myMark'); ``` ## License MIT © Joel Arvidsson 2021 – present ================================================ FILE: packages/isomorphic-performance/package.json ================================================ { "name": "isomorphic-performance", "version": "6.0.0", "description": "Isomorphic Performance API for Node, Browser & React Native", "homepage": "https://github.com/oblador/react-native-performance", "repository": { "type": "git", "url": "https://github.com/oblador/react-native-performance.git" }, "main": "src/node.js", "browser": "src/browser.js", "react-native": "src/react-native.js", "types": "src/types.d.ts", "files": [ "src" ], "peerDependencies": { "react-native-performance": "*" }, "devDependencies": { "typescript": "5.0.4" }, "keywords": [ "performance", "perf", "react-native", "node", "browser", "benchmark" ], "author": "Joel Arvidsson", "license": "MIT" } ================================================ FILE: packages/isomorphic-performance/src/browser.js ================================================ const g = typeof globalThis === 'undefined' ? window : globalThis; module.exports = { PerformanceObserver: g.PerformanceObserver, performance: g.performance, }; ================================================ FILE: packages/isomorphic-performance/src/node.js ================================================ const { performance } = require('perf_hooks'); const { createPerformance, } = require('react-native-performance/lib/commonjs/performance'); module.exports = createPerformance(performance.now.bind(performance)); ================================================ FILE: packages/isomorphic-performance/src/react-native.js ================================================ export { default as performance, PerformanceObserver, } from 'react-native-performance'; ================================================ FILE: packages/isomorphic-performance/src/types.d.ts ================================================ export { PerformanceObserver }; export const performance: Performance; ================================================ FILE: packages/isomorphic-performance/tsconfig.json ================================================ { "extends": "../../tsconfig.json", "compilerOptions": { "target": "es2015", "module": "es2015", "lib": ["es2015", "dom"] } } ================================================ FILE: packages/react-native-performance/README.md ================================================ # React Native Performance API This is an implementation of the [`Performance` API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) for React Native based on the [User Timing Level 3](https://www.w3.org/TR/user-timing-3/) and [Performance Timeline Level 2](https://www.w3.org/TR/performance-timeline-2/) drafts. _Note_: The timestamps used are high resolution (fractions of milliseconds) and monotonically increasing, meaning that they are independent of system clock adjustments. To convert a performance timestamp to a unix epoch timestamp do like this: ```js const timestamp = Date.now() - performance.timeOrigin + entry.startTime; ``` ## Installation **Yarn**: `yarn add --dev react-native-performance` **NPM**: `npm install --save-dev react-native-performance` ### Manual integration If your project is not set up with autolinking you need to link manually. #### iOS Add the following to your `Podfile` and run `pod install`: ```ruby pod 'react-native-performance', :path => '../node_modules/react-native-performance/ios' ``` ## Usage See [`examples/vanilla`](https://github.com/oblador/react-native-performance/tree/master/examples/vanilla) for a demo of the different features. ### Basic measure example Marking timeline events, measuring the duration between them and fetching these entries [works just like on the web](https://developer.mozilla.org/en-US/docs/Web/API/Performance): ```js import performance from 'react-native-performance'; performance.mark('myMark'); performance.measure('myMeasure', 'myMark'); performance.getEntriesByName('myMeasure'); -> [{ name: "myMeasure", entryType: "measure", startTime: 98, duration: 123 }] ``` ### Meta data If you want to add some additional details to your measurements or marks, you may pass a second options object argument with a `detail` entry per the [User Timing Level 3](https://www.w3.org/TR/user-timing-3/) draft: ```js import performance from 'react-native-performance'; performance.mark('myMark', { detail: { screen: 'settings', ... } }); performance.measure('myMeasure', { start: 'myMark', detail: { category: 'render', ... } }); performance.getEntriesByType('measure'); -> [{ name: "myMeasure", entryType: "measure", startTime: 98, duration: 123, detail: { ... } }] ``` ### Subscribing to entries The `PerformanceObserver` API enables subscribing to different types of performance entries. The handler is called in batches. Passing `buffered: true` would include entries produced before the `observe()` call which is useful to delay handing of measurements until after performance critical startup processing. ```js import { PerformanceObserver } from 'react-native-performance'; const measureObserver = new PerformanceObserver((list, observer) => { list.getEntries().forEach((entry) => { console.log(`${entry.name} took ${entry.duration}ms`); }); }); measureObserver.observe({ type: 'measure', buffered: true }); ``` ### Network resources Resource logging is disabled by default and currently will only cover `fetch`/`XMLHttpRequest` uses. ```js import performance, { setResourceLoggingEnabled, } from 'react-native-performance'; setResourceLoggingEnabled(true); await fetch('https://domain.com'); performance.getEntriesByType('resource'); -> [{ name: "https://domain.com", entryType: "resource", startTime: 98, duration: 123, initiatorType: "xmlhttprequest", // fetch is a polyfill on top of XHR in react-native fetchStart: 98, responseEnd: 221, transferSize: 456, ... }] ``` ### Custom metrics If you want to collect custom metrics not based on time, this module provides an extension of the `Performance` API called `.metric()` that produces entries with the type `metric`. ```js import performance from 'react-native-performance'; performance.metric('myMetric', 123); performance.getEntriesByType('metric'); -> [{ name: "myMetric", entryType: "metric", startTime: 98, duration: 0, value: 123 }] ``` ### Native marks This library exposes a set of native timeline events and metrics such as native app startup time, script execution time etc under the entryType `react-native-mark`. To install the native iOS dependency required, simply run `pod install` in `ios/` directory and rebuild the project. For android it should be enough by just rebuilding. If you wish to _opt out_ of autolinking of the native dependency, you may create or alter the `react-native.config.js` file to look something like this: ```js // react-native.config.js module.exports = { dependencies: { 'react-native-performance': { platforms: { android: null, ios: null, }, }, }, }; ``` Note that the native marks are not available immediately upon creation of the JS context, so it's best to set up an observer for the relevant end event before making measurements. ```js import performance, { PerformanceObserver } from 'react-native-performance'; new PerformanceObserver((list, observer) => { if (list.getEntries().find((entry) => entry.name === 'runJsBundleEnd')) { performance.measure('nativeLaunch', 'nativeLaunchStart', 'nativeLaunchEnd'); performance.measure('runJsBundle', 'runJsBundleStart', 'runJsBundleEnd'); } }).observe({ type: 'react-native-mark', buffered: true }); ``` #### Custom marks `ephemeral` is an optional parameter to `mark/metric` functions which if set to `NO/false` will retain the entries when the React Native bridge is (re)loaded. ##### iOS ```objc #import [RNPerformance.sharedInstance mark:@"myCustomMark"]; [RNPerformance.sharedInstance mark:@"myCustomMark" detail:@{ @"extra": @"info" }]; [RNPerformance.sharedInstance mark:@"myCustomMark" ephemeral:NO]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123)]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123) detail:@{ @"unit": @"ms" }]; [RNPerformance.sharedInstance metric:@"myCustomMetric" value:@(123) ephemeral:NO]; ``` ##### Android ```java import com.oblador.performance.RNPerformance; RNPerformance.getInstance().mark("myCustomMark"); RNPerformance.getInstance().mark("myCustomMark", false); // ephermal flag to disable resetOnReload Bundle bundle = new Bundle(); bundle.putString("extra", "info"); RNPerformance.getInstance().mark("myCustomMark", bundle); // Bundle to pass some detail payload RNPerformance.getInstance().metric("myCustomMetric", 123); RNPerformance.getInstance().metric("myCustomMetric", 123, false); // ephermal flag to disable resetOnReload Bundle bundle = new Bundle(); bundle.putString("unit", "ms"); RNPerformance.getInstance().metric("myCustomMetric", 123, bundle); // Bundle to pass some detail payload ``` #### Supported marks | Name | Platforms | Description | | ------------------------------------- | --------- | --------------------------------------------------------------------------- | | `nativeLaunchStart` | Both | Native process initialization started | | `nativeLaunchEnd` | Both | Native process initialization ended | | `downloadStart` | Both | **Only available in development.** Development bundle download started | | `downloadEnd` | Both | **Only available in development.** Development bundle download ended | | `runJsBundleStart` | Both | **Not available with debugger.** Parse and execution of the bundle started. | | `runJsBundleEnd` | Both | **Not available with debugger.** Parse and execution of the bundle ended | | `contentAppeared` | Both | Initial component mounted and presented to the user. | | `bridgeSetupStart` | Both | | | `bridgeSetupEnd` | iOS | | | `reactContextThreadStart` | Android | | | `reactContextThreadEnd` | Android | | | `vmInit` | Android | | | `createReactContextStart` | Android | | | `processCoreReactPackageStart` | Android | | | `processCoreReactPackageEnd` | Android | | | `buildNativeModuleRegistryStart` | Android | | | `buildNativeModuleRegistryEnd` | Android | | | `createCatalystInstanceStart` | Android | | | `createCatalystInstanceEnd` | Android | | | `preRunJsBundleStart` | Android | | | `createReactContextEnd` | Android | | | `preSetupReactContextStart` | Android | | | `preSetupReactContextEnd` | Android | | | `setupReactContextStart` | Android | | | `attachMeasuredRootViewsStart` | Android | | | `createUiManagerModuleStart` | Android | | | `createViewManagersStart` | Android | | | `createViewManagersEnd` | Android | | | `createUiManagerModuleConstantsStart` | Android | | | `createUiManagerModuleConstantsEnd` | Android | | | `createUiManagerModuleEnd` | Android | | | `attachMeasuredRootViewsEnd` | Android | | | `setupReactContextEnd` | Android | | ## License MIT © Joel Arvidsson 2021 – present ================================================ FILE: packages/react-native-performance/android/.gitignore ================================================ /build /.idea/ /.gradle/ /local.properties ================================================ FILE: packages/react-native-performance/android/build.gradle ================================================ import java.nio.file.Paths buildscript { if (project == rootProject) { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:7.0.4' } } } static def findNodeModules(baseDir) { def basePath = baseDir.toPath().normalize() // Node's module resolution algorithm searches up to the root directory, // after which the base path will be null while (basePath) { def nodeModulesPath = Paths.get(basePath.toString(), "node_modules") def reactNativePath = Paths.get(nodeModulesPath.toString(), "react-native") if (nodeModulesPath.toFile().exists() && reactNativePath.toFile().exists()) { return nodeModulesPath.toString() } basePath = basePath.getParent() } throw new GradleException("Unable to locate node_modules") } def isNewArchitectureEnabled() { // To opt-in for the New Architecture, you can either: // - Set `newArchEnabled` to true inside the `gradle.properties` file // - Invoke gradle with `-newArchEnabled=true` // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true` return rootProject.hasProperty("newArchEnabled") && rootProject.newArchEnabled == "true" } if (isNewArchitectureEnabled()) { apply plugin: 'com.facebook.react' } apply plugin: 'com.android.library' def safeExtGet(prop, fallback) { rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback } def nodeModules = findNodeModules(projectDir) android { compileSdkVersion safeExtGet('compileSdkVersion', 31) buildToolsVersion safeExtGet('buildToolsVersion', "31.0.0") def agpVersion = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')[0].toInteger() if (agpVersion >= 7) { namespace 'com.oblador.performance' } defaultConfig { minSdkVersion safeExtGet('minSdkVersion', 21) targetSdkVersion safeExtGet('targetSdkVersion', 31) buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() if (isNewArchitectureEnabled()) { var appProject = rootProject.allprojects.find {it.plugins.hasPlugin('com.android.application')} externalNativeBuild { ndkBuild { arguments "APP_PLATFORM=android-21", "APP_STL=c++_shared", "NDK_TOOLCHAIN_VERSION=clang", "GENERATED_SRC_DIR=${appProject.buildDir}/generated/source", "PROJECT_BUILD_DIR=${appProject.buildDir}", "REACT_ANDROID_DIR=${nodeModules}/react-native/ReactAndroid", "REACT_ANDROID_BUILD_DIR=${nodeModules}/react-native/ReactAndroid/build" cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1" cppFlags "-std=c++17" targets "rnperformance_modules" } } } } if (agpVersion < 8) { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } } repositories { if (project == rootProject) { repositories { maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("${nodeModules}/react-native/android") } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() maven { url 'https://www.jitpack.io' } } } } dependencies { implementation 'com.facebook.react:react-native:+' } ================================================ FILE: packages/react-native-performance/android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: packages/react-native-performance/android/gradle.properties ================================================ android.useAndroidX=true ================================================ FILE: packages/react-native-performance/android/src/main/AndroidManifest.xml ================================================ ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/PerformanceEntry.java ================================================ package com.oblador.performance; import android.os.Bundle; abstract class PerformanceEntry { protected String name; protected long startTime; protected boolean ephemeral = true; protected Bundle detail = null; protected String getName() { return name; } protected long getStartTime() { return startTime; } protected boolean isEphemeral() { return ephemeral; } protected Bundle getDetail() { return detail; } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/PerformanceMark.java ================================================ package com.oblador.performance; import android.os.Bundle; class PerformanceMark extends PerformanceEntry { protected PerformanceMark(String name, long startTime) { this(name, startTime, true); } protected PerformanceMark(String name, long startTime, boolean ephemeral) { this(name, startTime, ephemeral, null); } protected PerformanceMark(String name, long startTime, Bundle detail) { this(name, startTime, true, detail); } protected PerformanceMark(String name, long startTime, boolean ephemeral, Bundle detail) { this.name = name; this.startTime = startTime; this.ephemeral = ephemeral; this.detail = detail; } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/PerformanceMetric.java ================================================ package com.oblador.performance; import android.os.Bundle; class PerformanceMetric extends PerformanceEntry { private final double value; protected PerformanceMetric(String name, double value, long startTime) { this(name, value, startTime, true); } protected PerformanceMetric(String name, double value, long startTime, boolean ephemeral) { this(name, value, startTime, ephemeral, null); } protected PerformanceMetric(String name, double value, long startTime, Bundle detail) { this(name, value, startTime, true, detail); } protected PerformanceMetric(String name, double value, long startTime, boolean ephemeral, Bundle detail) { this.name = name; this.value = value; this.startTime = startTime; this.ephemeral = ephemeral; this.detail = detail; } protected double getValue() { return value; } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/PerformanceModule.java ================================================ package com.oblador.performance; import android.os.SystemClock; import androidx.annotation.NonNull; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; // Should extend NativeRNPerformanceManagerSpec when codegen for old architecture is solved public class PerformanceModule extends ReactContextBaseJavaModule implements TurboModule, RNPerformance.MarkerListener { public static final String PERFORMANCE_MODULE = "RNPerformanceManager"; public static final String BRIDGE_SETUP_START = "bridgeSetupStart"; private static boolean eventsBuffered = true; private static final Queue markBuffer = new ConcurrentLinkedQueue<>(); private static boolean didEmit = false; private static final ReactMarker.MarkerListener startupMarkerListener = (name, tag, instanceKey) -> { switch (name) { case RELOAD: clearMarkBuffer(); addMark(new PerformanceMark(BRIDGE_SETUP_START, SystemClock.uptimeMillis())); break; case ATTACH_MEASURED_ROOT_VIEWS_END: case ATTACH_MEASURED_ROOT_VIEWS_START: case BUILD_NATIVE_MODULE_REGISTRY_END: case BUILD_NATIVE_MODULE_REGISTRY_START: case CONTENT_APPEARED: case CREATE_CATALYST_INSTANCE_END: case CREATE_CATALYST_INSTANCE_START: case CREATE_REACT_CONTEXT_END: case CREATE_REACT_CONTEXT_START: case CREATE_UI_MANAGER_MODULE_CONSTANTS_END: case CREATE_UI_MANAGER_MODULE_CONSTANTS_START: case CREATE_UI_MANAGER_MODULE_END: case CREATE_UI_MANAGER_MODULE_START: case CREATE_VIEW_MANAGERS_END: case CREATE_VIEW_MANAGERS_START: case DOWNLOAD_END: case DOWNLOAD_START: case LOAD_REACT_NATIVE_SO_FILE_END: case LOAD_REACT_NATIVE_SO_FILE_START: case PRE_RUN_JS_BUNDLE_START: case PRE_SETUP_REACT_CONTEXT_END: case PRE_SETUP_REACT_CONTEXT_START: case PROCESS_CORE_REACT_PACKAGE_END: case PROCESS_CORE_REACT_PACKAGE_START: case REACT_CONTEXT_THREAD_END: case REACT_CONTEXT_THREAD_START: case RUN_JS_BUNDLE_END: case RUN_JS_BUNDLE_START: case SETUP_REACT_CONTEXT_END: case SETUP_REACT_CONTEXT_START: case VM_INIT: long startTime = SystemClock.uptimeMillis(); addMark(new PerformanceMark(getMarkName(name), startTime)); break; } }; private final ReactMarker.MarkerListener contentAppearedListener = (name, tag, instanceKey) -> { switch (name) { case CONTENT_APPEARED: eventsBuffered = false; emitNativeStartupTime(); emitBufferedMarks(); break; case RELOAD: eventsBuffered = true; break; } }; public PerformanceModule(@NonNull final ReactApplicationContext reactContext) { super(reactContext); setupMarkerListener(); setupNativeMarkerListener(); } private void setupMarkerListener() { ReactMarker.addListener( contentAppearedListener ); } private void setupNativeMarkerListener() { RNPerformance.getInstance().addListener(this); } // Need to set up the marker listener before the react module is initialized // to capture all events public static void setupListener() { ReactMarker.addListener(startupMarkerListener); } private static void clearMarkBuffer() { RNPerformance.getInstance().clearEphermalEntries(); Iterator iterator = markBuffer.iterator(); while (iterator.hasNext()) { PerformanceEntry entry = iterator.next(); if (entry.isEphemeral()) { iterator.remove(); } } } private static String getMarkName(ReactMarkerConstants name) { StringBuffer sb = new StringBuffer(); for (String s : name.toString().toLowerCase().split("_")) { if (sb.length() == 0) { sb.append(s); } else { sb.append(Character.toUpperCase(s.charAt(0))); if (s.length() > 1) { sb.append(s.substring(1, s.length())); } } } return sb.toString(); } @Override @NonNull public String getName() { return PERFORMANCE_MODULE; } private void emitNativeStartupTime() { safelyEmitMark(new PerformanceMark("nativeLaunchStart", StartTimeProvider.getStartTime())); safelyEmitMark(new PerformanceMark("nativeLaunchEnd", StartTimeProvider.getEndTime())); } private void safelyEmitMark(PerformanceEntry entry) { if (eventsBuffered) { addMark(entry); } else { emitMark(entry); } } private static void addMark(PerformanceEntry entry) { markBuffer.add(entry); } private void emitBufferedMarks() { didEmit = true; Iterator iterator = markBuffer.iterator(); while (iterator.hasNext()) { PerformanceEntry entry = iterator.next(); emitMark(entry); } emitNativeBufferedMarks(); } private void emitNativeBufferedMarks() { Iterator iterator = RNPerformance.getInstance().getEntries().iterator(); while (iterator.hasNext()) { PerformanceEntry entry = iterator.next(); emitMark(entry); } } private void emitMark(PerformanceEntry entry) { if (entry instanceof PerformanceMark) { emit((PerformanceMark) entry); } else if (entry instanceof PerformanceMetric) { emit((PerformanceMetric) entry); } } private void emit(PerformanceMetric metric) { WritableMap params = Arguments.createMap(); params.putString("name", metric.getName()); params.putDouble("startTime", metric.getStartTime()); params.putDouble("value", metric.getValue()); if (metric.getDetail() != null) { WritableMap map = Arguments.fromBundle(metric.getDetail()); params.putMap("detail", map); } if (getReactApplicationContext().hasActiveReactInstance()) { getReactApplicationContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("metric", params); } } private void emit(PerformanceMark mark) { WritableMap params = Arguments.createMap(); params.putString("name", mark.getName()); params.putDouble("startTime", mark.getStartTime()); if (mark.getDetail() != null) { WritableMap map = Arguments.fromBundle(mark.getDetail()); params.putMap("detail", map); } if (getReactApplicationContext().hasActiveReactInstance()) { getReactApplicationContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("mark", params); } } @Override public void logMarker(PerformanceEntry entry) { if (didEmit) { emitMark(entry); } } @Override public void invalidate() { super.invalidate(); RNPerformance.getInstance().removeListener(this); ReactMarker.removeListener(contentAppearedListener); } // Fix new arch runtime error public void addListener(String eventName) { } public void removeListeners(double count) { } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/PerformancePackage.java ================================================ package com.oblador.performance; import androidx.annotation.NonNull; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings("unused") public class PerformancePackage implements ReactPackage { public PerformancePackage() { PerformanceModule.setupListener(); } @Override @NonNull public List createNativeModules(@NonNull final ReactApplicationContext reactContext) { List modules = new ArrayList<>(); modules.add(new PerformanceModule(reactContext)); return modules; } @NonNull public List> createJSModules() { return Collections.emptyList(); } @Override @NonNull public List createViewManagers(@NonNull final ReactApplicationContext reactContext) { return Collections.emptyList(); } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/RNPerformance.java ================================================ package com.oblador.performance; import android.os.Bundle; import android.os.SystemClock; import androidx.annotation.NonNull; import com.facebook.proguard.annotations.DoNotStrip; import java.util.Iterator; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; public class RNPerformance { private RNPerformance() { } private static class LoadRNPerformance { static final RNPerformance instance = new RNPerformance(); } @NonNull public static RNPerformance getInstance() { return LoadRNPerformance.instance; } interface MarkerListener { void logMarker(PerformanceEntry entry); } private static final List sListeners = new CopyOnWriteArrayList<>(); private final Queue entries = new ConcurrentLinkedQueue<>(); @DoNotStrip protected void addListener(MarkerListener listener) { if (!sListeners.contains(listener)) { sListeners.add(listener); } } @DoNotStrip protected void removeListener(MarkerListener listener) { if (sListeners.contains(listener)) { sListeners.remove(listener); } } public void mark(@NonNull String markName) { mark(markName, true); } public void mark(@NonNull String markName, boolean ephemeral) { mark(markName, null, ephemeral); } public void mark(@NonNull String markName, Bundle detail) { mark(markName, detail, true); } public void mark(@NonNull String markName, Bundle detail, boolean ephemeral) { PerformanceEntry mark = new PerformanceMark( markName, SystemClock.uptimeMillis(), ephemeral, detail ); addEntry(mark); } public void metric(@NonNull String metricName, double value) { metric(metricName, value, true); } public void metric(@NonNull String metricName, double value, boolean ephemeral) { metric(metricName, value, null, ephemeral); } public void metric(@NonNull String metricName, double value, Bundle detail) { metric(metricName, value, detail, true); } public void metric( @NonNull String metricName, double value, Bundle detail, boolean ephemeral ) { PerformanceEntry mark = new PerformanceMetric( metricName, value, SystemClock.uptimeMillis(), ephemeral, detail ); addEntry(mark); } private void addEntry(@NonNull PerformanceEntry mark) { entries.add(mark); emitMark(mark); } private void emitMark(@NonNull PerformanceEntry entry) { for (MarkerListener listener : sListeners) { listener.logMarker(entry); } } protected @NonNull Queue getEntries() { return entries; } protected void clearEntries() { entries.clear(); } protected void clearEntries(String name) { Iterator iterator = entries.iterator(); while (iterator.hasNext()) { PerformanceEntry entry = iterator.next(); if (entry.getName().equals(name)) { iterator.remove(); } } } protected void clearEphermalEntries() { if (sListeners.isEmpty()) { return; } Iterator iterator = entries.iterator(); while (iterator.hasNext()) { PerformanceEntry entry = iterator.next(); if (entry.isEphemeral()) { iterator.remove(); } } } } ================================================ FILE: packages/react-native-performance/android/src/main/java/com/oblador/performance/StartTimeProvider.java ================================================ package com.oblador.performance; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Process; import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class StartTimeProvider extends ContentProvider { private static long startTime = 0; private static long endTime = 0; public static long getStartTime() { return startTime; } public static long getEndTime() { return endTime; } private static void setStartTime() { if (startTime == 0) { startTime = endTime - Process.getElapsedCpuTime(); } } private static void setEndTime() { if (endTime == 0) { endTime = SystemClock.uptimeMillis(); } } @Override public boolean onCreate() { setEndTime(); setStartTime(); return false; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) { return null; } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { return 0; } } ================================================ FILE: packages/react-native-performance/babel.config.js ================================================ module.exports = { presets: ['module:@react-native/babel-preset'], }; ================================================ FILE: packages/react-native-performance/ios/RNPerformance.h ================================================ #import "RNPerformanceEntry.h" @interface RNPerformance: NSObject + (RNPerformance *_Nonnull)sharedInstance; - (void)mark:(nonnull NSString *)markName; - (void)mark:(nonnull NSString *)markName ephemeral:(BOOL)ephemeral; - (void)mark:(nonnull NSString *)markName detail:(nullable NSDictionary *)detail; - (void)mark:(nonnull NSString *)markName detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral; - (void)metric:(nonnull NSString *)metricName value:(nonnull NSNumber *)value; - (void)metric:(nonnull NSString *)metricName value:(nonnull NSNumber *)value ephemeral:(BOOL)ephemeral; - (void)metric:(nonnull NSString *)metricName value:(nonnull NSNumber *)value detail:(nullable NSDictionary *)detail; - (void)metric:(nonnull NSString *)metricName value:(nonnull NSNumber *)value detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral; - (NSArray*_Nonnull)getEntries; - (void)clearEntries; - (void)clearEntries:(nonnull NSString *)name; - (void)clearEphemeralEntries; @end ================================================ FILE: packages/react-native-performance/ios/RNPerformance.mm ================================================ #import "RNPerformance.h" #import "RNPerformanceEntry.h" #import "RNPerformanceUtils.h" NSString *const RNPerformanceEntryWasAddedNotification = @"RNPerformanceEntryWasAdded"; @implementation RNPerformance { NSMutableArray *_entries; } static RNPerformance *_sharedInstance = nil; + (RNPerformance *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sharedInstance = [[self alloc] init]; }); return _sharedInstance; } - (id)init { if (self = [super init]) { _entries = [NSMutableArray new]; } return self; } - (void)mark:(nonnull NSString *)name { [self mark:name detail:nil]; } - (void)mark:(nonnull NSString *)name ephemeral:(BOOL)ephemeral { [self mark:name detail:nil ephemeral:ephemeral]; } - (void)mark:(nonnull NSString *)name detail:(nullable NSDictionary *)detail { [self mark:name detail:detail ephemeral:YES]; } - (void)mark:(nonnull NSString *)name detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral { RNPerformanceMark *mark = [[RNPerformanceMark alloc] initWithName:name startTime:RNPerformanceGetTimestamp() detail:detail ephemeral:ephemeral]; [self addEntry:mark]; } - (void)metric:(nonnull NSString *)name value:(nonnull NSNumber *)value { [self metric:name value:value detail:nil]; } - (void)metric:(nonnull NSString *)name value:(nonnull NSNumber *)value ephemeral:(BOOL)ephemeral { [self metric:name value:value detail:nil ephemeral:ephemeral]; } - (void)metric:(nonnull NSString *)name value:(nonnull NSNumber *)value detail:(nullable NSDictionary *)detail { [self metric:name value:value detail:detail ephemeral:YES]; } - (void)metric:(nonnull NSString *)name value:(nonnull NSNumber *)value detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral { RNPerformanceMetric *metric = [[RNPerformanceMetric alloc] initWithName:name value:value startTime:RNPerformanceGetTimestamp() detail:detail ephemeral:ephemeral]; [self addEntry:metric]; } - (void)addEntry:(nonnull RNPerformanceEntry *)entry { [_entries addObject:entry]; NSNotification *notification = [[NSNotification alloc] initWithName:RNPerformanceEntryWasAddedNotification object:nil userInfo:@{ @"entry": entry }]; [NSNotificationCenter.defaultCenter postNotification:notification]; } - (NSArray*)getEntries { return [[NSArray alloc] initWithArray:_entries]; } - (void)clearEntries { [_entries removeAllObjects]; } - (void)clearEntries:(nonnull NSString *)name { [_entries enumerateObjectsUsingBlock:^(RNPerformanceEntry * _Nonnull entry, NSUInteger idx, BOOL * _Nonnull stop) { if([entry.name isEqualToString:name]) { [_entries removeObject:entry]; } }]; } - (void)clearEphemeralEntries { [_entries enumerateObjectsUsingBlock:^(RNPerformanceEntry * _Nonnull entry, NSUInteger idx, BOOL * _Nonnull stop) { if(entry.ephemeral) { [_entries removeObject:entry]; } }]; } @end ================================================ FILE: packages/react-native-performance/ios/RNPerformanceEntry.h ================================================ #import typedef enum EntryType : NSUInteger { kMark, kMetric } EntryType; @interface RNPerformanceEntry: NSObject @property (nonatomic, copy, readonly) NSString * _Nonnull name; @property (nonatomic, assign, readonly) EntryType type; @property (nonatomic, assign, readonly) int64_t startTime; @property (nonatomic, assign, readonly) BOOL ephemeral; @property (nonatomic, copy, readonly) NSDictionary * _Nullable detail; @end @interface RNPerformanceMark: RNPerformanceEntry - (id)initWithName:(nonnull NSString *)name startTime:(int64_t)startTime detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral; @end @interface RNPerformanceMetric: RNPerformanceEntry @property (nonatomic, copy, readonly) NSNumber * _Nonnull value; - (id)initWithName:(nonnull NSString *)name value:(nonnull NSNumber *)value startTime:(int64_t)startTime detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral; @end ================================================ FILE: packages/react-native-performance/ios/RNPerformanceEntry.m ================================================ #import "RNPerformanceEntry.h" @implementation RNPerformanceEntry - (id)initWithName:(nonnull NSString *)name type:(EntryType)type startTime:(int64_t)startTime detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral { if (self = [super init]) { _name = name; _type = type; _startTime = startTime; _detail = detail; _ephemeral = ephemeral; } return self; } @end @implementation RNPerformanceMark - (id)initWithName:(nonnull NSString *)name startTime:(int64_t)startTime detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral { self = [super initWithName:name type:kMark startTime:startTime detail:detail ephemeral:ephemeral]; return self; } @end @implementation RNPerformanceMetric - (id)initWithName:(nonnull NSString *)name value:(nonnull NSNumber *)value startTime:(int64_t)startTime detail:(nullable NSDictionary *)detail ephemeral:(BOOL)ephemeral { if (self = [super initWithName:name type:kMetric startTime:startTime detail:detail ephemeral:ephemeral]) { _value = value; } return self; } @end ================================================ FILE: packages/react-native-performance/ios/RNPerformanceManager.h ================================================ #import #import #import @interface RNPerformanceManager : RCTEventEmitter @end ================================================ FILE: packages/react-native-performance/ios/RNPerformanceManager.mm ================================================ #import "RNPerformanceManager.h" #import "RNPerformance.h" #import #import #import #import #import #import "RNPerformanceUtils.h" #ifdef RCT_NEW_ARCH_ENABLED #import #endif static int64_t sNativeLaunchStart; static int64_t sNativeLaunchEnd; using namespace facebook::react; @implementation RNPerformanceManager { bool hasListeners; bool didEmit; int64_t contentAppeared; } RCT_EXPORT_MODULE(); + (void) initialize { [super initialize]; struct timespec tp; clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp); sNativeLaunchEnd = RNPerformanceGetTimestamp(); sNativeLaunchStart = sNativeLaunchEnd - (tp.tv_sec * 1e3 + tp.tv_nsec / 1e6); } - (instancetype)init { if (self = [super init]) { hasListeners = NO; didEmit = NO; contentAppeared = -1; } return self; } - (void)setBridge:(RCTBridge *)bridge { [super setBridge:bridge]; [RNPerformance.sharedInstance clearEphemeralEntries]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentAppeared) name:RCTContentDidAppearNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emitIfReady) name:RCTJavaScriptDidLoadNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customEntryWasAdded:) name:RNPerformanceEntryWasAddedNotification object:nil]; } - (BOOL)isReady { return contentAppeared != -1 && !std::isnan(ReactMarker::StartupLogger::getInstance().getRunJSBundleEndTime()); } - (void) contentAppeared { contentAppeared = RNPerformanceGetTimestamp(); [self emitIfReady]; } - (void)emitIfReady { if (!didEmit && hasListeners && [self isReady]) { [self emitEntries]; } } - (void)customEntryWasAdded:(NSNotification *)notification { if(didEmit == YES) { [self emitEntry:notification.userInfo[@"entry"]]; } } - (void)emitEntries { didEmit = YES; [self emitMarkNamed:@"nativeLaunchStart" withStartTime:sNativeLaunchStart]; [self emitMarkNamed:@"nativeLaunchEnd" withStartTime:sNativeLaunchEnd]; [self emitMarkNamed:@"runJsBundleStart" withMediaTime:ReactMarker::StartupLogger::getInstance().getRunJSBundleStartTime()]; [self emitMarkNamed:@"runJsBundleEnd" withMediaTime:ReactMarker::StartupLogger::getInstance().getRunJSBundleEndTime()]; [self emitMarkNamed:@"appStartupStart" withMediaTime:ReactMarker::StartupLogger::getInstance().getAppStartupStartTime()]; [self emitMarkNamed:@"appStartupEnd" withMediaTime:ReactMarker::StartupLogger::getInstance().getAppStartupEndTime()]; [self emitMarkNamed:@"initReactRuntimeStart" withMediaTime:ReactMarker::StartupLogger::getInstance().getInitReactRuntimeStartTime()]; [self emitMarkNamed:@"initReactRuntimeEnd" withMediaTime:ReactMarker::StartupLogger::getInstance().getInitReactRuntimeEndTime()]; [self emitMarkNamed:@"contentAppeared" withStartTime:contentAppeared]; [self emitMetricNamed:@"bundleSize" withValue:@([self.bridge.performanceLogger valueForTag:RCTPLBundleSize]) withStartTime:RNPerformanceGetTimestamp() withDetail:@{ @"unit": @"byte" }]; [[RNPerformance.sharedInstance getEntries] enumerateObjectsUsingBlock:^(RNPerformanceEntry * _Nonnull entry, NSUInteger idx, BOOL * _Nonnull stop) { [self emitEntry:entry]; }]; } - (void)emitEntry:(nonnull RNPerformanceEntry *)entry { switch (entry.type) { case kMark: [self emitMarkNamed:entry.name withStartTime:entry.startTime withDetail:entry.detail]; break; case kMetric: RNPerformanceMetric *metric = (RNPerformanceMetric *)entry; [self emitMetricNamed:metric.name withValue:metric.value withStartTime:metric.startTime withDetail:metric.detail]; break; } } - (NSArray *)supportedEvents { return @[ @"mark", @"metric" ]; } - (void)invalidate { [super invalidate]; [NSNotificationCenter.defaultCenter removeObserver:self]; } - (void)startObserving { hasListeners = YES; if (didEmit != YES && [self isReady]) { [self emitEntries]; } } -(void)stopObserving { hasListeners = NO; } - (void)emitMarkNamed:(NSString *)name withMediaTime:(int64_t)mediaTime { if (mediaTime == 0) { NSLog(@"Ignoring mark named %@ as timestamp is not set", name); return; } [self emitMarkNamed:name withStartTime:mediaTime + RNPerformanceGetTimestamp() - (CACurrentMediaTime() * 1000)]; } - (void)emitMarkNamed:(NSString *)name withStartTime:(int64_t)startTime { [self emitMarkNamed:name withStartTime:startTime withDetail:nil]; } - (void)emitMarkNamed:(NSString *)name withStartTime:(int64_t)startTime withDetail:(NSDictionary *)detail { if (hasListeners) { [self sendEventWithName:@"mark" body:@{ @"name": name, @"startTime": @(startTime), @"detail": detail == nil ? [NSNull null] : detail }]; } } - (void)emitMetricNamed:(NSString *)name withValue:(NSNumber *)value withStartTime:(int64_t)startTime withDetail:(NSDictionary *)detail { if (hasListeners) { [self sendEventWithName:@"metric" body:@{ @"name": name, @"startTime": @(startTime), @"value": value, @"detail": detail == nil ? [NSNull null] : detail }]; } } #ifdef RCT_NEW_ARCH_ENABLED - (std::shared_ptr)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params { return std::make_shared(params); } #endif @end ================================================ FILE: packages/react-native-performance/ios/RNPerformanceUtils.h ================================================ #ifndef RNPerformanceUtils_h #define RNPerformanceUtils_h #import RCT_EXTERN NSString * _Nonnull const RNPerformanceEntryWasAddedNotification; #include static int64_t RNPerformanceGetTimestamp() { // Copied from https://github.com/facebook/react-native/blob/main/React/CxxBridge/RCTJSIExecutorRuntimeInstaller.mm#L25 auto time = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast( time.time_since_epoch()) .count(); constexpr double NANOSECONDS_IN_MILLISECOND = 1000000.0; return duration / NANOSECONDS_IN_MILLISECOND; } #endif /* RNPerformanceUtils_h */ ================================================ FILE: packages/react-native-performance/jest.config.js ================================================ module.exports = { setupFilesAfterEnv: ['./test/setup.js'], preset: 'react-native', }; ================================================ FILE: packages/react-native-performance/package.json ================================================ { "name": "react-native-performance", "version": "6.0.0", "description": "Measure React Native performance", "homepage": "https://github.com/oblador/react-native-performance", "repository": { "type": "git", "url": "https://github.com/oblador/react-native-performance.git", "directory": "packages/react-native-performance" }, "main": "lib/commonjs/index.js", "types": "lib/typescript/index.d.ts", "react-native": "src/index.ts", "source": "src/index", "files": [ "src", "lib", "!**/__tests__", "!**/__fixtures__", "!**/__mocks__", "android", "ios", "react-native-performance.*", "!.DS_Store", "!android/build", "!ios/build" ], "scripts": { "test": "jest", "prepare": "bob build" }, "keywords": [ "react-native", "performance", "perf", "benchmark" ], "author": "Joel Arvidsson", "license": "MIT", "peerDependencies": { "react-native": "*" }, "devDependencies": { "@babel/core": "^7.25.2", "@babel/preset-env": "^7.25.3", "@babel/runtime": "^7.25.0", "@react-native/babel-preset": "0.78.2", "@types/jest": "^29.5.13", "babel-jest": "^29.6.3", "jest": "^29.6.3", "react-native-builder-bob": "^0.21.2", "typescript": "5.0.4" }, "codegenConfig": { "name": "RNPerformanceSpec", "type": "modules", "jsSrcsDir": "./src", "android": { "javaPackageName": "com.oblador.performance" } }, "react-native-builder-bob": { "source": "src", "output": "lib", "targets": [ "commonjs", [ "typescript", { "project": "tsconfig.build.json" } ] ] } } ================================================ FILE: packages/react-native-performance/react-native-performance.podspec ================================================ require 'json' package = JSON.parse(File.read(File.join(__dir__, './package.json'))) folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32' Pod::Spec.new do |s| s.name = package['name'] s.version = package['version'] s.summary = package['description'] s.author = package['author'] s.homepage = package['homepage'] s.license = package['license'] s.source = { :git => 'https://github.com/oblador/react-native-performance.git', :tag => "v#{s.version}" } s.platform = :ios, "11.0" s.source_files = "ios/**/*.{h,m,mm}" s.dependency 'React-Core' # This guard prevent to install the dependencies when we run `pod install` in the old architecture. if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1" s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"", "CLANG_CXX_LANGUAGE_STANDARD" => "c++17" } install_modules_dependencies(s) end end ================================================ FILE: packages/react-native-performance/react-native-performance.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 93CE2D3B25AF808F00589E8F /* RNPerformanceManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 93CE2D3925AF808F00589E8F /* RNPerformanceManager.h */; }; 93CE2D3C25AF808F00589E8F /* RNPerformanceManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 93CE2D3925AF808F00589E8F /* RNPerformanceManager.h */; }; 93CE2D3D25AF808F00589E8F /* RNPerformanceManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 93CE2D3A25AF808F00589E8F /* RNPerformanceManager.m */; }; 93CE2D3E25AF808F00589E8F /* RNPerformanceManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 93CE2D3A25AF808F00589E8F /* RNPerformanceManager.m */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 5D82366D1B0CE05B005A9EF3 /* Copy Headers */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = "include/$(PRODUCT_NAME)"; dstSubfolderSpec = 16; files = ( ); name = "Copy Headers"; runOnlyForDeploymentPostprocessing = 0; }; 6478985D1F38BF9100DA1C12 /* Copy Headers */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = "include/$(PRODUCT_NAME)"; dstSubfolderSpec = 16; files = ( ); name = "Copy Headers"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 93CE2D3925AF808F00589E8F /* RNPerformanceManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RNPerformanceManager.h; sourceTree = ""; }; 93CE2D3A25AF808F00589E8F /* RNPerformanceManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RNPerformanceManager.m; sourceTree = ""; }; 93CE2D7425AF810600589E8F /* libreact-native-performance.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libreact-native-performance.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 93CE2D7C25AF815700589E8F /* lib.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; name = lib.a; path = "/Users/joel.arvidsson/Code/flipper-plugin-react-native-performance/packages/react-native-performance/ios/build/Debug-appletvos/lib.a"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 5D82366C1B0CE05B005A9EF3 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 6478985C1F38BF9100DA1C12 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 5D8236661B0CE05B005A9EF3 = { isa = PBXGroup; children = ( 93B250D4256EA09C007CC95B /* RNPerformanceManager */, 93CE2D7425AF810600589E8F /* libreact-native-performance.a */, ); sourceTree = ""; wrapsLines = 0; }; 93B250D4256EA09C007CC95B /* RNPerformanceManager */ = { isa = PBXGroup; children = ( 93CE2D3925AF808F00589E8F /* RNPerformanceManager.h */, 93CE2D3A25AF808F00589E8F /* RNPerformanceManager.m */, ); name = RNPerformanceManager; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ 5DE632D820434281004F9598 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 93CE2D3B25AF808F00589E8F /* RNPerformanceManager.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; 5DE632DD204342BC004F9598 /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( 93CE2D3C25AF808F00589E8F /* RNPerformanceManager.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXHeadersBuildPhase section */ /* Begin PBXNativeTarget section */ 5D82366E1B0CE05B005A9EF3 /* react-native-performance */ = { isa = PBXNativeTarget; buildConfigurationList = 5D8236831B0CE05B005A9EF3 /* Build configuration list for PBXNativeTarget "react-native-performance" */; buildPhases = ( 5D82366B1B0CE05B005A9EF3 /* Sources */, 5D82366C1B0CE05B005A9EF3 /* Frameworks */, 5DE632D820434281004F9598 /* Headers */, 5D82366D1B0CE05B005A9EF3 /* Copy Headers */, ); buildRules = ( ); dependencies = ( ); name = "react-native-performance"; productName = RNKeychain; productReference = 93CE2D7425AF810600589E8F /* libreact-native-performance.a */; productType = "com.apple.product-type.library.static"; }; 6478985E1F38BF9100DA1C12 /* react-native-performance-tvOS */ = { isa = PBXNativeTarget; buildConfigurationList = 647898671F38BF9100DA1C12 /* Build configuration list for PBXNativeTarget "react-native-performance-tvOS" */; buildPhases = ( 6478985B1F38BF9100DA1C12 /* Sources */, 6478985C1F38BF9100DA1C12 /* Frameworks */, 5DE632DD204342BC004F9598 /* Headers */, 6478985D1F38BF9100DA1C12 /* Copy Headers */, ); buildRules = ( ); dependencies = ( ); name = "react-native-performance-tvOS"; productName = "RNKeychain-tvOS"; productReference = 93CE2D7C25AF815700589E8F /* lib.a */; productType = "com.apple.product-type.library.static"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 5D8236671B0CE05B005A9EF3 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0630; ORGANIZATIONNAME = "Joel Arvidsson"; TargetAttributes = { 5D82366E1B0CE05B005A9EF3 = { CreatedOnToolsVersion = 6.3.1; }; 6478985E1F38BF9100DA1C12 = { CreatedOnToolsVersion = 8.3.3; ProvisioningStyle = Automatic; }; }; }; buildConfigurationList = 5D82366A1B0CE05B005A9EF3 /* Build configuration list for PBXProject "react-native-performance" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( English, en, ); mainGroup = 5D8236661B0CE05B005A9EF3; productRefGroup = 5D8236661B0CE05B005A9EF3; projectDirPath = ""; projectRoot = ""; targets = ( 5D82366E1B0CE05B005A9EF3 /* react-native-performance */, 6478985E1F38BF9100DA1C12 /* react-native-performance-tvOS */, ); }; /* End PBXProject section */ /* Begin PBXSourcesBuildPhase section */ 5D82366B1B0CE05B005A9EF3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 93CE2D3D25AF808F00589E8F /* RNPerformanceManager.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 6478985B1F38BF9100DA1C12 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 93CE2D3E25AF808F00589E8F /* RNPerformanceManager.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin XCBuildConfiguration section */ 5D8236811B0CE05B005A9EF3 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; }; name = Debug; }; 5D8236821B0CE05B005A9EF3 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; 5D8236841B0CE05B005A9EF3 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../../React/**", "$(SRCROOT)/../react-native/React/**", "$(SRCROOT)/node_modules/react-native/React/**", ); OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; }; name = Debug; }; 5D8236851B0CE05B005A9EF3 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../../React/**", "$(SRCROOT)/../react-native/React/**", "$(SRCROOT)/node_modules/react-native/React/**", ); OTHER_LDFLAGS = "-ObjC"; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; }; name = Release; }; 647898651F38BF9100DA1C12 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_TESTABILITY = YES; OTHER_LDFLAGS = "-ObjC"; SDKROOT = appletvos; SKIP_INSTALL = YES; TVOS_DEPLOYMENT_TARGET = 10.2; }; name = Debug; }; 647898661F38BF9100DA1C12 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; OTHER_LDFLAGS = "-ObjC"; SDKROOT = appletvos; SKIP_INSTALL = YES; TVOS_DEPLOYMENT_TARGET = 10.2; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 5D82366A1B0CE05B005A9EF3 /* Build configuration list for PBXProject "react-native-performance" */ = { isa = XCConfigurationList; buildConfigurations = ( 5D8236811B0CE05B005A9EF3 /* Debug */, 5D8236821B0CE05B005A9EF3 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 5D8236831B0CE05B005A9EF3 /* Build configuration list for PBXNativeTarget "react-native-performance" */ = { isa = XCConfigurationList; buildConfigurations = ( 5D8236841B0CE05B005A9EF3 /* Debug */, 5D8236851B0CE05B005A9EF3 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 647898671F38BF9100DA1C12 /* Build configuration list for PBXNativeTarget "react-native-performance-tvOS" */ = { isa = XCConfigurationList; buildConfigurations = ( 647898651F38BF9100DA1C12 /* Debug */, 647898661F38BF9100DA1C12 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 5D8236671B0CE05B005A9EF3 /* Project object */; } ================================================ FILE: packages/react-native-performance/react-native-performance.xcodeproj/xcshareddata/xcschemes/react-native-performance-tvOS.xcscheme ================================================ ================================================ FILE: packages/react-native-performance/react-native-performance.xcodeproj/xcshareddata/xcschemes/react-native-performance.xcscheme ================================================ ================================================ FILE: packages/react-native-performance/src/NativeRNPerformanceManager.ts ================================================ import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport'; import { TurboModuleRegistry } from 'react-native'; export interface Spec extends TurboModule { // Events addListener: (eventName: string) => void; removeListeners: (count: number) => void; } export default TurboModuleRegistry.get('RNPerformanceManager'); ================================================ FILE: packages/react-native-performance/src/event-emitter.ts ================================================ type Callback = (entry: T) => void; export const createEventEmitter = () => { const callbacks = new Set>(); const addEventListener = (callback: Callback) => { callbacks.add(callback); }; const removeEventListener = (callback: Callback) => { callbacks.delete(callback); }; const emit = (event: T) => { callbacks.forEach((callback) => { callback(event); }); }; return { addEventListener, removeEventListener, emit, }; }; ================================================ FILE: packages/react-native-performance/src/index.ts ================================================ import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; import { PerformanceReactNativeMark, PerformanceMetric, } from './performance-entry'; import { installResourceLogger, uninstallResourceLogger, } from './resource-logger'; import { PerformanceObserver, addEntry, performance } from './instance'; declare const global: { __turboModuleProxy: null | {}; RN$Bridgeless?: boolean; }; const isTurboModuleEnabled = global.RN$Bridgeless || global.__turboModuleProxy != null; const RNPerformanceManager = isTurboModuleEnabled ? require('./NativeRNPerformanceManager').default : NativeModules.RNPerformanceManager; if (Platform.OS === 'android' || RNPerformanceManager) { const emitter = new NativeEventEmitter(RNPerformanceManager); emitter.addListener('mark', (data) => { addEntry( new PerformanceReactNativeMark(data.name, data.startTime, data.detail) ); }); emitter.addListener('metric', (data) => { addEntry( new PerformanceMetric(data.name, { startTime: data.startTime, value: data.value, detail: data.detail, }) ); }); } export default performance; export type Performance = typeof performance; export const setResourceLoggingEnabled = (enabled = true) => { if (enabled) { //@ts-ignore installResourceLogger(globalThis, performance, addEntry); } else { uninstallResourceLogger(globalThis); } }; export { PerformanceObserver }; export type { EntryType, PerformanceMark, PerformanceMeasure, PerformanceMetric, PerformanceEntry, PerformanceReactNativeMark, PerformanceResourceTiming, } from './performance-entry'; ================================================ FILE: packages/react-native-performance/src/instance.ts ================================================ import { createPerformance } from './performance'; export const { PerformanceObserver, addEntry, performance } = createPerformance(); ================================================ FILE: packages/react-native-performance/src/performance-entry.ts ================================================ type MarkOptions = { startTime?: number; detail?: any; }; type MetricOptions = { startTime: number; value: string | number; detail?: any; }; type MeasureOptions = { startTime?: number; detail?: any; duration?: number; }; export type EntryType = | 'mark' | 'measure' | 'resource' | 'metric' | 'react-native-mark'; export class PerformanceEntry { name: string; entryType: EntryType; startTime: number; duration: number; constructor( name: string, entryType: EntryType, startTime: number, duration: number ) { this.name = name; this.entryType = entryType; this.startTime = startTime; this.duration = duration; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, }; } } export class PerformanceMark extends PerformanceEntry { detail?: any; constructor(markName: string, markOptions: MarkOptions = {}) { super(markName, 'mark', markOptions.startTime, 0); this.detail = markOptions.detail; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, detail: this.detail, }; } } export class PerformanceReactNativeMark extends PerformanceEntry { detail?: any; constructor(name: string, startTime: number, detail: any) { super(name, 'react-native-mark', startTime, 0); this.detail = detail; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, detail: this.detail, }; } } export class PerformanceMetric extends PerformanceEntry { value: string | number; detail?: any; constructor(name: string, metricOptions: MetricOptions) { super(name, 'metric', metricOptions.startTime, 0); this.value = metricOptions.value; this.detail = metricOptions.detail; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, detail: this.detail, value: this.value, }; } } export class PerformanceMeasure extends PerformanceEntry { detail?: any; constructor(measureName: string, measureOptions: MeasureOptions = {}) { super( measureName, 'measure', measureOptions.startTime, measureOptions.duration ); this.detail = measureOptions.detail; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, detail: this.detail, }; } } export class PerformanceResourceTiming extends PerformanceEntry { initiatorType?: string; responseEnd: number; fetchStart: number; transferSize: number; connectEnd: number; connectStart: number; decodedBodySize: number; domainLookupEnd: number; domainLookupStart: number; encodedBodySize: number; redirectEnd: number; redirectStart: number; requestStart: number; responseStart: number; secureConnectionStart?: number; serverTiming: number[]; workerStart: number; workerTiming: number[]; constructor({ name, startTime, duration, initiatorType, responseEnd, transferSize, }: { name?: string; startTime?: number; duration?: number; initiatorType?: string; responseEnd?: number; transferSize?: number; } = {}) { super(name, 'resource', startTime, duration); this.initiatorType = initiatorType; this.fetchStart = startTime; this.responseEnd = responseEnd; this.transferSize = transferSize; this.connectEnd = 0; this.connectStart = 0; this.decodedBodySize = 0; this.domainLookupEnd = 0; this.domainLookupStart = 0; this.encodedBodySize = 0; this.redirectEnd = 0; this.redirectStart = 0; this.requestStart = 0; this.responseStart = 0; this.secureConnectionStart = 0; this.serverTiming = []; this.transferSize = 0; this.workerStart = 0; this.workerTiming = []; } toJSON() { return { name: this.name, entryType: this.entryType, startTime: this.startTime, duration: this.duration, initiatorType: this.initiatorType, fetchStart: this.fetchStart, responseEnd: this.responseEnd, transferSize: this.transferSize, connectEnd: this.connectEnd, connectStart: this.connectStart, decodedBodySize: this.decodedBodySize, domainLookupEnd: this.domainLookupEnd, domainLookupStart: this.domainLookupStart, encodedBodySize: this.encodedBodySize, redirectEnd: this.redirectEnd, redirectStart: this.redirectStart, requestStart: this.requestStart, responseStart: this.responseStart, secureConnectionStart: this.secureConnectionStart, serverTiming: this.serverTiming, workerStart: this.workerStart, workerTiming: this.workerTiming, }; } } ================================================ FILE: packages/react-native-performance/src/performance-observer.ts ================================================ import type { EntryType, PerformanceEntry } from './performance-entry'; type ObserveOptionType1 = { entryTypes: EntryType[]; }; type ObserveOptionType2 = { type: EntryType; buffered?: boolean; }; export class PerformanceObserverEntryList { entries: PerformanceEntry[]; constructor(entries: PerformanceEntry[]) { this.entries = entries; } getEntries() { return this.entries.slice(0); } getEntriesByType(type: EntryType) { return this.entries.filter((entry) => entry.entryType === type); } getEntriesByName(name: string, type?: EntryType) { return this.entries.filter( (entry) => entry.name === name && (!type || entry.entryType === type) ); } } const SUPPORTED_ENTRY_TYPES = [ 'mark', 'measure', 'metric', 'react-native-mark', 'resource', ]; const sortByStartTime = (a, b) => a.startTime - b.startTime; const OBSERVER_TYPE_SINGLE = 'single'; const OBSERVER_TYPE_MULTIPLE = 'multiple'; export const createPerformanceObserver = ({ addEventListener, removeEventListener, getEntriesByType, }) => class PerformanceObserver { callback: ( list: PerformanceObserverEntryList, observer: PerformanceObserver ) => void; buffer: PerformanceEntry[]; entryTypes: Set; timer?: number; observerType: | null | typeof OBSERVER_TYPE_SINGLE | typeof OBSERVER_TYPE_MULTIPLE; static supportedEntryTypes = SUPPORTED_ENTRY_TYPES; constructor( callback: ( list: PerformanceObserverEntryList, observer: PerformanceObserver ) => void ) { this.callback = callback; this.buffer = []; this.timer = null; this.entryTypes = new Set(); this.observerType = null; } emitRecords = () => { this.callback(new PerformanceObserverEntryList(this.takeRecords()), this); }; scheduleEmission() { if (this.timer === null) { this.timer = requestAnimationFrame(() => { this.timer = null; this.emitRecords(); }); } } receiveRecord = (entry: PerformanceEntry) => { if (this.entryTypes.has(entry.entryType)) { this.buffer.push(entry); this.scheduleEmission(); } }; observe(options: ObserveOptionType1): void; observe(options: ObserveOptionType2): void; observe(options: any) { if (!options || (!options.entryTypes && !options.type)) { throw new TypeError( "Failed to execute 'observe' on 'PerformanceObserver': An observe() call must include either entryTypes or type arguments." ); } if (options.entryTypes && options.type) { throw new TypeError( "Failed to execute 'observe' on 'PerformanceObserver': An observe() call must not include both entryTypes and type arguments." ); } if (options.entryTypes) { if (this.observerType === OBSERVER_TYPE_SINGLE) { throw new Error( 'This PerformanceObserver has performed observe({type:...}, therefore it cannot perform observe({entryTypes:...})' ); } if (!Array.isArray(options.entryTypes)) { throw new TypeError('entryTypes argument must be an array'); } this.observerType = OBSERVER_TYPE_MULTIPLE; this.entryTypes = new Set(options.entryTypes); this.buffer = []; if (options.buffered) { console.warn( 'The PerformanceObserver does not support buffered flag with the entryTypes argument.' ); } } else { if (this.observerType === OBSERVER_TYPE_MULTIPLE) { throw new Error( 'This PerformanceObserver has performed observe({entryTypes:...}, therefore it cannot perform observe({type:...})' ); } this.observerType = OBSERVER_TYPE_SINGLE; this.entryTypes.add(options.type); if (options.buffered) { this.buffer = getEntriesByType(options.type); this.scheduleEmission(); } } this.entryTypes.forEach((entryType) => { if (!SUPPORTED_ENTRY_TYPES.includes(entryType)) { console.warn( `The entry type '${entryType}' does not exist or isn't supported.` ); } }); addEventListener(this.receiveRecord); } disconnect() { removeEventListener(this.receiveRecord); this.entryTypes = new Set(); this.observerType = null; this.buffer = []; if (this.timer !== null) { cancelAnimationFrame(this.timer); this.timer = null; } } takeRecords() { const entries = this.buffer.sort(sortByStartTime); this.buffer = []; return entries; } }; ================================================ FILE: packages/react-native-performance/src/performance.ts ================================================ import { createEventEmitter } from './event-emitter'; import { createPerformanceObserver } from './performance-observer'; import { EntryType, PerformanceMark, PerformanceMeasure, PerformanceMetric, PerformanceEntry, PerformanceReactNativeMark, PerformanceResourceTiming, } from './performance-entry'; // @ts-ignore export const defaultNow: () => number = global.performance.now.bind( // @ts-ignore global.performance ); export type MarkOptions = { startTime?: number; detail?: any; }; export type MeasureOptions = { start?: string | number; end?: string | number; duration?: number; detail?: any; }; export type StartOrMeasureOptions = string | MeasureOptions | undefined; export type MetricOptions = { startTime: number; detail: any; value: number | string; }; export type ValueOrOptions = number | string | MetricOptions; export const createPerformance = (now: () => number = defaultNow) => { const timeOrigin = now(); const { addEventListener, removeEventListener, emit } = createEventEmitter(); const marks = new Map(); let entries: PerformanceEntry[] = []; function addEntry(entry: T): T { entries.push(entry); if (entry.entryType === 'mark' || entry.entryType === 'react-native-mark') { marks.set(entry.name, entry.startTime); } emit(entry); return entry; } const removeEntries = (type: EntryType, name?: string) => { entries = entries.filter((entry) => { if (entry.entryType === type && (!name || entry.name === name)) { marks.delete(entry.name); return false; } return true; }); }; const mark = (markName: string, markOptions: MarkOptions = {}) => addEntry( new PerformanceMark(markName, { startTime: 'startTime' in markOptions && markOptions.startTime !== undefined ? markOptions.startTime : now(), detail: markOptions.detail, }) ); const clearMarks = (name?: string) => removeEntries('mark', name); const clearMeasures = (name?: string) => removeEntries('measure', name); const clearMetrics = (name?: string) => removeEntries('metric', name); const clearResourceTimings = (name?: string) => removeEntries('resource', name); const convertMarkToTimestamp = (markOrTimestamp: string | number) => { switch (typeof markOrTimestamp) { case 'string': { if (!marks.has(markOrTimestamp)) { throw new Error( `Failed to execute 'measure' on 'Performance': The mark '${markOrTimestamp}' does not exist.` ); } return marks.get(markOrTimestamp); } case 'number': { return markOrTimestamp; } default: throw new TypeError( `Failed to execute 'measure' on 'Performance': Expected mark name or timestamp, got '${markOrTimestamp}'.` ); } }; const measure = ( measureName: string, startOrMeasureOptions?: StartOrMeasureOptions, endMark?: string | number ) => { let start = 0; let end = 0; let detail: any; if ( startOrMeasureOptions && typeof startOrMeasureOptions === 'object' && startOrMeasureOptions.constructor == Object ) { if (endMark) { throw new TypeError( `Failed to execute 'measure' on 'Performance': The measureOptions and endMark arguments may not be combined.` ); } if (!startOrMeasureOptions.start && !startOrMeasureOptions.end) { throw new TypeError( `Failed to execute 'measure' on 'Performance': At least one of the start and end option must be passed.` ); } if ( startOrMeasureOptions.start && startOrMeasureOptions.end && startOrMeasureOptions.duration ) { throw new TypeError( `Failed to execute 'measure' on 'Performance': Cannot send start, end and duration options together.` ); } detail = startOrMeasureOptions.detail; if (startOrMeasureOptions && startOrMeasureOptions.end) { end = convertMarkToTimestamp(startOrMeasureOptions.end); } else if ( startOrMeasureOptions && startOrMeasureOptions.start && startOrMeasureOptions.duration ) { end = convertMarkToTimestamp(startOrMeasureOptions.start) + convertMarkToTimestamp(startOrMeasureOptions.duration); } else { end = now(); } if (startOrMeasureOptions && startOrMeasureOptions.start) { start = convertMarkToTimestamp(startOrMeasureOptions.start); } else if ( startOrMeasureOptions && startOrMeasureOptions.end && startOrMeasureOptions.duration ) { start = convertMarkToTimestamp(startOrMeasureOptions.end) - convertMarkToTimestamp(startOrMeasureOptions.duration); } else { start = timeOrigin; } } else { if (endMark) { end = convertMarkToTimestamp(endMark); } else { end = now(); } if (typeof startOrMeasureOptions === 'string') { start = convertMarkToTimestamp(startOrMeasureOptions); } else { start = timeOrigin; } } return addEntry( new PerformanceMeasure(measureName, { detail, startTime: start, duration: end - start, }) ); }; const metric = (name: string, valueOrOptions: ValueOrOptions) => { let value: string | number; let startTime: number | undefined; let detail: any; if ( typeof valueOrOptions === 'object' && valueOrOptions.constructor == Object ) { if (!valueOrOptions.value) { throw new TypeError( `Failed to execute 'metric' on 'Performance': The value option must be passed.` ); } value = valueOrOptions.value; startTime = valueOrOptions.startTime; detail = valueOrOptions.detail; } else if ( typeof valueOrOptions === 'undefined' || valueOrOptions === null ) { throw new TypeError( `Failed to execute 'metric' on 'Performance': The value option must be passed.` ); } else { value = valueOrOptions as string | number; } return addEntry( new PerformanceMetric(name, { startTime: startTime ? startTime : now(), value, detail, }) ); }; const getEntries = () => entries.slice(0); const getEntriesByName = (name: string, type?: EntryType) => entries.filter( (entry) => entry.name === name && (!type || entry.entryType === type) ); function getEntriesByType(type: 'measure'): PerformanceMeasure[]; function getEntriesByType(type: 'mark'): PerformanceMark[]; function getEntriesByType(type: 'resource'): PerformanceResourceTiming[]; function getEntriesByType(type: 'metric'): PerformanceMetric[]; function getEntriesByType( type: 'react-native-mark' ): PerformanceReactNativeMark[]; function getEntriesByType(type: EntryType) { return entries.filter((entry) => entry.entryType === type); } const PerformanceObserver = createPerformanceObserver({ addEventListener, removeEventListener, getEntriesByType, }); return { PerformanceObserver, addEntry, performance: { timeOrigin, now, mark, clearMarks, measure, clearMeasures, metric, clearMetrics, clearResourceTimings, getEntries, getEntriesByName, getEntriesByType, }, }; }; export type Performance = ReturnType['performance']; ================================================ FILE: packages/react-native-performance/src/resource-logger.ts ================================================ import { PerformanceResourceTiming } from './performance-entry'; import type { PerformanceEntry } from './performance-entry'; import type { Performance } from './performance'; interface XMLHttpRequestType extends XMLHttpRequest { new (...args: any): XMLHttpRequestType; performanceOriginal: XMLHttpRequest; performanceStartTime?: number; responseURL: string; responseHeaders: string[]; } interface Context { XMLHttpRequest: XMLHttpRequestType; } export const installResourceLogger = ( context: Context, performance: Performance, addEntry: (entry: PerformanceEntry) => PerformanceEntry ) => { if (context.XMLHttpRequest && !context.XMLHttpRequest.performanceOriginal) { class XMLHttpRequest extends context.XMLHttpRequest { constructor(...args: any) { super(...args); this.performanceStartTime = null; super.addEventListener('readystatechange', () => { if (this.readyState === this.DONE) { if (this.responseURL && this.responseHeaders) { const responseEnd = performance.now(); const contentLength = Object.entries(this.responseHeaders).find( ([header]) => header.toLowerCase() === 'content-length' ); addEntry( new PerformanceResourceTiming({ name: this.responseURL, startTime: this.performanceStartTime, duration: responseEnd - this.performanceStartTime, initiatorType: 'xmlhttprequest', responseEnd, transferSize: contentLength ? parseInt(contentLength[1]) : 0, }) ); } } }); } open(...args: any) { this.performanceStartTime = performance.now(); //@ts-ignore super.open(...args); } } XMLHttpRequest.performanceOriginal = context.XMLHttpRequest; context.XMLHttpRequest = XMLHttpRequest; } }; export const uninstallResourceLogger = (context: any) => { if (context.XMLHttpRequest && context.XMLHttpRequest.performanceOriginal) { context.XMLHttpRequest = context.XMLHttpRequest.performanceOriginal; } }; ================================================ FILE: packages/react-native-performance/test/README.md ================================================ # Tests These tests are based on the [`web-platform-tests` project](https://web-platform-tests.org) under the [3-Clause BSD License](https://github.com/web-platform-tests/wpt/blob/master/LICENSE.md). Copyright 2019 [web-platform-tests contributors](https://github.com/web-platform-tests/wpt/graphs/contributors). ## Running ```bash yarn test ``` ================================================ FILE: packages/react-native-performance/test/performance-entry.spec.ts ================================================ import { createPerformance } from '../src/performance'; test('PerformanceEntry.toJSON()', () => { const { performance } = createPerformance(); performance.mark('markName'); performance.measure('measureName'); const entries = performance.getEntries(); const performanceEntryKeys = ['name', 'entryType', 'startTime', 'duration']; for (let i = 0; i < entries.length; ++i) { expect(typeof entries[i].toJSON).toBe('function'); const json = entries[i].toJSON(); expect(typeof json).toBe('object'); for (const key of performanceEntryKeys) { expect(json[key]).toBe(entries[i][key]); } } }); ================================================ FILE: packages/react-native-performance/test/performance-now.spec.ts ================================================ import { createPerformance } from '../src/performance'; describe('as a polyfill', () => { afterEach(() => { jest.restoreAllMocks(); }); test('performance.now() does not cause infinite recursion', () => { const { performance } = createPerformance(); // In react-native we can just polyfill the whole global object with `global.performance = performance` // Doing the same in Node has no effect. The test would pass even without any change to `performance.ts` jest // @ts-ignore .spyOn(global.performance, 'now') .mockImplementation(performance.now.bind(performance)); // @ts-ignore expect(() => global.performance.now()).not.toThrow(); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/buffered-false.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver', () => { test('PerformanceObserver without buffered flag set to false cannot see past entries', (done) => { const { performance, PerformanceObserver } = createPerformance(); performance.mark('foo'); // Use a timeout to ensure the remainder of the test runs after the entry is created. setTimeout(() => { // Observer with buffered flag set to false should not see entry. new PerformanceObserver(() => { throw new Error('Should not have observed any entry!'); }).observe({ type: 'mark', buffered: false }); // Use a timeout to give time to the observer. setTimeout(done, 100); }, 0); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/buffered-flag-after-timeout.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver', () => { test('PerformanceObserver with buffered flag sees entry after timeout', (done) => { const { performance, PerformanceObserver } = createPerformance(); performance.mark('foo'); setTimeout(() => { // After a timeout, PerformanceObserver should still receive entry if using the buffered flag. new PerformanceObserver((list) => { const entries = list.getEntries(); expect(entries.length).toBe(1); expect(entries[0].entryType).toBe('mark'); done(); }).observe({ type: 'mark', buffered: true }); }, 100); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/buffered-flag.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver', () => { test('PerformanceObserver with buffered flag should see past and future entries', (done) => { const { performance, PerformanceObserver } = createPerformance(); for (let i = 0; i < 50; i++) performance.mark('foo' + i); let marksCreated = 50; let marksReceived = 0; new PerformanceObserver((list) => { marksReceived += list.getEntries().length; if (marksCreated < 100) { performance.mark('bar' + marksCreated); marksCreated++; } if (marksReceived == 100) done(); }).observe({ type: 'mark', buffered: true }); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/disconnect-removes-observed-types.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries } from './helpers'; describe('PerformanceObserver', () => { test('Types observed are forgotten when disconnect() is called', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver((entryList) => { // There should be no mark entry. checkEntries(entryList.getEntries(), [ { entryType: 'measure', name: 'b' }, ]); done(); }); observer.observe({ type: 'mark' }); // Disconnect the observer. observer.disconnect(); // Now, only observe measure. observer.observe({ type: 'measure' }); performance.mark('a'); performance.measure('b'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/disconnect.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver', () => { test('disconnected callbacks must not be invoked', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver(() => { throw new Error('This callback must not be invoked'); }); observer.observe({ entryTypes: ['mark', 'measure'] }); observer.disconnect(); performance.mark('mark1'); performance.measure('measure1'); setTimeout(done, 2000); }); test('disconnecting an unconnected observer is a no-op', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => true); obs.disconnect(); obs.disconnect(); }); test('An observer disconnected after a mark must not have its callback invoked', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver(() => { throw new Error('This callback must not be invoked'); }); observer.observe({ entryTypes: ['mark'] }); performance.mark('mark1'); observer.disconnect(); performance.mark('mark2'); setTimeout(done, 2000); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/entries-sort.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries, checkSorted, wait } from './helpers'; describe('PerformanceObserver', () => { test('getEntries, getEntriesByType, getEntriesByName sort order', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver((entryList) => { const stored_entries = entryList.getEntries(); const stored_entries_by_type = entryList.getEntriesByType('mark'); const stored_entries_by_name = entryList.getEntriesByName('name-repeat'); checkSorted(stored_entries); checkEntries(stored_entries, [ { entryType: 'measure', name: 'measure1' }, { entryType: 'measure', name: 'measure2' }, { entryType: 'measure', name: 'measure3' }, { entryType: 'measure', name: 'name-repeat' }, { entryType: 'mark', name: 'mark1' }, { entryType: 'mark', name: 'mark2' }, { entryType: 'measure', name: 'measure-matching-mark2-1' }, { entryType: 'measure', name: 'measure-matching-mark2-2' }, { entryType: 'mark', name: 'name-repeat' }, { entryType: 'mark', name: 'name-repeat' }, ]); checkSorted(stored_entries_by_type); checkEntries(stored_entries_by_type, [ { entryType: 'mark', name: 'mark1' }, { entryType: 'mark', name: 'mark2' }, { entryType: 'mark', name: 'name-repeat' }, { entryType: 'mark', name: 'name-repeat' }, ]); checkSorted(stored_entries_by_name); checkEntries(stored_entries_by_name, [ { entryType: 'measure', name: 'name-repeat' }, { entryType: 'mark', name: 'name-repeat' }, { entryType: 'mark', name: 'name-repeat' }, ]); observer.disconnect(); done(); }); observer.observe({ entryTypes: ['mark', 'measure'] }); performance.mark('mark1'); performance.measure('measure1'); wait(); // Ensure mark1 !== mark2 startTime by making sure performance.now advances. performance.mark('mark2'); performance.measure('measure2'); performance.measure('measure-matching-mark2-1', 'mark2'); wait(); // Ensure mark2 !== mark3 startTime by making sure performance.now advances. performance.mark('name-repeat'); performance.measure('measure3'); performance.measure('measure-matching-mark2-2', 'mark2'); wait(); // Ensure name-repeat startTime will differ. performance.mark('name-repeat'); wait(); // Ensure name-repeat startTime will differ. performance.measure('name-repeat'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/get-entries.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries } from './helpers'; describe('PerformanceObserver', () => { test('getEntries, getEntriesByType and getEntriesByName work', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver((entryList) => { checkEntries(entryList.getEntries(), [ { entryType: 'mark', name: 'mark1' }, ]); checkEntries(entryList.getEntriesByType('mark'), [ { entryType: 'mark', name: 'mark1' }, ]); expect(entryList.getEntriesByType('measure').length).toBe(0); // @ts-ignore expect(entryList.getEntriesByType('234567').length).toBe(0); checkEntries(entryList.getEntriesByName('mark1'), [ { entryType: 'mark', name: 'mark1' }, ]); expect(entryList.getEntriesByName('mark2').length).toBe(0); expect(entryList.getEntriesByName('234567').length).toBe(0); checkEntries(entryList.getEntriesByName('mark1', 'mark'), [ { entryType: 'mark', name: 'mark1' }, ]); expect(entryList.getEntriesByName('mark1', 'measure').length).toBe(0); expect(entryList.getEntriesByName('mark2', 'measure').length).toBe(0); // @ts-ignore expect(entryList.getEntriesByName('mark1', '234567').length).toBe(0); observer.disconnect(); done(); }); observer.observe({ entryTypes: ['mark'] }); performance.mark('mark1'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/helpers.ts ================================================ // Vendored from https://github.com/web-platform-tests/wpt/blob/master/performance-timeline/performanceobservers.js // Compares a performance entry to a predefined one // perfEntriesToCheck is an array of performance entries from the user agent // expectedEntries is an array of performance entries minted by the test export function checkEntries(perfEntriesToCheck, expectedEntries) { function findMatch(pe) { // we match based on entryType and name for (var i = expectedEntries.length - 1; i >= 0; i--) { var ex = expectedEntries[i]; if (ex.entryType === pe.entryType && ex.name === pe.name) { return ex; } } return null; } expect(perfEntriesToCheck.length).toBe(expectedEntries.length); perfEntriesToCheck.forEach(function (pe1) { expect(findMatch(pe1)).not.toBe(null); }); } // Waits for performance.now to advance. Since precision reduction might // cause it to return the same value across multiple calls. export function wait() { // @ts-ignore const now = global.performance.now(); // @ts-ignore while (now === global.performance.now()) continue; } // Ensure the entries list is sorted by startTime. export function checkSorted(entries) { expect(entries.length).not.toBe(0); if (!entries.length) return; var lastStartTime = entries[0].startTime; for (var i = 1; i < entries.length; ++i) { var currStartTime = entries[i].startTime; expect(lastStartTime).toBeLessThanOrEqual(currStartTime); lastStartTime = currStartTime; } } export function muteConsoleWarn() { beforeAll(() => { const originalWarn = console.warn; console.warn = () => {}; // @ts-ignore console.warn.original = originalWarn; }); afterAll(() => { // @ts-ignore console.warn = console.warn.original; }); } ================================================ FILE: packages/react-native-performance/test/performance-observer/mark-measure.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries } from './helpers'; describe('PerformanceObserver', () => { test('entries are observable', (done) => { const { performance, PerformanceObserver } = createPerformance(); let stored_entries = []; const observer = new PerformanceObserver((entryList) => { stored_entries = stored_entries.concat(entryList.getEntries()); if (stored_entries.length >= 4) { checkEntries(stored_entries, [ { entryType: 'mark', name: 'mark1' }, { entryType: 'mark', name: 'mark2' }, { entryType: 'measure', name: 'measure1' }, { entryType: 'measure', name: 'measure2' }, ]); observer.disconnect(); done(); } }); observer.observe({ entryTypes: ['mark', 'measure'] }); performance.mark('mark1'); performance.mark('mark2'); performance.measure('measure1'); performance.measure('measure2'); }); test('mark entries are observable', (done) => { const { performance, PerformanceObserver } = createPerformance(); let mark_entries = []; const observer = new PerformanceObserver((entryList) => { mark_entries = mark_entries.concat(entryList.getEntries()); if (mark_entries.length >= 2) { checkEntries(mark_entries, [ { entryType: 'mark', name: 'mark1' }, { entryType: 'mark', name: 'mark2' }, ]); observer.disconnect(); done(); } }); observer.observe({ entryTypes: ['mark'] }); performance.mark('mark1'); performance.mark('mark2'); }); test('measure entries are observable', (done) => { const { performance, PerformanceObserver } = createPerformance(); let measure_entries = []; const observer = new PerformanceObserver((entryList) => { measure_entries = measure_entries.concat(entryList.getEntries()); if (measure_entries.length >= 2) { checkEntries(measure_entries, [ { entryType: 'measure', name: 'measure1' }, { entryType: 'measure', name: 'measure2' }, ]); observer.disconnect(); done(); } }); observer.observe({ entryTypes: ['measure'] }); performance.measure('measure1'); performance.measure('measure2'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/multiple-buffered-flag-observers.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver', () => { test('Multiple PerformanceObservers with buffered flag see all entries', () => { const { performance, PerformanceObserver } = createPerformance(); // The first promise waits for one buffered flag observer to receive 3 entries. const promise1 = new Promise((resolve1) => { let numObserved1 = 0; new PerformanceObserver((_, obs) => { // This buffered flag observer is constructed after a regular observer detects a mark. new PerformanceObserver((list) => { numObserved1 += list.getEntries().length; if (numObserved1 == 3) resolve1(null); }).observe({ type: 'mark', buffered: true }); obs.disconnect(); }).observe({ entryTypes: ['mark'] }); performance.mark('foo'); }); // The second promise waits for another buffered flag observer to receive 3 entries. const promise2 = new Promise((resolve2) => { setTimeout(() => { let numObserved2 = 0; // This buffered flag observer is constructed after a delay of 100ms. new PerformanceObserver((list) => { numObserved2 += list.getEntries().length; if (numObserved2 == 3) resolve2(null); }).observe({ type: 'mark', buffered: true }); }, 100); performance.mark('bar'); }); performance.mark('meow'); // Pass if and only if both buffered observers received all 3 mark entries. return Promise.all([promise1, promise2]); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/observe-repeated-type.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries } from './helpers'; describe('PerformanceObserver', () => { test("Two calls of observe() with the same 'type' cause override", (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver((entryList) => { checkEntries(entryList.getEntries(), [ { entryType: 'mark', name: 'early' }, ]); observer.disconnect(); done(); }); performance.mark('early'); // This call will not trigger anything. observer.observe({ type: 'mark' }); // This call should override the previous call and detect the early mark. observer.observe({ type: 'mark', buffered: true }); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/observe-type.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { muteConsoleWarn } from './helpers'; describe('PerformanceObserver', () => { muteConsoleWarn(); test("Calling observe() without 'type' or 'entryTypes' throws a TypeError", () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); // @ts-ignore expect(() => obs.observe({})).toThrow(TypeError); // @ts-ignore expect(() => obs.observe({ entryType: ['mark', 'measure'] })).toThrow( TypeError ); }); test('Calling observe() with entryTypes and then type should throw an InvalidModificationError', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); obs.observe({ entryTypes: ['mark'] }); expect(() => obs.observe({ type: 'measure' })).toThrow(); }); test('Calling observe() with type and then entryTypes should throw an InvalidModificationError', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); obs.observe({ type: 'mark' }); expect(() => obs.observe({ entryTypes: ['measure'] })).toThrow(); }); test('Passing in unknown values to type does not throw an exception', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); // Definitely not an entry type. // @ts-ignore obs.observe({ type: 'this-cannot-match-an-entryType' }); // Close to an entry type, but not quite. // @ts-ignore obs.observe({ type: 'marks' }); }); test('observe() with different type values stacks', (done) => { const { performance, PerformanceObserver } = createPerformance(); let observedMark = 0; let observedMeasure = 0; const observer = new PerformanceObserver(function (entryList) { observedMark |= entryList .getEntries() .filter((entry) => entry.entryType === 'mark').length; observedMeasure |= entryList .getEntries() .filter((entry) => entry.entryType === 'measure').length; // Only conclude the test once we receive both entries! if (observedMark && observedMeasure) { observer.disconnect(); done(); } }); observer.observe({ type: 'mark' }); observer.observe({ type: 'measure' }); performance.mark('mark1'); performance.measure('measure1'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/observe.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { PerformanceObserverEntryList } from '../../src/performance-observer'; import { checkEntries, muteConsoleWarn } from './helpers'; describe('PerformanceObserver', () => { muteConsoleWarn(); test('entryTypes must be a sequence or throw a TypeError', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); // @ts-ignore expect(() => obs.observe({ entryTypes: 'mark' })).toThrow(TypeError); }); test('Unknown entryTypes do not throw an exception', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); // @ts-ignore obs.observe({ entryTypes: ['this-cannot-match-an-entryType'] }); // @ts-ignore obs.observe({ entryTypes: ['marks', 'navigate', 'resources'] }); }); test('Filter unsupported entryType entryType names within the entryTypes sequence', () => { const { PerformanceObserver } = createPerformance(); const obs = new PerformanceObserver(() => {}); // @ts-ignore obs.observe({ entryTypes: ['mark', 'this-cannot-match-an-entryType'] }); // @ts-ignore obs.observe({ entryTypes: ['this-cannot-match-an-entryType', 'mark'] }); // @ts-ignore obs.observe({ entryTypes: ['mark'], others: true }); }); test('Check observer callback parameter and this values', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver(function (entryList, obs) { expect(entryList).toBeInstanceOf(PerformanceObserverEntryList); expect(obs).toBeInstanceOf(PerformanceObserver); expect(observer).toBe(this); expect(observer).toBe(obs); expect(this).toBe(obs); observer.disconnect(); done(); }); performance.clearMarks(); observer.observe({ entryTypes: ['mark'] }); performance.mark('mark1'); }); test('replace observer if already present', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver(function (entryList) { checkEntries(entryList.getEntries(), [ { entryType: 'measure', name: 'measure1' }, ]); observer.disconnect(); done(); }); performance.clearMarks(); observer.observe({ entryTypes: ['mark'] }); observer.observe({ entryTypes: ['measure'] }); performance.mark('mark1'); performance.measure('measure1'); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/supported-entry-types.spec.ts ================================================ import { createPerformance } from '../../src/performance'; describe('PerformanceObserver.supportedEntryTypes', () => { it('exists and returns entries in alphabetical order', () => { const { PerformanceObserver } = createPerformance(); expect(PerformanceObserver.supportedEntryTypes).not.toBeUndefined(); const types = PerformanceObserver.supportedEntryTypes; for (let i = 1; i < types.length; i++) { expect(types[i - 1] < types[i]).toBe(true); } }); it('caches result', () => { const { PerformanceObserver } = createPerformance(); expect(PerformanceObserver.supportedEntryTypes).toBe( PerformanceObserver.supportedEntryTypes ); }); }); ================================================ FILE: packages/react-native-performance/test/performance-observer/take-records.spec.ts ================================================ import { createPerformance } from '../../src/performance'; import { checkEntries } from './helpers'; describe('PerformanceObserver', () => { test('takeRecords()', (done) => { const { performance, PerformanceObserver } = createPerformance(); const observer = new PerformanceObserver(() => { throw new Error('This callback should not have been called.'); }); let entries = observer.takeRecords(); checkEntries(entries, []); // No records before observe observer.observe({ entryTypes: ['mark'] }); entries = observer.takeRecords(); checkEntries(entries, []); // No records just from observe performance.mark('a'); performance.mark('b'); entries = observer.takeRecords(); checkEntries(entries, [ { entryType: 'mark', name: 'a' }, { entryType: 'mark', name: 'b' }, ]); performance.mark('c'); performance.mark('d'); performance.mark('e'); entries = observer.takeRecords(); checkEntries(entries, [ { entryType: 'mark', name: 'c' }, { entryType: 'mark', name: 'd' }, { entryType: 'mark', name: 'e' }, ]); entries = observer.takeRecords(); checkEntries(entries, []); // No entries right after takeRecords observer.disconnect(); done(); }); }); ================================================ FILE: packages/react-native-performance/test/setup.js ================================================ const perf = require('perf_hooks').performance; global.performance.now = perf.now.bind(perf); ================================================ FILE: packages/react-native-performance/test/user-timing-3.spec.ts ================================================ import { createPerformance } from '../src/performance'; test('Performance.measure with start', () => { const mockNow = jest.fn(); mockNow.mockReturnValue(1); const { performance } = createPerformance(mockNow); mockNow.mockReturnValue(2); performance.mark('start'); mockNow.mockReturnValue(8); const measure1 = performance.measure('measure1', 'start'); const measure2 = performance.measure('measure2', { start: 'start' }); expect(measure1.startTime).toBe(2); expect(measure2.startTime).toBe(2); expect(measure1.duration).toBe(6); expect(measure2.duration).toBe(6); }); test('Performance.measure with end', () => { const mockNow = jest.fn(); mockNow.mockReturnValue(1); const { performance } = createPerformance(mockNow); mockNow.mockReturnValue(5); performance.mark('end'); mockNow.mockReturnValue(8); const measure1 = performance.measure('measure1', null, 'end'); const measure2 = performance.measure('measure2', { end: 'end', detail: 'lol', }); expect(measure1.startTime).toBe(1); expect(measure2.startTime).toBe(1); expect(measure1.duration).toBe(4); expect(measure2.duration).toBe(4); }); test('Performance.measure with duration', () => { const mockNow = jest.fn(); mockNow.mockReturnValue(1); const { performance } = createPerformance(mockNow); mockNow.mockReturnValue(2); performance.mark('start'); mockNow.mockReturnValue(5); performance.mark('end'); mockNow.mockReturnValue(8); const measure1 = performance.measure('measure2', { duration: 1, end: 'end', }); expect(measure1.startTime).toBe(4); expect(measure1.duration).toBe(1); const measure2 = performance.measure('measure2', { duration: 2, start: 'start', }); expect(measure2.startTime).toBe(2); expect(measure2.duration).toBe(2); }); ================================================ FILE: packages/react-native-performance/tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "exclude": ["test"] } ================================================ FILE: packages/react-native-performance/tsconfig.json ================================================ { "extends": "../../tsconfig.json" } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "baseUrl": ".", "allowUnreachableCode": false, "allowUnusedLabels": false, "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "jsx": "react", "lib": ["esnext"], "module": "esnext", "moduleResolution": "node", "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "noImplicitUseStrict": false, "noStrictGenericChecks": false, "noUnusedLocals": true, "noUnusedParameters": true, "skipLibCheck": true, "target": "esnext" }, "exclude": ["examples"] }